You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@mynewt.apache.org by st...@apache.org on 2016/09/29 01:34:08 UTC

[01/49] incubator-mynewt-core git commit: final cbmem fixes

Repository: incubator-mynewt-core
Updated Branches:
  refs/heads/develop 797b3412d -> ac676a909


final cbmem fixes


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/ac676a90
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/ac676a90
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/ac676a90

Branch: refs/heads/develop
Commit: ac676a909d48673f1a127e20bb37ee7e66cd909e
Parents: 09aec6c
Author: Sterling Hughes <st...@apache.org>
Authored: Wed Sep 28 18:31:03 2016 -0700
Committer: Sterling Hughes <st...@apache.org>
Committed: Wed Sep 28 18:32:22 2016 -0700

----------------------------------------------------------------------
 sys/log/pkg.yml    | 2 +-
 sys/log/src/log.c  | 2 +-
 util/cbmem/pkg.yml | 2 +-
 3 files changed, 3 insertions(+), 3 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/ac676a90/sys/log/pkg.yml
----------------------------------------------------------------------
diff --git a/sys/log/pkg.yml b/sys/log/pkg.yml
index b931e43..fbab46a 100644
--- a/sys/log/pkg.yml
+++ b/sys/log/pkg.yml
@@ -26,7 +26,7 @@ pkg.keywords:
 
 pkg.deps:
     - kernel/os
-    - libs/util
+    - util/cbmem
 pkg.deps.LOG_FCB:
     - hw/hal
     - fs/fcb

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/ac676a90/sys/log/src/log.c
----------------------------------------------------------------------
diff --git a/sys/log/src/log.c b/sys/log/src/log.c
index 6160626..23714f6 100644
--- a/sys/log/src/log.c
+++ b/sys/log/src/log.c
@@ -25,7 +25,7 @@
 #include "sysinit/sysinit.h"
 #include "syscfg/syscfg.h"
 #include "os/os.h"
-#include "util/cbmem.h"
+#include "cbmem/cbmem.h"
 #include "log/log.h"
 
 #if MYNEWT_VAL(LOG_CLI)

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/ac676a90/util/cbmem/pkg.yml
----------------------------------------------------------------------
diff --git a/util/cbmem/pkg.yml b/util/cbmem/pkg.yml
index 9957805..0031a6c 100644
--- a/util/cbmem/pkg.yml
+++ b/util/cbmem/pkg.yml
@@ -17,7 +17,7 @@
 # under the License.
 #
 
-pkg.name: libs/util
+pkg.name: util/cbmem
 pkg.description: Library containing miscellaneous utilities.
 pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
 pkg.homepage: "http://mynewt.apache.org/"


[12/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/test/pkg.yml
----------------------------------------------------------------------
diff --git a/libs/os/test/pkg.yml b/libs/os/test/pkg.yml
deleted file mode 100644
index e517618..0000000
--- a/libs/os/test/pkg.yml
+++ /dev/null
@@ -1,30 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you 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.
-#
-pkg.name: libs/os/test
-pkg.type: unittest
-pkg.description: "OS unit tests."
-pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
-pkg.homepage: "http://mynewt.apache.org/"
-pkg.keywords:
-
-pkg.deps: 
-    - libs/os
-    - libs/testutil
-
-pkg.deps.SELFTEST:
-    - libs/console/stub

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/test/src/arch/cortex_m4/os_test_arch_arm.c
----------------------------------------------------------------------
diff --git a/libs/os/test/src/arch/cortex_m4/os_test_arch_arm.c b/libs/os/test/src/arch/cortex_m4/os_test_arch_arm.c
deleted file mode 100644
index 35134f7..0000000
--- a/libs/os/test/src/arch/cortex_m4/os_test_arch_arm.c
+++ /dev/null
@@ -1,27 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include "testutil/testutil.h"
-#include "os_test_priv.h"
-
-void
-os_test_restart(void)
-{
-    tu_restart();
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/test/src/arch/sim/os_test_arch_sim.c
----------------------------------------------------------------------
diff --git a/libs/os/test/src/arch/sim/os_test_arch_sim.c b/libs/os/test/src/arch/sim/os_test_arch_sim.c
deleted file mode 100644
index 3b6cfbf..0000000
--- a/libs/os/test/src/arch/sim/os_test_arch_sim.c
+++ /dev/null
@@ -1,52 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include <stdio.h>
-#include <setjmp.h>
-#include <signal.h>
-#include <string.h>
-#include <sys/time.h>
-#include "testutil/testutil.h"
-#include "os/os.h"
-#include "os_test_priv.h"
-
-void
-os_test_restart(void)
-{
-    struct sigaction sa;
-    struct itimerval it;
-    int rc;
-
-    g_os_started = 0;
-
-    memset(&sa, 0, sizeof sa);
-    sa.sa_handler = SIG_IGN;
-
-    sigaction(SIGALRM, &sa, NULL);
-    sigaction(SIGVTALRM, &sa, NULL);
-
-    memset(&it, 0, sizeof(it));
-    rc = setitimer(ITIMER_VIRTUAL, &it, NULL);
-    if (rc != 0) {
-        perror("Cannot set itimer");
-        abort();
-    }
-
-    tu_restart();
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/test/src/callout_test.c
----------------------------------------------------------------------
diff --git a/libs/os/test/src/callout_test.c b/libs/os/test/src/callout_test.c
deleted file mode 100644
index 4e3811d..0000000
--- a/libs/os/test/src/callout_test.c
+++ /dev/null
@@ -1,330 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
- 
-#include "testutil/testutil.h"
-#include "os/os.h"
-#include "os_test_priv.h"
-#include "os/os_eventq.h"
-#include "os/os_callout.h"
-#include "os/os_time.h"
-
-/* Task 1 for sending */
-#define CALLOUT_STACK_SIZE        (5120)
-#define SEND_CALLOUT_TASK_PRIO        (1)
-struct os_task callout_task_struct_send;
-os_stack_t callout_task_stack_send[CALLOUT_STACK_SIZE];
-
-#define RECEIVE_CALLOUT_TASK_PRIO        (2)
-struct os_task callout_task_struct_receive;
-os_stack_t callout_task_stack_receive[CALLOUT_STACK_SIZE];
-
-/* Delearing variables for callout_func */
-struct os_callout_func callout_func_test;
-
-/* The event to be sent*/
-struct os_eventq callout_evq;
-struct os_event callout_ev;
-
-/* The callout_stop task */
-#define SEND_STOP_CALLOUT_TASK_PRIO        (3)
-struct os_task callout_task_struct_stop_send;
-os_stack_t callout_task_stack_stop_send[CALLOUT_STACK_SIZE];
-
-#define RECEIVE_STOP_CALLOUT_TASK_PRIO        (4)
-struct os_task callout_task_struct_stop_receive;
-os_stack_t callout_task_stack_stop_receive[CALLOUT_STACK_SIZE];
-
-/* Delearing variables for callout_stop_func */
-#define MULTI_SIZE    (2)
-struct os_callout_func callout_func_stop_test[MULTI_SIZE];
-
-/* The event to be sent*/
-struct os_eventq callout_stop_evq[MULTI_SIZE];
-struct os_event callout_stop_ev;
-
-/* Declearing varables for callout_speak */
-#define SPEAK_CALLOUT_TASK_PRIO        (5)
-struct os_task callout_task_struct_speak;
-os_stack_t callout_task_stack_speak[CALLOUT_STACK_SIZE];
-
-/* Declearing varaibles for listen */
-#define LISTEN_CALLOUT_TASK_PRIO        (6)
-struct os_task callout_task_struct_listen;
-os_stack_t callout_task_stack_listen[CALLOUT_STACK_SIZE];
-
-struct os_callout_func callout_func_speak;
-
-/* Global variables to be used by the callout functions */
-int p;
-int q;
-int t;
-/* This is the function for callout_init*/
-void
-my_callout_func(void *arg)
-{
-    p = 4;
-}
-
-/* This is the function for callout_init of stop test_case*/
-void
-my_callout_stop_func(void *arg)
-{
-    q = 1;
-}
-/* This is the function for callout_init for speak test_case*/
-void
-my_callout_speak_func(void *arg)
-{
-    t = 2;
-}
-
-/* This is a callout task to send data */
-void
-callout_task_send(void *arg )
-{
-   int i;
-    /* Should say whether callout is armed or not */
-    i= os_callout_queued(&callout_func_test.cf_c);
-    TEST_ASSERT(i == 0);
-
-    /* Arm the callout */
-    i = os_callout_reset(&callout_func_test.cf_c, OS_TICKS_PER_SEC/ 50);
-    TEST_ASSERT_FATAL(i == 0);
-
-    /* Should say whether callout is armed or not */
-    i = os_callout_queued(&callout_func_test.cf_c);
-    TEST_ASSERT(i == 1);
-
-    /* Send the callout */ 
-    os_time_delay(OS_TICKS_PER_SEC );
-}
-
-/* This is the callout to receive data */
-void
-callout_task_receive( void *arg)
-{
-    int i;
-    struct os_event *event;
-    struct os_callout_func *callout;
-    os_time_t now;
-    os_time_t tm;
-    os_sr_t sr; 
-    /* Recieve using the os_eventq_poll */
-    event = os_eventq_poll(&callout_func_test.cf_c.c_evq, 1, OS_WAIT_FOREVER);
-    TEST_ASSERT(event->ev_type ==  OS_EVENT_T_TIMER);
-    TEST_ASSERT(event->ev_arg == NULL);
-    callout = (struct os_callout_func *)event;
-    TEST_ASSERT(callout->cf_func == my_callout_func);
-
-    /* Should say whether callout is armed or not */
-    i = os_callout_queued(&callout_func_test.cf_c);
-    TEST_ASSERT(i == 0);
-
-    OS_ENTER_CRITICAL(sr);
-    now = os_time_get();
-    tm = os_callout_wakeup_ticks(now);
-    TEST_ASSERT(tm == OS_TIMEOUT_NEVER);
-    OS_EXIT_CRITICAL(sr);
-    
-    /* Finishes the test when OS has been started */
-    os_test_restart();
-
-}
-
-/* This is callout to send the stop_callout */
-void
-callout_task_stop_send( void *arg)
-{
-    int k;
-    int j;    
-     /* Should say whether callout is armed or not */
-    for(k = 0; k<MULTI_SIZE; k++){
-        j = os_callout_queued(&callout_func_stop_test[k].cf_c);
-        TEST_ASSERT(j == 0);
-    }
-
-
-    /* Show that  callout is not armed after calling callout_stop */
-    for(k = 0; k<MULTI_SIZE; k++){
-        os_callout_stop(&callout_func_stop_test[k].cf_c);
-        j = os_callout_queued(&callout_func_stop_test[k].cf_c);
-        TEST_ASSERT(j == 0);
-    }
-    /* Arm the callout */
-    for(k = 0; k<MULTI_SIZE; k++){
-        j = os_callout_reset(&callout_func_stop_test[k].cf_c, OS_TICKS_PER_SEC/ 50);
-        TEST_ASSERT_FATAL(j == 0);
-    }
-    os_time_delay( OS_TICKS_PER_SEC );
-}
-
-/* This is the callout to receive stop_callout data */
-void
-callout_task_stop_receive( void *arg )
-{
-    int k;
-    struct os_event *event;
-    struct os_callout_func *callout;
-    /* Recieving using the os_eventq_poll */
-    for(k=0; k<MULTI_SIZE; k++){
-        event = os_eventq_poll(&callout_func_stop_test[k].cf_c.c_evq, 1,
-           OS_WAIT_FOREVER);
-        TEST_ASSERT(event->ev_type ==  OS_EVENT_T_TIMER);
-        TEST_ASSERT(event->ev_arg == NULL);
-        callout = (struct os_callout_func *)event;
-        TEST_ASSERT(callout->cf_func == my_callout_stop_func);
-
-
-     }
-     
-    /* Show that event is removed from the queued after calling callout_stop */
-    for(k=0; k<MULTI_SIZE; k++){
-        os_callout_stop(&callout_func_stop_test[k].cf_c);
-        /* Testing that the event has been removed from queue */
-        TEST_ASSERT_FATAL(1); 
-     }
-    /* Finishes the test when OS has been started */
-    os_test_restart();
-
-}
-
-/* This is a callout task to send data */
-void
-callout_task_stop_speak( void *arg )
-{
-    int i;
-    /* Arm the callout */
-    i = os_callout_reset(&callout_func_speak.cf_c, OS_TICKS_PER_SEC/ 50);
-    TEST_ASSERT_FATAL(i == 0);
-
-    /* should say whether callout is armed or not */
-    i = os_callout_queued(&callout_func_speak.cf_c);
-    TEST_ASSERT(i == 1);
-
-    os_callout_stop(&callout_func_speak.cf_c);
-    
-    /* Send the callout */ 
-    os_time_delay(OS_TICKS_PER_SEC/ 100 );
-    /* Finishes the test when OS has been started */
-    os_test_restart();
-}
-
-void
-callout_task_stop_listen( void *arg )
-{
-    struct os_event *event;
-    struct os_callout_func *callout;
-    event = os_eventq_get(callout_func_speak.cf_c.c_evq);
-    TEST_ASSERT_FATAL(0);
-    callout = (struct os_callout_func *)event;
-    TEST_ASSERT(callout->cf_func == my_callout_speak_func);
-
-}
-
-/* Test case to test the basics of the callout */
-TEST_CASE(callout_test)
-{
-
-    /* Initializing the OS */
-    os_init();
-    
-    /* Initialize the sending task */
-    os_task_init(&callout_task_struct_send, "callout_task_send",
-        callout_task_send, NULL, SEND_CALLOUT_TASK_PRIO, OS_WAIT_FOREVER,
-        callout_task_stack_send, CALLOUT_STACK_SIZE);
-
-    /* Initialize the receive task */
-    os_task_init(&callout_task_struct_receive, "callout_task_receive",
-        callout_task_receive, NULL, RECEIVE_CALLOUT_TASK_PRIO, OS_WAIT_FOREVER,
-        callout_task_stack_receive, CALLOUT_STACK_SIZE);
-
-    os_eventq_init(&callout_evq);
-    
-    /* Initialize the callout function */
-    os_callout_func_init(&callout_func_test, &callout_evq,
-        my_callout_func, NULL);
-
-    /* Does not return until OS_restart is called */
-    os_start();
-}
-
-/* Test case of the callout_task_stop */
-TEST_CASE(callout_test_stop)
-{
-    int k;
-    /* Initializing the OS */
-    os_init();
-
-    /* Initialize the sending task */
-    os_task_init(&callout_task_struct_stop_send, "callout_task_stop_send",
-        callout_task_stop_send, NULL, SEND_STOP_CALLOUT_TASK_PRIO, OS_WAIT_FOREVER,
-        callout_task_stack_stop_send, CALLOUT_STACK_SIZE);
-
-    /* Initialize the receiving task */
-    os_task_init(&callout_task_struct_stop_receive, "callout_task_stop_receive",
-        callout_task_stop_receive, NULL, RECEIVE_STOP_CALLOUT_TASK_PRIO,
-        OS_WAIT_FOREVER, callout_task_stack_stop_receive, CALLOUT_STACK_SIZE);
-
-    for(k = 0; k< MULTI_SIZE; k++){
-        os_eventq_init(&callout_stop_evq[k]);
-    }
-    
-    /* Initialize the callout function */
-    for(k = 0; k<MULTI_SIZE; k++){
-        os_callout_func_init(&callout_func_stop_test[k], &callout_stop_evq[k],
-           my_callout_stop_func, NULL);
-    }
-
-    /* Does not return until OS_restart is called */
-    os_start();
-
-}
-
-/* Test case to test case for speak and listen */
-TEST_CASE(callout_test_speak)
-{
-    /* Initializing the OS */
-    os_init();
-    
-    /* Initialize the sending task */
-    os_task_init(&callout_task_struct_speak, "callout_task_speak",
-        callout_task_stop_speak, NULL, SPEAK_CALLOUT_TASK_PRIO, OS_WAIT_FOREVER,
-        callout_task_stack_speak, CALLOUT_STACK_SIZE);
-
-    /* Initialize the receive task */
-    os_task_init(&callout_task_struct_listen, "callout_task_listen",
-        callout_task_stop_listen, NULL, LISTEN_CALLOUT_TASK_PRIO, OS_WAIT_FOREVER,
-        callout_task_stack_listen, CALLOUT_STACK_SIZE);
-
-    os_eventq_init(&callout_evq);
-    
-    /* Initialize the callout function */
-    os_callout_func_init(&callout_func_speak, &callout_evq,
-        my_callout_speak_func, NULL);    
-    /* Does not return until OS_restart is called */
-    os_start();
-
-}
-
-TEST_SUITE(os_callout_test_suite)
-{   
-    callout_test();
-    callout_test_stop();
-    callout_test_speak();
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/test/src/eventq_test.c
----------------------------------------------------------------------
diff --git a/libs/os/test/src/eventq_test.c b/libs/os/test/src/eventq_test.c
deleted file mode 100644
index 3fceb0e..0000000
--- a/libs/os/test/src/eventq_test.c
+++ /dev/null
@@ -1,416 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
- 
-#include <string.h>
-#include "testutil/testutil.h"
-#include "os/os.h"
-#include "os_test_priv.h"
-#include "os/os_eventq.h"
-
-#define MY_STACK_SIZE        (5120)
-#define POLL_STACK_SIZE        (4096)
-/* Task 1 sending task */
-/* Define task stack and task object */
-#define SEND_TASK_PRIO        (1)
-struct os_task eventq_task_s;
-os_stack_t eventq_task_stack_s[MY_STACK_SIZE];
-
-/* Task 2 receiving task */
-#define RECEIVE_TASK_PRIO     (2)
-struct os_task eventq_task_r;
-os_stack_t eventq_task_stack_r[MY_STACK_SIZE];
-
-struct os_eventq my_eventq;
-
-#define SIZE_MULTI_EVENT        (4)
-struct os_eventq multi_eventq[SIZE_MULTI_EVENT];
-
-/* This is to set the events we will use below */
-struct os_event g_event;
-struct os_event m_event[SIZE_MULTI_EVENT];
-
-/* Setting the event to send and receive multiple data */
-uint8_t my_event_type = 1;
-
-/* Setting up data for the poll */
-/* Define the task stack for the eventq_task_poll_send */
-#define SEND_TASK_POLL_PRIO        (3)
-struct os_task eventq_task_poll_s;
-os_stack_t eventq_task_stack_poll_s[POLL_STACK_SIZE];
-
-/* Define the task stack for the eventq_task_poll_receive */
-#define RECEIVE_TASK_POLL_PRIO     (4)
-struct os_task eventq_task_poll_r;
-os_stack_t eventq_task_stack_poll_r[POLL_STACK_SIZE ];
-
-/* Setting the data for the poll timeout */
-/* Define the task stack for the eventq_task_poll_timeout_send */
-#define SEND_TASK_POLL_TIMEOUT_PRIO        (5)
-struct os_task eventq_task_poll_timeout_s;
-os_stack_t eventq_task_stack_poll_timeout_s[POLL_STACK_SIZE];
-
-/* Define the task stack for the eventq_task_poll_receive */
-#define RECEIVE_TASK_POLL_TIMEOUT_PRIO     (6)
-struct os_task eventq_task_poll_timeout_r;
-os_stack_t eventq_task_stack_poll_timeout_r[POLL_STACK_SIZE];
-
-/* Setting the data for the poll single */
-/* Define the task stack for the eventq_task_poll_single_send */
-#define SEND_TASK_POLL_SINGLE_PRIO        (7)
-struct os_task eventq_task_poll_single_s;
-os_stack_t eventq_task_stack_poll_single_s[POLL_STACK_SIZE];
-
-/* Define the task stack for the eventq_task_poll_single_receive */
-#define RECEIVE_TASK_POLL_SINGLE_PRIO     (8)
-struct os_task eventq_task_poll_single_r;
-os_stack_t eventq_task_stack_poll_single_r[POLL_STACK_SIZE];
-
-/* This is the task function  to send data */
-void
-eventq_task_send(void *arg)
-{
-    int i;
-
-    g_event.ev_queued = 0;
-    g_event.ev_type = my_event_type;
-    g_event.ev_arg = NULL;
-
-    os_eventq_put(&my_eventq, &g_event);
-
-    os_time_delay(OS_TICKS_PER_SEC / 2);
-
-    for (i = 0; i < SIZE_MULTI_EVENT; i++){
-        m_event[i].ev_type = i + 2;
-        m_event[i].ev_arg = NULL;
-
-        /* Put and send */
-        os_eventq_put(&multi_eventq[i], &m_event[i]);
-        os_time_delay(OS_TICKS_PER_SEC / 2);
-    }
-
-    /* This task sleeps until the receive task completes the test. */
-    os_time_delay(1000000);
-}
-
-/* This is the task function is the receiving function */
-void
-eventq_task_receive(void *arg)
-{
-    struct os_event *event;
-    int i;
-
-    event = os_eventq_get(&my_eventq);
-    TEST_ASSERT(event->ev_type == my_event_type);
-
-    /* Receiving multi event from the send task */
-    for (i = 0; i < SIZE_MULTI_EVENT; i++) {
-        event = os_eventq_get(&multi_eventq[i]);
-        TEST_ASSERT(event->ev_type == i + 2);
-    }
-
-    /* Finishes the test when OS has been started */
-    os_test_restart();
-}
-
-void
-eventq_task_poll_send(void *arg)
-{
-    struct os_eventq *eventqs[SIZE_MULTI_EVENT];
-    int i;
-
-    for (i = 0; i < SIZE_MULTI_EVENT; i++){
-        eventqs[i] = &multi_eventq[i];
-    }
-
-    for (i = 0; i < SIZE_MULTI_EVENT; i++){
-        m_event[i].ev_type = i + 10;
-        m_event[i].ev_arg = NULL;
-
-        /* Put and send */
-        os_eventq_put(eventqs[i], &m_event[i]);
-        os_time_delay(OS_TICKS_PER_SEC / 2);
-    }
-
-    /* This task sleeps until the receive task completes the test. */
-    os_time_delay(1000000);
-}
-
-void
-eventq_task_poll_receive(void *arg)
-{
-    struct os_eventq *eventqs[SIZE_MULTI_EVENT];
-    struct os_event *event;
-    int i;
-
-    for (i = 0; i < SIZE_MULTI_EVENT; i++){
-        eventqs[i] = &multi_eventq[i];
-    }
-
-    /* Recieving using the os_eventq_poll*/
-    for (i = 0; i < SIZE_MULTI_EVENT; i++) {
-        event = os_eventq_poll(eventqs, SIZE_MULTI_EVENT, OS_WAIT_FOREVER);
-        TEST_ASSERT(event->ev_type == i +10);
-    }
-
-    /* Finishes the test when OS has been started */
-    os_test_restart();
-
-}
-
-/* Sending with a time failure */
-void
-eventq_task_poll_timeout_send(void *arg)
-{
-    struct os_eventq *eventqs[SIZE_MULTI_EVENT];
-    int i;
-
-    for (i = 0; i < SIZE_MULTI_EVENT; i++){
-        eventqs[i] = &multi_eventq[i];
-    }
-
-    for (i = 0; i < SIZE_MULTI_EVENT; i++){
-         os_time_delay(OS_TICKS_PER_SEC);
-
-        /* Put and send */
-        os_eventq_put(eventqs[i], &m_event[i]);
-        os_time_delay(OS_TICKS_PER_SEC / 2);
-    }
-
-    /* This task sleeps until the receive task completes the test. */
-    os_time_delay(1000000);
-    
-}
-
-/* Receiving multiple event queues with a time failure */
-void
-eventq_task_poll_timeout_receive(void *arg)
-{
-    struct os_eventq *eventqs[SIZE_MULTI_EVENT];
-    struct os_event *event;
-    int i;
-
-    for (i = 0; i < SIZE_MULTI_EVENT; i++){
-        eventqs[i] = &multi_eventq[i];
-    }
-
-    /* Recieving using the os_eventq_poll_timeout*/
-    for (i = 0; i < SIZE_MULTI_EVENT; i++) {
-        event = os_eventq_poll(eventqs, SIZE_MULTI_EVENT, OS_TICKS_PER_SEC / 5);
-        TEST_ASSERT(event == NULL);
-    }
-
-    /* Finishes the test when OS has been started */
-    os_test_restart();
-
-}
-
-/* Sending a single event to poll */
-void
-eventq_task_poll_single_send(void *arg)
-{
-    struct os_eventq *eventqs[SIZE_MULTI_EVENT];
-    int i;
-    int position = 2;
-
-    for (i = 0; i < SIZE_MULTI_EVENT; i++){
-        eventqs[i] = &multi_eventq[i];
-    }
-
-    /* Put and send */
-    os_eventq_put(eventqs[position], &m_event[position]);
-    os_time_delay(OS_TICKS_PER_SEC / 2);
-
-    /* This task sleeps until the receive task completes the test. */
-    os_time_delay(1000000);
-}
-
-/* Recieving the single event */
-void
-eventq_task_poll_single_receive(void *arg)
-{
-    struct os_eventq *eventqs[SIZE_MULTI_EVENT];
-    struct os_event *event;
-    int i;
-
-    for (i = 0; i < SIZE_MULTI_EVENT; i++){
-        eventqs[i] = &multi_eventq[i];
-    }
-
-    /* Recieving using the os_eventq_poll*/
-    event = os_eventq_poll(eventqs, SIZE_MULTI_EVENT, OS_WAIT_FOREVER);
-    TEST_ASSERT(event->ev_type == 20);
-
-    /* Finishes the test when OS has been started */
-    os_test_restart();
-}
-
-TEST_CASE(event_test_sr)
-{
-    int i;
-
-    /* Initializing the OS */
-    os_init();
-    /* Initialize the task */
-    os_task_init(&eventq_task_s, "eventq_task_s", eventq_task_send, NULL,
-        SEND_TASK_PRIO, OS_WAIT_FOREVER, eventq_task_stack_s, MY_STACK_SIZE);
-
-    /* Receive events and check whether the eevnts are correctly received */
-    os_task_init(&eventq_task_r, "eventq_task_r", eventq_task_receive, NULL,
-        RECEIVE_TASK_PRIO, OS_WAIT_FOREVER, eventq_task_stack_r,
-        MY_STACK_SIZE);
-
-    os_eventq_init(&my_eventq);
-
-    for (i = 0; i < SIZE_MULTI_EVENT; i++){
-        os_eventq_init(&multi_eventq[i]);
-    }
-
-    /* Does not return until OS_restart is called */
-    os_start();
-
-}
-
-/* To test for the basic function of os_eventq_poll() */
-TEST_CASE(event_test_poll_sr)
-{
-    int i;
-
-    /* Initializing the OS */
-    os_init();
-    /* Initialize the task */
-    os_task_init(&eventq_task_poll_s, "eventq_task_poll_s", eventq_task_poll_send,
-        NULL, SEND_TASK_POLL_PRIO, OS_WAIT_FOREVER, eventq_task_stack_poll_s, 
-        POLL_STACK_SIZE);
-
-    /* Receive events and check whether the eevnts are correctly received */
-    os_task_init(&eventq_task_poll_r, "eventq_task_r", eventq_task_poll_receive,
-        NULL, RECEIVE_TASK_POLL_PRIO, OS_WAIT_FOREVER, eventq_task_stack_poll_r,
-        POLL_STACK_SIZE);
-
-    /* Initializing the eventqs. */
-    for (i = 0; i < SIZE_MULTI_EVENT; i++){
-        os_eventq_init(&multi_eventq[i]);
-    }
-
-    /* Does not return until OS_restart is called */
-    os_start();
-
-}
-
-/* Test case for poll timeout */
-TEST_CASE(event_test_poll_timeout_sr)
-{
-    int i;
-
-    /* Initializing the OS */
-    os_init();
-    /* Initialize the task */
-    os_task_init(&eventq_task_poll_timeout_s, "eventq_task_poll_timeout_s", 
-        eventq_task_poll_timeout_send, NULL, SEND_TASK_POLL_TIMEOUT_PRIO,
-        OS_WAIT_FOREVER, eventq_task_stack_poll_timeout_s, POLL_STACK_SIZE);
-
-    /* Receive events and check whether the eevnts are correctly received */
-    os_task_init(&eventq_task_poll_timeout_r, "eventq_task_timeout_r",
-        eventq_task_poll_timeout_receive, NULL, RECEIVE_TASK_POLL_TIMEOUT_PRIO,
-        OS_WAIT_FOREVER, eventq_task_stack_poll_timeout_r, POLL_STACK_SIZE);
-
-    /* Initializing the eventqs. */
-    for (i = 0; i < SIZE_MULTI_EVENT; i++){
-        os_eventq_init(&multi_eventq[i]);
-
-        m_event[i].ev_type = i + 10;
-        m_event[i].ev_arg = NULL;
-    }
-
-    /* Does not return until OS_restart is called */
-    os_start();
-
-}
-
-/* The case for poll single */
-/* Test case for poll timeout */
-TEST_CASE(event_test_poll_single_sr)
-{
-    int i;
-
-    /* Initializing the OS */
-    os_init();
-    /* Initialize the task */
-    os_task_init(&eventq_task_poll_single_s, "eventq_task_poll_single_s", 
-        eventq_task_poll_single_send, NULL, SEND_TASK_POLL_SINGLE_PRIO,
-        OS_WAIT_FOREVER, eventq_task_stack_poll_single_s, POLL_STACK_SIZE);
-
-    /* Receive events and check whether the eevnts are correctly received */
-    os_task_init(&eventq_task_poll_single_r, "eventq_task_single_r",
-        eventq_task_poll_single_receive, NULL, RECEIVE_TASK_POLL_SINGLE_PRIO,
-        OS_WAIT_FOREVER, eventq_task_stack_poll_single_r, POLL_STACK_SIZE);
-
-    for (i = 0; i < SIZE_MULTI_EVENT; i++){
-        os_eventq_init(&multi_eventq[i]);
-
-        m_event[i].ev_type = 10 * i;
-        m_event[i].ev_arg = NULL;
-    }
-
-    /* Does not return until OS_restart is called */
-    os_start();
-
-}
-
-/**
- * Tests eventq_poll() with a timeout of 0.  This should not involve the
- * scheduler at all, so it should work without starting the OS.
- */
-TEST_CASE(event_test_poll_0timo)
-{
-    struct os_eventq *eventqs[SIZE_MULTI_EVENT];
-    struct os_event *evp;
-    struct os_event ev;
-    int i;
-
-    for (i = 0; i < SIZE_MULTI_EVENT; i++){
-        os_eventq_init(&multi_eventq[i]);
-        eventqs[i] = &multi_eventq[i];
-    }
-
-    evp = os_eventq_poll(eventqs, SIZE_MULTI_EVENT, 0);
-    TEST_ASSERT(evp == NULL);
-
-    /* Ensure no eventq thinks a task is waiting on it. */
-    for (i = 0; i < SIZE_MULTI_EVENT; i++) {
-        TEST_ASSERT(eventqs[i]->evq_task == NULL);
-    }
-
-    /* Put an event on one of the queues. */
-    memset(&ev, 0, sizeof ev);
-    ev.ev_type = 1;
-    os_eventq_put(eventqs[3], &ev);
-
-    evp = os_eventq_poll(eventqs, SIZE_MULTI_EVENT, 0);
-    TEST_ASSERT(evp == &ev);
-}
-
-TEST_SUITE(os_eventq_test_suite)
-{
-    event_test_sr();
-    event_test_poll_sr();
-    event_test_poll_timeout_sr();
-    event_test_poll_single_sr();
-    event_test_poll_0timo();
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/test/src/mbuf_test.c
----------------------------------------------------------------------
diff --git a/libs/os/test/src/mbuf_test.c b/libs/os/test/src/mbuf_test.c
deleted file mode 100644
index dd4121d..0000000
--- a/libs/os/test/src/mbuf_test.c
+++ /dev/null
@@ -1,420 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include "testutil/testutil.h"
-#include "os/os.h"
-#include "os_test_priv.h"
-
-#include <string.h>
-
-/* 
- * NOTE: currently, the buffer size cannot be changed as some tests are
- * hard-coded for this size.
- */
-#define MBUF_TEST_POOL_BUF_SIZE     (256)
-#define MBUF_TEST_POOL_BUF_COUNT    (10)
-
-#define MBUF_TEST_DATA_LEN          (1024)
-
-static os_membuf_t os_mbuf_membuf[OS_MEMPOOL_SIZE(MBUF_TEST_POOL_BUF_SIZE,
-        MBUF_TEST_POOL_BUF_COUNT)];
-
-static struct os_mbuf_pool os_mbuf_pool;
-static struct os_mempool os_mbuf_mempool;
-static uint8_t os_mbuf_test_data[MBUF_TEST_DATA_LEN];
-
-static void
-os_mbuf_test_setup(void)
-{
-    int rc;
-    int i;
-
-    rc = os_mempool_init(&os_mbuf_mempool, MBUF_TEST_POOL_BUF_COUNT,
-            MBUF_TEST_POOL_BUF_SIZE, &os_mbuf_membuf[0], "mbuf_pool");
-    TEST_ASSERT_FATAL(rc == 0, "Error creating memory pool %d", rc);
-
-    rc = os_mbuf_pool_init(&os_mbuf_pool, &os_mbuf_mempool,
-            MBUF_TEST_POOL_BUF_SIZE, MBUF_TEST_POOL_BUF_COUNT);
-    TEST_ASSERT_FATAL(rc == 0, "Error creating mbuf pool %d", rc);
-
-    for (i = 0; i < sizeof os_mbuf_test_data; i++) {
-        os_mbuf_test_data[i] = i;
-    }
-}
-
-static void
-os_mbuf_test_misc_assert_sane(struct os_mbuf *om, void *data,
-                              int buflen, int pktlen, int pkthdr_len)
-{
-    uint8_t *data_min;
-    uint8_t *data_max;
-    int totlen;
-    int i;
-
-    TEST_ASSERT_FATAL(om != NULL);
-
-    if (OS_MBUF_IS_PKTHDR(om)) {
-        TEST_ASSERT(OS_MBUF_PKTLEN(om) == pktlen);
-    }
-
-    totlen = 0;
-    for (i = 0; om != NULL; i++) {
-        if (i == 0) {
-            TEST_ASSERT(om->om_len == buflen);
-            TEST_ASSERT(om->om_pkthdr_len == pkthdr_len);
-        }
-
-        data_min = om->om_databuf + om->om_pkthdr_len;
-        data_max = om->om_databuf + om->om_omp->omp_databuf_len - om->om_len;
-        TEST_ASSERT(om->om_data >= data_min && om->om_data <= data_max);
-
-        if (data != NULL) {
-            TEST_ASSERT(memcmp(om->om_data, data + totlen, om->om_len) == 0);
-        }
-
-        totlen += om->om_len;
-        om = SLIST_NEXT(om, om_next);
-    }
-
-    TEST_ASSERT(totlen == pktlen);
-}
-
-
-TEST_CASE(os_mbuf_test_alloc)
-{
-    struct os_mbuf *m;
-    int rc;
-
-    os_mbuf_test_setup();
-
-    m = os_mbuf_get(&os_mbuf_pool, 0);
-    TEST_ASSERT_FATAL(m != NULL, "Error allocating mbuf");
-
-    rc = os_mbuf_free(m);
-    TEST_ASSERT_FATAL(rc == 0, "Error free'ing mbuf %d", rc);
-}
-
-TEST_CASE(os_mbuf_test_get_pkthdr)
-{
-    struct os_mbuf *m;
- 
-    os_mbuf_test_setup();
-
-#if (MBUF_TEST_POOL_BUF_SIZE <= 256)
-    m = os_mbuf_get_pkthdr(&os_mbuf_pool, MBUF_TEST_POOL_BUF_SIZE - 1);
-    TEST_ASSERT_FATAL(m == NULL, "Error: should not have returned mbuf");
-#endif
-
-    m = os_mbuf_get(&os_mbuf_pool, MBUF_TEST_POOL_BUF_SIZE);
-    TEST_ASSERT_FATAL(m == NULL, "Error: should not have returned mbuf");
-}
-
-
-TEST_CASE(os_mbuf_test_dup)
-{
-    struct os_mbuf *om;
-    struct os_mbuf *om2;
-    struct os_mbuf *dup;
-    int rc;
-
-    os_mbuf_test_setup();
-
-    /* Test first allocating and duplicating a single mbuf */
-    om = os_mbuf_get(&os_mbuf_pool, 0);
-    TEST_ASSERT_FATAL(om != NULL, "Error allocating mbuf");
-
-    rc = os_mbuf_append(om, os_mbuf_test_data, 200);
-    TEST_ASSERT_FATAL(rc == 0);
-    os_mbuf_test_misc_assert_sane(om, os_mbuf_test_data, 200, 200, 0);
-
-    dup = os_mbuf_dup(om);
-    TEST_ASSERT_FATAL(dup != NULL, "NULL mbuf returned from dup");
-    TEST_ASSERT_FATAL(dup != om, "duplicate matches original.");
-    os_mbuf_test_misc_assert_sane(dup, os_mbuf_test_data, 200, 200, 0);
-
-    rc = os_mbuf_free(om);
-    TEST_ASSERT_FATAL(rc == 0, "Error free'ing mbuf om %d", rc);
-
-    rc = os_mbuf_free(dup);
-    TEST_ASSERT_FATAL(rc == 0, "Error free'ing mbuf dup %d", rc);
-
-    om = os_mbuf_get(&os_mbuf_pool, 0);
-    TEST_ASSERT_FATAL(om != NULL, "Error allocating mbuf");
-    rc = os_mbuf_append(om, os_mbuf_test_data, 200);
-    TEST_ASSERT_FATAL(rc == 0);
-    os_mbuf_test_misc_assert_sane(om, os_mbuf_test_data, 200, 200, 0);
-
-    om2 = os_mbuf_get(&os_mbuf_pool, 0);
-    TEST_ASSERT_FATAL(om2 != NULL, "Error allocating mbuf");
-    rc = os_mbuf_append(om2, os_mbuf_test_data + 200, 200);
-    TEST_ASSERT_FATAL(rc == 0);
-    os_mbuf_test_misc_assert_sane(om2, os_mbuf_test_data + 200, 200, 200, 0);
-
-    os_mbuf_concat(om, om2);
-    os_mbuf_test_misc_assert_sane(om, os_mbuf_test_data, 200, 400, 0);
-
-    dup = os_mbuf_dup(om);
-    TEST_ASSERT_FATAL(dup != NULL, "NULL mbuf returned from dup");
-    TEST_ASSERT_FATAL(dup != om, "Duplicate matches original");
-    TEST_ASSERT_FATAL(SLIST_NEXT(dup, om_next) != NULL,
-            "NULL chained element, duplicate should match original");
-
-    os_mbuf_test_misc_assert_sane(dup, os_mbuf_test_data, 200, 400, 0);
-
-    rc = os_mbuf_free_chain(om);
-    TEST_ASSERT_FATAL(rc == 0, "Cannot free mbuf chain %d", rc);
-
-    rc = os_mbuf_free_chain(dup);
-    TEST_ASSERT_FATAL(rc == 0, "Cannot free mbuf chain %d", rc);
-}
-
-TEST_CASE(os_mbuf_test_append)
-{
-    struct os_mbuf *om;
-    int rc;
-    uint8_t databuf[] = {0xa, 0xb, 0xc, 0xd};
-    uint8_t cmpbuf[] = {0xff, 0xff, 0xff, 0xff};
-
-    os_mbuf_test_setup();
-
-    om = os_mbuf_get(&os_mbuf_pool, 0);
-    TEST_ASSERT_FATAL(om != NULL, "Error allocating mbuf");
-    os_mbuf_test_misc_assert_sane(om, NULL, 0, 0, 0);
-
-    rc = os_mbuf_append(om, databuf, sizeof(databuf));
-    TEST_ASSERT_FATAL(rc == 0, "Cannot add %d bytes to mbuf",
-            sizeof(databuf));
-    os_mbuf_test_misc_assert_sane(om, databuf, sizeof databuf, sizeof databuf,
-                                  0);
-
-    memcpy(cmpbuf, OS_MBUF_DATA(om, uint8_t *), om->om_len);
-    TEST_ASSERT_FATAL(memcmp(cmpbuf, databuf, sizeof(databuf)) == 0,
-            "Databuf doesn't match cmpbuf");
-}
-
-TEST_CASE(os_mbuf_test_extend)
-{
-    struct os_mbuf *om;
-    void *v;
-
-    os_mbuf_test_setup();
-
-    /*** Series of successful extensions. */
-    om = os_mbuf_get_pkthdr(&os_mbuf_pool, 10);
-    TEST_ASSERT_FATAL(om != NULL);
-
-    TEST_ASSERT(OS_MBUF_TRAILINGSPACE(om) == 222);
-    TEST_ASSERT(SLIST_NEXT(om, om_next) == NULL);
-    os_mbuf_test_misc_assert_sane(om, NULL, 0, 0, 18);
-
-    v = os_mbuf_extend(om, 20);
-    TEST_ASSERT(v != NULL);
-    TEST_ASSERT(v == om->om_data);
-    TEST_ASSERT(om->om_len == 20);
-
-    TEST_ASSERT(OS_MBUF_TRAILINGSPACE(om) == 202);
-    TEST_ASSERT(SLIST_NEXT(om, om_next) == NULL);
-    os_mbuf_test_misc_assert_sane(om, NULL, 20, 20, 18);
-
-    v = os_mbuf_extend(om, 100);
-    TEST_ASSERT(v != NULL);
-    TEST_ASSERT(v == om->om_data + 20);
-    TEST_ASSERT(om->om_len == 120);
-
-    TEST_ASSERT(OS_MBUF_TRAILINGSPACE(om) == 102);
-    TEST_ASSERT(SLIST_NEXT(om, om_next) == NULL);
-    os_mbuf_test_misc_assert_sane(om, NULL, 120, 120, 18);
-
-    v = os_mbuf_extend(om, 101);
-    TEST_ASSERT(v != NULL);
-    TEST_ASSERT(v == om->om_data + 120);
-    TEST_ASSERT(om->om_len == 221);
-
-    TEST_ASSERT(OS_MBUF_TRAILINGSPACE(om) == 1);
-    TEST_ASSERT(SLIST_NEXT(om, om_next) == NULL);
-    os_mbuf_test_misc_assert_sane(om, NULL, 221, 221, 18);
-
-    v = os_mbuf_extend(om, 1);
-    TEST_ASSERT(v != NULL);
-    TEST_ASSERT(v == om->om_data + 221);
-    TEST_ASSERT(om->om_len == 222);
-
-    TEST_ASSERT(OS_MBUF_TRAILINGSPACE(om) == 0);
-    TEST_ASSERT(SLIST_NEXT(om, om_next) == NULL);
-    os_mbuf_test_misc_assert_sane(om, NULL, 222, 222, 18);
-
-    /* Overflow into next buffer. */
-    v = os_mbuf_extend(om, 1);
-    TEST_ASSERT(OS_MBUF_TRAILINGSPACE(om) == 0);
-    TEST_ASSERT(SLIST_NEXT(om, om_next) != NULL);
-
-    TEST_ASSERT(v == SLIST_NEXT(om, om_next)->om_data);
-    TEST_ASSERT(om->om_len == 222);
-    TEST_ASSERT(SLIST_NEXT(om, om_next)->om_len == 1);
-    os_mbuf_test_misc_assert_sane(om, NULL, 222, 223, 18);
-
-    /*** Attempt to extend by an amount larger than max buf size fails. */
-    v = os_mbuf_extend(om, 257);
-    TEST_ASSERT(v == NULL);
-    TEST_ASSERT(OS_MBUF_TRAILINGSPACE(om) == 0);
-    TEST_ASSERT(SLIST_NEXT(om, om_next) != NULL);
-
-    TEST_ASSERT(om->om_len == 222);
-    TEST_ASSERT(SLIST_NEXT(om, om_next)->om_len == 1);
-    os_mbuf_test_misc_assert_sane(om, NULL, 222, 223, 18);
-}
-
-TEST_CASE(os_mbuf_test_pullup)
-{
-    struct os_mbuf *om;
-    struct os_mbuf *om2;
-    int rc;
-
-    os_mbuf_test_setup();
-
-    /*** Free when too much os_mbuf_test_data is requested. */
-    om = os_mbuf_get_pkthdr(&os_mbuf_pool, 10);
-    TEST_ASSERT_FATAL(om != NULL);
-
-    om = os_mbuf_pullup(om, 1);
-    TEST_ASSERT(om == NULL);
-
-    /*** No effect when all os_mbuf_test_data is already at the start. */
-    om = os_mbuf_get_pkthdr(&os_mbuf_pool, 10);
-    TEST_ASSERT_FATAL(om != NULL);
-
-    rc = os_mbuf_append(om, os_mbuf_test_data, 1);
-    TEST_ASSERT_FATAL(rc == 0);
-    os_mbuf_test_misc_assert_sane(om, os_mbuf_test_data, 1, 1, 18);
-
-    om = os_mbuf_pullup(om, 1);
-    os_mbuf_test_misc_assert_sane(om, os_mbuf_test_data, 1, 1, 18);
-
-    /*** Spread os_mbuf_test_data across four mbufs. */
-    om2 = os_mbuf_get(&os_mbuf_pool, 10);
-    TEST_ASSERT_FATAL(om2 != NULL);
-    rc = os_mbuf_append(om2, os_mbuf_test_data + 1, 1);
-    TEST_ASSERT_FATAL(rc == 0);
-    os_mbuf_concat(om, om2);
-
-    om2 = os_mbuf_get(&os_mbuf_pool, 10);
-    TEST_ASSERT_FATAL(om2 != NULL);
-    rc = os_mbuf_append(om2, os_mbuf_test_data + 2, 1);
-    TEST_ASSERT_FATAL(rc == 0);
-    os_mbuf_concat(om, om2);
-
-    om2 = os_mbuf_get(&os_mbuf_pool, 10);
-    TEST_ASSERT_FATAL(om2 != NULL);
-    rc = os_mbuf_append(om2, os_mbuf_test_data + 3, 1);
-    TEST_ASSERT_FATAL(rc == 0);
-    os_mbuf_concat(om, om2);
-
-    TEST_ASSERT_FATAL(OS_MBUF_PKTLEN(om) == 4);
-
-    om = os_mbuf_pullup(om, 4);
-    os_mbuf_test_misc_assert_sane(om, os_mbuf_test_data, 4, 4, 18);
-
-    os_mbuf_free_chain(om);
-
-    /*** Require an allocation. */
-    om = os_mbuf_get_pkthdr(&os_mbuf_pool, 10);
-    TEST_ASSERT_FATAL(om != NULL);
-
-    om->om_data += 100;
-    rc = os_mbuf_append(om, os_mbuf_test_data, 100);
-    TEST_ASSERT_FATAL(rc == 0);
-
-    om2 = os_mbuf_get(&os_mbuf_pool, 10);
-    TEST_ASSERT_FATAL(om2 != NULL);
-    rc = os_mbuf_append(om2, os_mbuf_test_data + 100, 100);
-    TEST_ASSERT_FATAL(rc == 0);
-    os_mbuf_concat(om, om2);
-
-    om = os_mbuf_pullup(om, 200);
-    os_mbuf_test_misc_assert_sane(om, os_mbuf_test_data, 200, 200, 18);
-
-    /*** Partial pullup. */
-    om = os_mbuf_get_pkthdr(&os_mbuf_pool, 10);
-    TEST_ASSERT_FATAL(om != NULL);
-
-    om->om_data += 100;
-    rc = os_mbuf_append(om, os_mbuf_test_data, 100);
-    TEST_ASSERT_FATAL(rc == 0);
-
-    om2 = os_mbuf_get(&os_mbuf_pool, 10);
-    TEST_ASSERT_FATAL(om2 != NULL);
-    rc = os_mbuf_append(om2, os_mbuf_test_data + 100, 100);
-    TEST_ASSERT_FATAL(rc == 0);
-    os_mbuf_concat(om, om2);
-
-    om = os_mbuf_pullup(om, 150);
-    os_mbuf_test_misc_assert_sane(om, os_mbuf_test_data, 150, 200, 18);
-}
-
-TEST_CASE(os_mbuf_test_adj)
-{
-    struct os_mbuf *om;
-    int rc;
-
-    os_mbuf_test_setup();
-
-    om = os_mbuf_get_pkthdr(&os_mbuf_pool, 10);
-    TEST_ASSERT_FATAL(om != NULL);
-
-    rc = os_mbuf_append(om, os_mbuf_test_data, sizeof os_mbuf_test_data);
-    TEST_ASSERT_FATAL(rc == 0);
-
-    os_mbuf_test_misc_assert_sane(om, os_mbuf_test_data, 222,
-                                  sizeof os_mbuf_test_data, 18);
-
-    /* Remove from the front. */
-    os_mbuf_adj(om, 10);
-    os_mbuf_test_misc_assert_sane(om, os_mbuf_test_data + 10, 212,
-                                  sizeof os_mbuf_test_data - 10, 18);
-
-    /* Remove from the back. */
-    os_mbuf_adj(om, -10);
-    os_mbuf_test_misc_assert_sane(om, os_mbuf_test_data + 10, 212,
-                                  sizeof os_mbuf_test_data - 20, 18);
-
-    /* Remove entire first buffer. */
-    os_mbuf_adj(om, 212);
-    os_mbuf_test_misc_assert_sane(om, os_mbuf_test_data + 222, 0,
-                                  sizeof os_mbuf_test_data - 232, 18);
-
-    /* Remove next buffer. */
-    os_mbuf_adj(om, 256);
-    os_mbuf_test_misc_assert_sane(om, os_mbuf_test_data + 478, 0,
-                                  sizeof os_mbuf_test_data - 488, 18);
-
-    /* Remove more data than is present. */
-    os_mbuf_adj(om, 1000);
-    os_mbuf_test_misc_assert_sane(om, NULL, 0, 0, 18);
-}
-
-TEST_SUITE(os_mbuf_test_suite)
-{
-    os_mbuf_test_alloc();
-    os_mbuf_test_dup();
-    os_mbuf_test_append();
-    os_mbuf_test_pullup();
-    os_mbuf_test_extend();
-    os_mbuf_test_adj();
-    os_mbuf_test_get_pkthdr();
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/test/src/mempool_test.c
----------------------------------------------------------------------
diff --git a/libs/os/test/src/mempool_test.c b/libs/os/test/src/mempool_test.c
deleted file mode 100644
index cd17c90..0000000
--- a/libs/os/test/src/mempool_test.c
+++ /dev/null
@@ -1,227 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-#include <stdio.h>
-#include <string.h>
-#include "testutil/testutil.h"
-#include "os/os.h"
-#include "os_test_priv.h"
-
-/* Create a memory pool for testing */
-#define NUM_MEM_BLOCKS  (10)
-#define MEM_BLOCK_SIZE  (80)
-
-/* Limit max blocks for testing */
-#define MEMPOOL_TEST_MAX_BLOCKS     (128)
-
-#if OS_CFG_ALIGNMENT == OS_CFG_ALIGN_4
-int alignment = 4;
-#else
-int alignment = 8;
-#endif
-
-/* Test memory pool structure */
-struct os_mempool g_TstMempool;
-
-/* Test memory pool buffer */
-os_membuf_t TstMembuf[OS_MEMPOOL_SIZE(NUM_MEM_BLOCKS, MEM_BLOCK_SIZE)];
-
-/* Array of block pointers. */
-void *block_array[MEMPOOL_TEST_MAX_BLOCKS];
-
-int verbose = 0;
-
-static int
-mempool_test_get_pool_size(int num_blocks, int block_size)
-{
-    int mem_pool_size;
-
-#if OS_CFG_ALIGNMENT == OS_CFG_ALIGN_4
-    mem_pool_size = (num_blocks * ((block_size + 3)/4) * sizeof(os_membuf_t));
-#else
-    mem_pool_size = (num_blocks * ((block_size + 7)/8) * sizeof(os_membuf_t));
-#endif
-
-    return mem_pool_size;
-}
-
-static void
-mempool_test(int num_blocks, int block_size)
-{
-    int cnt;
-    int true_block_size;
-    int mem_pool_size;
-    uint32_t test_block;
-    uint8_t *tstptr;
-    void **free_ptr;
-    void *block;
-    os_error_t rc;
-
-    /* Check for too many blocks */
-    TEST_ASSERT(num_blocks <= MEMPOOL_TEST_MAX_BLOCKS);
-
-    rc = os_mempool_init(&g_TstMempool, num_blocks, MEM_BLOCK_SIZE, 
-                         &TstMembuf[0], "TestMemPool");
-    TEST_ASSERT_FATAL(rc == 0, "Error creating memory pool %d", rc);
-
-    TEST_ASSERT(g_TstMempool.mp_num_free == num_blocks,
-                "Number of free blocks not equal to total blocks!");
-
-    TEST_ASSERT(SLIST_FIRST(&g_TstMempool) == (void *)&TstMembuf[0],
-                "Free list pointer does not point to first block!");
-
-    mem_pool_size = mempool_test_get_pool_size(num_blocks, block_size);
-    TEST_ASSERT(mem_pool_size == sizeof(TstMembuf),
-                "Total memory pool size not correct! (%d vs %lu)",
-                mem_pool_size, (unsigned long)sizeof(TstMembuf));
-
-    /* Get the real block size */
-#if (OS_CFG_ALIGNMENT == OS_CFG_ALIGN_4)
-    true_block_size = (g_TstMempool.mp_block_size + 3) & ~3;
-#else
-    true_block_size = (g_TstMempool.mp_block_size + 7) & ~7;
-#endif
-
-    /* Traverse free list. Better add up to number of blocks! */
-    cnt = 0;
-    free_ptr = (void **)&TstMembuf;
-    tstptr = (uint8_t *)&TstMembuf;
-    while (1) {
-        /* Increment # of elements by 1 */
-        ++cnt;
-
-        /* If the free list is NULL, leave */
-        if (*free_ptr == NULL) {
-            break;
-        }
-
-        TEST_ASSERT(((uint8_t *)*free_ptr - (uint8_t *)free_ptr) ==
-                        true_block_size,
-                    "Free pointers are more than one block apart!");
-
-        /* Move to next memory block */
-        tstptr += true_block_size;
-
-        TEST_ASSERT(*free_ptr == (void *)tstptr,
-                    "Error: free_ptr=%p testptr=%p\n", *free_ptr, tstptr);
-
-        free_ptr = *free_ptr;
-    }
-
-    /* Last one in list better be NULL */
-    TEST_ASSERT(cnt == g_TstMempool.mp_num_blocks,
-                "Free list contains too many elements (%u)", cnt);
-
-    /* Get a block */
-    block = os_memblock_get(&g_TstMempool);
-    TEST_ASSERT(block != NULL,
-                "Error: get block fails when pool should have elements");
-
-    TEST_ASSERT(g_TstMempool.mp_num_free == (num_blocks-1),
-                "Number of free blocks incorrect (%u vs %u)",
-                g_TstMempool.mp_num_free, (num_blocks-1));
-
-    /* Put back the block */
-    rc = os_memblock_put(&g_TstMempool, block);
-    TEST_ASSERT(rc == 0, "Put block fails with error code=%d\n", rc);
-
-    TEST_ASSERT(g_TstMempool.mp_num_free == num_blocks,
-                "Number of free blocks incorrect (%u vs %u)",
-                g_TstMempool.mp_num_free, num_blocks);
-
-    /* remove all the blocks. Make sure we get count. */
-    memset(block_array, 0, sizeof(block_array));
-    cnt = 0;
-    while (1) {
-        block = os_memblock_get(&g_TstMempool);
-        if (block == NULL) {
-            break;
-        }
-        block_array[cnt] = block;
-        ++cnt;
-        if (cnt == MEMPOOL_TEST_MAX_BLOCKS) {
-            break;
-        }
-    }
-
-    TEST_ASSERT((cnt == g_TstMempool.mp_num_blocks) && 
-                (cnt != MEMPOOL_TEST_MAX_BLOCKS),
-                "Got more blocks than mempool contains (%d vs %d)",
-                cnt, g_TstMempool.mp_num_blocks);
-
-    /* Better be no free blocks left! */
-    TEST_ASSERT(g_TstMempool.mp_num_free == 0,
-                "Got all blocks but number free not zero! (%d)",
-                g_TstMempool.mp_num_free);
-
-    /* Now put them all back */
-    for (cnt = 0; cnt < g_TstMempool.mp_num_blocks; ++cnt) {
-        rc = os_memblock_put(&g_TstMempool, block_array[cnt]);
-        TEST_ASSERT(rc == 0,
-                    "Error putting back block %p (cnt=%d err=%d)", 
-                    block_array[cnt], cnt, rc);
-    }
-
-    /* Better be no free blocks left! */
-    TEST_ASSERT(g_TstMempool.mp_num_free == g_TstMempool.mp_num_blocks,
-                "Put all blocks but number free not equal to total!");
-
-    /* Better get error when we try these things! */
-    rc = os_memblock_put(NULL, block_array[0]);
-    TEST_ASSERT(rc != 0,
-                "Should have got an error trying to put to null pool");
-
-    rc = os_memblock_put(&g_TstMempool, NULL);
-    TEST_ASSERT(rc != 0, "No error trying to put to NULL block");
-
-    TEST_ASSERT(os_memblock_get(NULL) == NULL,
-                "No error trying to get a block from NULL pool");
-
-    /* Attempt to free a block outside the range of the membuf */
-    test_block = g_TstMempool.mp_membuf_addr;
-    test_block -= 4;
-    rc = os_memblock_put(&g_TstMempool, (void *)test_block);
-    TEST_ASSERT(rc == OS_INVALID_PARM, "No error freeing bad block address");
-
-    test_block += (true_block_size * g_TstMempool.mp_num_blocks) + 100;
-    rc = os_memblock_put(&g_TstMempool, (void *)test_block);
-    TEST_ASSERT(rc == OS_INVALID_PARM, "No error freeing bad block address");
-
-    /* Attempt to free on bad boundary */
-    test_block = g_TstMempool.mp_membuf_addr;
-    test_block += (true_block_size / 2);
-    rc = os_memblock_put(&g_TstMempool, (void *)test_block);
-    TEST_ASSERT(rc == OS_INVALID_PARM, "No error freeing bad block address");
-}
-
-/**
- * os mempool test 
- *  
- * Main test loop for memory pool testing. 
- * 
- * @return int 
- */
-TEST_CASE(os_mempool_test_case)
-{
-    mempool_test(NUM_MEM_BLOCKS, MEM_BLOCK_SIZE);
-}
-
-TEST_SUITE(os_mempool_test_suite)
-{
-    os_mempool_test_case();
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/test/src/mutex_test.c
----------------------------------------------------------------------
diff --git a/libs/os/test/src/mutex_test.c b/libs/os/test/src/mutex_test.c
deleted file mode 100644
index d23f099..0000000
--- a/libs/os/test/src/mutex_test.c
+++ /dev/null
@@ -1,407 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-#include <stdio.h>
-#include <string.h>
-#include <assert.h>
-#include <sys/time.h>
-#include "testutil/testutil.h"
-#include "os/os.h"
-#include "os/os_test.h"
-#include "os/os_cfg.h"
-#include "os/os_mutex.h"
-#include "os_test_priv.h"
-
-#ifdef ARCH_sim
-#define MUTEX_TEST_STACK_SIZE   1024
-#else
-#define MUTEX_TEST_STACK_SIZE   256
-#endif
-
-struct os_task task14;
-os_stack_t stack14[OS_STACK_ALIGN(MUTEX_TEST_STACK_SIZE)];
-
-struct os_task task15;
-os_stack_t stack15[OS_STACK_ALIGN(MUTEX_TEST_STACK_SIZE)];
-
-struct os_task task16;
-os_stack_t stack16[OS_STACK_ALIGN(MUTEX_TEST_STACK_SIZE)];
-
-struct os_task task17;
-os_stack_t stack17[OS_STACK_ALIGN(MUTEX_TEST_STACK_SIZE)];
-
-#define TASK14_PRIO (4)
-#define TASK15_PRIO (5)
-#define TASK16_PRIO (6)
-#define TASK17_PRIO (7)
-
-volatile int g_task14_val;
-volatile int g_task15_val;
-volatile int g_task16_val;
-volatile int g_task17_val;
-struct os_mutex g_mutex1;
-struct os_mutex g_mutex2;
-
-static volatile int g_mutex_test;
-
-/**
- * mutex test basic 
- *  
- * Basic mutex tests
- * 
- * @return int 
- */
-static void
-mutex_test_basic_handler(void *arg)
-{
-    struct os_mutex *mu;
-    struct os_task *t;
-    os_error_t err;
-
-    mu = &g_mutex1;
-    t = os_sched_get_current_task();
-
-    /* Test some error cases */
-    TEST_ASSERT(os_mutex_init(NULL)     == OS_INVALID_PARM);
-    TEST_ASSERT(os_mutex_release(NULL)  == OS_INVALID_PARM);
-    TEST_ASSERT(os_mutex_pend(NULL, 0)  == OS_INVALID_PARM);
-
-    /* Get the mutex */
-    err = os_mutex_pend(mu, 0);
-    TEST_ASSERT(err == 0,
-                "Did not get free mutex immediately (err=%d)", err);
-
-    /* Check mutex internals */
-    TEST_ASSERT(mu->mu_owner == t && mu->mu_level == 1 &&
-                mu->mu_prio == t->t_prio && SLIST_EMPTY(&mu->mu_head),
-                "Mutex internals not correct after getting mutex\n"
-                "Mutex: owner=%p prio=%u level=%u head=%p\n"
-                "Task: task=%p prio=%u",
-                mu->mu_owner, mu->mu_prio, mu->mu_level, 
-                SLIST_FIRST(&mu->mu_head),
-                t, t->t_prio);
-
-    /* Get the mutex again; should be level 2 */
-    err = os_mutex_pend(mu, 0);
-    TEST_ASSERT(err == 0, "Did not get my mutex immediately (err=%d)", err);
-
-    /* Check mutex internals */
-    TEST_ASSERT(mu->mu_owner == t && mu->mu_level == 2 &&
-                mu->mu_prio == t->t_prio && SLIST_EMPTY(&mu->mu_head),
-                "Mutex internals not correct after getting mutex\n"
-                "Mutex: owner=%p prio=%u level=%u head=%p\n"
-                "Task: task=%p prio=%u",
-                mu->mu_owner, mu->mu_prio, mu->mu_level, 
-                SLIST_FIRST(&mu->mu_head), t, t->t_prio);
-
-    /* Release mutex */
-    err = os_mutex_release(mu);
-    TEST_ASSERT(err == 0, "Could not release mutex I own (err=%d)", err);
-
-    /* Check mutex internals */
-    TEST_ASSERT(mu->mu_owner == t && mu->mu_level == 1 &&
-                mu->mu_prio == t->t_prio && SLIST_EMPTY(&mu->mu_head),
-                "Error: mutex internals not correct after getting mutex\n"
-                "Mutex: owner=%p prio=%u level=%u head=%p\n"
-                "Task: task=%p prio=%u",
-                mu->mu_owner, mu->mu_prio, mu->mu_level, 
-                SLIST_FIRST(&mu->mu_head), t, t->t_prio);
-
-    /* Release it again */
-    err = os_mutex_release(mu);
-    TEST_ASSERT(err == 0, "Could not release mutex I own (err=%d)", err);
-
-    /* Check mutex internals */
-    TEST_ASSERT(mu->mu_owner == NULL && mu->mu_level == 0 &&
-                mu->mu_prio == t->t_prio && SLIST_EMPTY(&mu->mu_head),
-                "Mutex internals not correct after getting mutex\n"
-                "Mutex: owner=%p prio=%u level=%u head=%p\n"
-                "Task: task=%p prio=%u",
-                mu->mu_owner, mu->mu_prio, mu->mu_level, 
-                SLIST_FIRST(&mu->mu_head), t, t->t_prio);
-
-    os_test_restart();
-}
-
-static void 
-mutex_test1_task14_handler(void *arg)
-{
-    os_error_t err;
-    struct os_task *t;
-    int iters;
-
-    t = os_sched_get_current_task();
-    TEST_ASSERT(t->t_func == mutex_test1_task14_handler);
-
-    for (iters = 0; iters < 3; iters++) {
-        os_time_delay(OS_TICKS_PER_SEC / 10);
-
-        g_task14_val = 1;
-
-        err = os_mutex_pend(&g_mutex1, OS_TICKS_PER_SEC / 10);
-        TEST_ASSERT(err == OS_OK);
-        TEST_ASSERT(g_task16_val == 1);
-
-        os_time_delay(OS_TICKS_PER_SEC / 10);
-    }
-
-    os_test_restart();
-}
-
-static void 
-mutex_test2_task14_handler(void *arg)
-{
-    os_error_t err;
-    struct os_task *t;
-    int iters;
-
-    t = os_sched_get_current_task();
-    TEST_ASSERT(t->t_func == mutex_test2_task14_handler);
-
-    for (iters = 0; iters < 3; iters++) {
-        err = os_mutex_pend(&g_mutex1, 0);
-        TEST_ASSERT(err == OS_OK, "err=%d", err);
-
-        g_task14_val = 1;
-        os_time_delay(OS_TICKS_PER_SEC / 10);
-
-        /* 
-         * Task17 should have its mutex wait flag set; at least the first time
-         * through!
-         */
-        if (iters == 0) {
-            TEST_ASSERT(task17.t_flags & OS_TASK_FLAG_MUTEX_WAIT);
-        }
-
-        if (g_mutex_test == 4) {
-            os_time_delay(150);
-        }
-
-        os_mutex_release(&g_mutex1);
-        os_time_delay(OS_TICKS_PER_SEC / 10);
-    }
-
-    os_test_restart();
-}
-
-static void 
-task15_handler(void *arg) 
-{
-    os_error_t err;
-    struct os_task *t;
-
-    if (g_mutex_test == 1) {
-        while (1) {
-            t = os_sched_get_current_task();
-            TEST_ASSERT(t->t_func == task15_handler);
-
-            os_time_delay(OS_TICKS_PER_SEC / 20);
-            while (1) {
-                /* Wait here forever */
-            }
-        }
-    } else {
-        if (g_mutex_test == 2) {
-            /* Sleep for 3 seconds */
-            t = os_sched_get_current_task();
-            os_time_delay(OS_TICKS_PER_SEC / 2);
-        } else if (g_mutex_test == 3) {
-            /* Sleep for 3 seconds */
-            t = os_sched_get_current_task();
-            os_time_delay(OS_TICKS_PER_SEC / 33);
-        }
-
-        while (1) {
-            t = os_sched_get_current_task();
-            TEST_ASSERT(t->t_func == task15_handler);
-
-            err = os_mutex_pend(&g_mutex1, OS_TICKS_PER_SEC * 10);
-            if (g_mutex_test == 4) {
-                TEST_ASSERT(err == OS_TIMEOUT);
-            } else {
-                TEST_ASSERT(err == OS_OK);
-            }
-
-            os_time_delay(OS_TICKS_PER_SEC / 10);
-        }
-    }
-}
-
-static void 
-task16_handler(void *arg) 
-{
-    os_error_t err;
-    struct os_task *t;
-
-    if (g_mutex_test == 1) {
-        while (1) {
-            t = os_sched_get_current_task();
-            TEST_ASSERT(t->t_func == task16_handler);
-
-            /* Get mutex 1 */
-            err = os_mutex_pend(&g_mutex1, OS_TIMEOUT_NEVER);
-            TEST_ASSERT(err == OS_OK);
-
-            while (g_task14_val != 1) {
-                /* Wait till task 1 wakes up and sets val. */
-            }
-
-            g_task16_val = 1;
-
-            err = os_mutex_release(&g_mutex1);
-            TEST_ASSERT(err == OS_OK);
-        }
-    } else {
-        if (g_mutex_test == 2) {
-            /* Sleep for 3 seconds */
-            t = os_sched_get_current_task();
-            os_time_delay(OS_TICKS_PER_SEC / 33);
-        } else if (g_mutex_test == 3) {
-            /* Sleep for 3 seconds */
-            t = os_sched_get_current_task();
-            os_time_delay(OS_TICKS_PER_SEC / 20);
-        }
-
-        while (1) {
-            t = os_sched_get_current_task();
-            TEST_ASSERT(t->t_func == task16_handler);
-
-            err = os_mutex_pend(&g_mutex1, OS_TICKS_PER_SEC * 10);
-            if (g_mutex_test == 4) {
-                TEST_ASSERT(err == OS_TIMEOUT);
-            } else {
-                TEST_ASSERT(err == OS_OK);
-            }
-
-            if (err == OS_OK) {
-                err = os_mutex_release(&g_mutex1);
-                TEST_ASSERT(err == OS_OK);
-            }
-
-            os_time_delay(OS_TICKS_PER_SEC * 10);
-        }
-    }
-}
-
-static void 
-task17_handler(void *arg)
-{
-    os_error_t err;
-    struct os_task *t;
-
-    while (1) {
-        t = os_sched_get_current_task();
-        TEST_ASSERT(t->t_func == task17_handler);
-
-        if (g_mutex_test == 5) {
-            err = os_mutex_pend(&g_mutex1, OS_TICKS_PER_SEC / 10);
-        } else {
-            err = os_mutex_pend(&g_mutex1, OS_TICKS_PER_SEC * 10);
-            TEST_ASSERT((t->t_flags & OS_TASK_FLAG_MUTEX_WAIT) == 0);
-        }
-
-        if (g_mutex_test == 4 || g_mutex_test == 5) {
-            TEST_ASSERT(err == OS_TIMEOUT);
-        } else {
-            TEST_ASSERT(err == OS_OK);
-        }
-
-        if (err == OS_OK) {
-            err = os_mutex_release(&g_mutex1);
-            TEST_ASSERT(err == OS_OK);
-        }
-
-        os_time_delay(OS_TICKS_PER_SEC * 10);
-    }
-}
-
-TEST_CASE(os_mutex_test_basic)
-{
-    os_init();
-
-    os_mutex_init(&g_mutex1);
-
-    os_task_init(&task14, "task14", mutex_test_basic_handler, NULL,
-                 TASK14_PRIO, OS_WAIT_FOREVER, stack14,
-                 OS_STACK_ALIGN(MUTEX_TEST_STACK_SIZE));
-
-    os_start();
-}
-
-TEST_CASE(os_mutex_test_case_1)
-{
-    int rc;
-
-    os_init();
-
-    g_mutex_test = 1;
-    g_task14_val = 0;
-    g_task15_val = 0;
-    g_task16_val = 0;
-
-    rc = os_mutex_init(&g_mutex1);
-    TEST_ASSERT(rc == 0);
-    rc = os_mutex_init(&g_mutex2);
-    TEST_ASSERT(rc == 0);
-
-    os_task_init(&task14, "task14", mutex_test1_task14_handler, NULL,
-                 TASK14_PRIO, OS_WAIT_FOREVER, stack14,
-                 OS_STACK_ALIGN(MUTEX_TEST_STACK_SIZE));
-
-    os_task_init(&task15, "task15", task15_handler, NULL, TASK15_PRIO, 
-            OS_WAIT_FOREVER, stack15, OS_STACK_ALIGN(MUTEX_TEST_STACK_SIZE));
-
-    os_task_init(&task16, "task16", task16_handler, NULL, TASK16_PRIO, 
-            OS_WAIT_FOREVER, stack16, OS_STACK_ALIGN(MUTEX_TEST_STACK_SIZE));
-
-    os_start();
-}
-
-TEST_CASE(os_mutex_test_case_2)
-{
-    os_init();
-
-    g_mutex_test = 2;
-    g_task14_val = 0;
-    g_task15_val = 0;
-    g_task16_val = 0;
-    os_mutex_init(&g_mutex1);
-    os_mutex_init(&g_mutex2);
-
-    os_task_init(&task14, "task14", mutex_test2_task14_handler, NULL,
-                 TASK14_PRIO, OS_WAIT_FOREVER, stack14,
-                 OS_STACK_ALIGN(MUTEX_TEST_STACK_SIZE));
-
-    os_task_init(&task15, "task15", task15_handler, NULL, TASK15_PRIO, 
-            OS_WAIT_FOREVER, stack15, OS_STACK_ALIGN(MUTEX_TEST_STACK_SIZE));
-
-    os_task_init(&task16, "task16", task16_handler, NULL, TASK16_PRIO, 
-            OS_WAIT_FOREVER, stack16, OS_STACK_ALIGN(MUTEX_TEST_STACK_SIZE));
-
-    os_task_init(&task17, "task17", task17_handler, NULL, TASK17_PRIO, 
-            OS_WAIT_FOREVER, stack17, OS_STACK_ALIGN(MUTEX_TEST_STACK_SIZE));
- 
-    os_start();
-}
-
-TEST_SUITE(os_mutex_test_suite)
-{
-    os_mutex_test_basic();
-    os_mutex_test_case_1();
-    os_mutex_test_case_2();
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/test/src/os_test.c
----------------------------------------------------------------------
diff --git a/libs/os/test/src/os_test.c b/libs/os/test/src/os_test.c
deleted file mode 100644
index e9d041b..0000000
--- a/libs/os/test/src/os_test.c
+++ /dev/null
@@ -1,53 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include <assert.h>
-#include <stddef.h>
-#include "syscfg/syscfg.h"
-#include "testutil/testutil.h"
-#include "os/os_test.h"
-#include "os_test_priv.h"
-
-int
-os_test_all(void)
-{
-    os_mempool_test_suite();
-    os_mutex_test_suite();
-    os_sem_test_suite();
-    os_mbuf_test_suite();
-    os_eventq_test_suite();
-    os_callout_test_suite();
-
-    return tu_case_failed;
-}
-
-#if MYNEWT_VAL(SELFTEST)
-
-int
-main(int argc, char **argv)
-{
-    tu_config.tc_print_results = 1;
-    tu_init();
-
-    os_test_all();
-
-    return tu_any_failed;
-}
-
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/test/src/os_test_priv.h
----------------------------------------------------------------------
diff --git a/libs/os/test/src/os_test_priv.h b/libs/os/test/src/os_test_priv.h
deleted file mode 100644
index e923a6f..0000000
--- a/libs/os/test/src/os_test_priv.h
+++ /dev/null
@@ -1,32 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 H_OS_TEST_PRIV_
-#define H_OS_TEST_PRIV_
-
-void os_test_restart(void);
-
-int os_mempool_test_suite(void);
-int os_mbuf_test_suite(void);
-int os_mutex_test_suite(void);
-int os_sem_test_suite(void);
-int os_eventq_test_suite(void);
-int os_callout_test_suite(void);
-
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/test/src/sem_test.c
----------------------------------------------------------------------
diff --git a/libs/os/test/src/sem_test.c b/libs/os/test/src/sem_test.c
deleted file mode 100644
index 6b40069..0000000
--- a/libs/os/test/src/sem_test.c
+++ /dev/null
@@ -1,401 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-#include <stdio.h>
-#include <string.h>
-#include "testutil/testutil.h"
-#include "os/os.h"
-#include "os/os_cfg.h"
-#include "os/os_sem.h"
-#include "os_test_priv.h"
-
-#ifdef ARCH_sim
-#define SEM_TEST_STACK_SIZE     1024
-#else 
-#define SEM_TEST_STACK_SIZE     512
-#endif
-
-struct os_task task1;
-os_stack_t stack1[OS_STACK_ALIGN(SEM_TEST_STACK_SIZE)];
-
-struct os_task task2;
-os_stack_t stack2[OS_STACK_ALIGN(SEM_TEST_STACK_SIZE)];
-
-struct os_task task3;
-os_stack_t stack3[OS_STACK_ALIGN(SEM_TEST_STACK_SIZE)];
-
-struct os_task task4;
-os_stack_t stack4[OS_STACK_ALIGN(SEM_TEST_STACK_SIZE)];
-
-#define TASK1_PRIO (1) 
-#define TASK2_PRIO (2) 
-#define TASK3_PRIO (3) 
-#define TASK4_PRIO (4) 
-
-struct os_sem g_sem1;
-
-/* 
- * TEST NUMBERS:
- *  10: In this test we have the highest priority task getting the semaphore
- *  then sleeping. Two lower priority tasks then wake up and attempt to get
- *  the semaphore. They are blocked until the higher priority task releases
- *  the semaphore, at which point the lower priority tasks should wake up in
- *  order, get the semaphore, then release it and go back to sleep.
- * 
- */
-
-/**
- * sem test disp sem
- *  
- * Display semaphore contents 
- * 
- * @param sem 
- */
-static const char *
-sem_test_sem_to_s(const struct os_sem *sem)
-{
-    static char buf[128];
-
-    snprintf(buf, sizeof buf, "\tSemaphore: tokens=%u head=%p",
-             sem->sem_tokens, SLIST_FIRST(&sem->sem_head));
-
-    return buf;
-}
-
-static void 
-sem_test_sleep_task_handler(void *arg)
-{
-    struct os_task *t;
-
-    t = os_sched_get_current_task();
-    TEST_ASSERT(t->t_func == sem_test_sleep_task_handler);
-
-    os_time_delay(2 * OS_TICKS_PER_SEC);
-    os_test_restart();
-}
-
-static void
-sem_test_pend_release_loop(int delay, int timeout, int itvl)
-{
-    os_error_t err;
-
-    os_time_delay(delay);
-
-    while (1) {
-        err = os_sem_pend(&g_sem1, timeout);
-        TEST_ASSERT((err == OS_OK) || (err == OS_TIMEOUT));
-
-        err = os_sem_release(&g_sem1);
-        TEST_ASSERT(err == OS_OK);
-
-        os_time_delay(itvl);
-    }
-}
-
-/**
- * sem test basic 
- *  
- * Basic semaphore tests
- * 
- * @return int 
- */
-static void 
-sem_test_basic_handler(void *arg)
-{
-    struct os_task *t;
-    struct os_sem *sem;
-    os_error_t err;
-
-    sem = &g_sem1;
-    t = os_sched_get_current_task();
-
-    /* Test some error cases */
-    TEST_ASSERT(os_sem_init(NULL, 1)    == OS_INVALID_PARM);
-    TEST_ASSERT(os_sem_release(NULL)    == OS_INVALID_PARM);
-    TEST_ASSERT(os_sem_pend(NULL, 1)    == OS_INVALID_PARM);
-
-    /* Get the semaphore */
-    err = os_sem_pend(sem, 0);
-    TEST_ASSERT(err == 0,
-                "Did not get free semaphore immediately (err=%d)", err);
-
-    /* Check semaphore internals */
-    TEST_ASSERT(sem->sem_tokens == 0 && SLIST_EMPTY(&sem->sem_head),
-                "Semaphore internals wrong after getting semaphore\n"
-                "%s\n"
-                "Task: task=%p prio=%u", sem_test_sem_to_s(sem), t, t->t_prio);
-
-    /* Get the semaphore again; should fail */
-    err = os_sem_pend(sem, 0);
-    TEST_ASSERT(err == OS_TIMEOUT,
-                "Did not time out waiting for semaphore (err=%d)", err);
-
-    /* Check semaphore internals */
-    TEST_ASSERT(sem->sem_tokens == 0 && SLIST_EMPTY(&sem->sem_head),
-                "Semaphore internals wrong after getting semaphore\n"
-                "%s\n"
-                "Task: task=%p prio=%u\n", sem_test_sem_to_s(sem), t,
-                t->t_prio);
-
-    /* Release semaphore */
-    err = os_sem_release(sem);
-    TEST_ASSERT(err == 0,
-                "Could not release semaphore I own (err=%d)", err);
-
-    /* Check semaphore internals */
-    TEST_ASSERT(sem->sem_tokens == 1 && SLIST_EMPTY(&sem->sem_head),
-                "Semaphore internals wrong after releasing semaphore\n"
-                "%s\n"
-                "Task: task=%p prio=%u\n", sem_test_sem_to_s(sem), t,
-                t->t_prio);
-
-    /* Release it again */
-    err = os_sem_release(sem);
-    TEST_ASSERT(err == 0,
-                "Could not release semaphore again (err=%d)\n", err);
-
-    /* Check semaphore internals */
-    TEST_ASSERT(sem->sem_tokens == 2 && SLIST_EMPTY(&sem->sem_head),
-                "Semaphore internals wrong after releasing semaphore\n"
-                "%s\n"
-                "Task: task=%p prio=%u\n", sem_test_sem_to_s(sem), t,
-                t->t_prio);
-
-    os_test_restart();
-}
-
-static void 
-sem_test_1_task1_handler(void *arg)
-{
-    os_error_t err;
-    struct os_task *t;
-    int i;;
-
-    for (i = 0; i < 3; i++) {
-        t = os_sched_get_current_task();
-        TEST_ASSERT(t->t_func == sem_test_1_task1_handler);
-
-
-        err = os_sem_pend(&g_sem1, 0);
-        TEST_ASSERT(err == OS_OK);
-
-        /* Sleep to let other tasks run */
-        os_time_delay(OS_TICKS_PER_SEC / 10);
-
-        /* Release the semaphore */
-        err = os_sem_release(&g_sem1);
-        TEST_ASSERT(err == OS_OK);
-
-        /* Sleep to let other tasks run */
-        os_time_delay(OS_TICKS_PER_SEC / 10);
-    }
-
-    os_test_restart();
-}
-
-TEST_CASE(os_sem_test_basic)
-{
-    os_error_t err;
-
-    os_init();
-
-    err = os_sem_init(&g_sem1, 1);
-    TEST_ASSERT(err == OS_OK);
-
-    os_task_init(&task1, "task1", sem_test_basic_handler, NULL, TASK1_PRIO, 
-            OS_WAIT_FOREVER, stack1, OS_STACK_ALIGN(SEM_TEST_STACK_SIZE));
-
-    os_start();
-}
-
-static void 
-sem_test_1_task2_handler(void *arg) 
-{
-    sem_test_pend_release_loop(0, OS_TICKS_PER_SEC / 10, OS_TICKS_PER_SEC / 10);
-}
-
-static void 
-sem_test_1_task3_handler(void *arg) 
-{
-    sem_test_pend_release_loop(0, OS_TIMEOUT_NEVER, OS_TICKS_PER_SEC * 2);
-}
-
-TEST_CASE(os_sem_test_case_1)
-{
-    os_error_t err;
-
-    os_init();
-
-    err = os_sem_init(&g_sem1, 1);
-    TEST_ASSERT(err == OS_OK);
-
-    os_task_init(&task1, "task1", sem_test_1_task1_handler, NULL,
-                 TASK1_PRIO, OS_WAIT_FOREVER, stack1,
-                 OS_STACK_ALIGN(SEM_TEST_STACK_SIZE));
-
-    os_task_init(&task2, "task2", sem_test_1_task2_handler, NULL,
-                 TASK2_PRIO, OS_WAIT_FOREVER, stack2,
-                 OS_STACK_ALIGN(SEM_TEST_STACK_SIZE));
-
-    os_task_init(&task3, "task3", sem_test_1_task3_handler, NULL, TASK3_PRIO, 
-                 OS_WAIT_FOREVER, stack3, OS_STACK_ALIGN(SEM_TEST_STACK_SIZE));
-
-    os_start();
-}
-
-static void 
-sem_test_2_task2_handler(void *arg) 
-{
-    sem_test_pend_release_loop(0, 2000, 2000);
-}
-
-static void 
-sem_test_2_task3_handler(void *arg) 
-{
-    sem_test_pend_release_loop(0, OS_TIMEOUT_NEVER, 2000);
-}
-
-static void 
-sem_test_2_task4_handler(void *arg) 
-{
-    sem_test_pend_release_loop(0, 2000, 2000);
-}
-
-TEST_CASE(os_sem_test_case_2)
-{
-    os_error_t err;
-
-    os_init();
-
-    err = os_sem_init(&g_sem1, 1);
-    TEST_ASSERT(err == OS_OK);
-
-    os_task_init(&task1, "task1", sem_test_sleep_task_handler, NULL,
-                 TASK1_PRIO, OS_WAIT_FOREVER, stack1,
-                 OS_STACK_ALIGN(SEM_TEST_STACK_SIZE));
-
-    os_task_init(&task2, "task2", sem_test_2_task2_handler, NULL,
-                 TASK2_PRIO, OS_WAIT_FOREVER, stack2,
-                 OS_STACK_ALIGN(SEM_TEST_STACK_SIZE));
-
-    os_task_init(&task3, "task3", sem_test_2_task3_handler, NULL, TASK3_PRIO,
-            OS_WAIT_FOREVER, stack3, OS_STACK_ALIGN(SEM_TEST_STACK_SIZE));
-
-    os_task_init(&task4, "task4", sem_test_2_task4_handler, NULL, TASK4_PRIO,
-            OS_WAIT_FOREVER, stack4, OS_STACK_ALIGN(SEM_TEST_STACK_SIZE));
-
-    os_start();
-}
-
-static void 
-sem_test_3_task2_handler(void *arg) 
-{
-    sem_test_pend_release_loop(100, 2000, 2000);
-}
-
-static void 
-sem_test_3_task3_handler(void *arg) 
-{
-    sem_test_pend_release_loop(150, 2000, 2000);
-}
-
-static void 
-sem_test_3_task4_handler(void *arg) 
-{
-    sem_test_pend_release_loop(0, 2000, 2000);
-}
-
-TEST_CASE(os_sem_test_case_3)
-{
-    os_error_t err;
-
-    os_init();
-
-    err = os_sem_init(&g_sem1, 1);
-    TEST_ASSERT(err == OS_OK);
-
-    os_task_init(&task1, "task1", sem_test_sleep_task_handler, NULL,
-                 TASK1_PRIO, OS_WAIT_FOREVER, stack1,
-                 OS_STACK_ALIGN(SEM_TEST_STACK_SIZE));
-
-    os_task_init(&task2, "task2", sem_test_3_task2_handler, NULL,
-                 TASK2_PRIO, OS_WAIT_FOREVER, stack2,
-                 OS_STACK_ALIGN(SEM_TEST_STACK_SIZE));
-
-    os_task_init(&task3, "task3", sem_test_3_task3_handler, NULL, TASK3_PRIO,
-            OS_WAIT_FOREVER, stack3, OS_STACK_ALIGN(SEM_TEST_STACK_SIZE));
-
-    os_task_init(&task4, "task4", sem_test_3_task4_handler, NULL, TASK4_PRIO,
-            OS_WAIT_FOREVER, stack4, OS_STACK_ALIGN(SEM_TEST_STACK_SIZE));
-
-    os_start();
-}
-
-static void 
-sem_test_4_task2_handler(void *arg) 
-{
-    sem_test_pend_release_loop(60, 2000, 2000);
-}
-
-static void 
-sem_test_4_task3_handler(void *arg) 
-{
-    sem_test_pend_release_loop(60, 2000, 2000);
-}
-
-static void 
-sem_test_4_task4_handler(void *arg) 
-{
-    sem_test_pend_release_loop(0, 2000, 2000);
-}
-
-
-TEST_CASE(os_sem_test_case_4)
-{
-    os_error_t err;
-
-    os_init();
-
-    err = os_sem_init(&g_sem1, 1);
-    TEST_ASSERT(err == OS_OK);
-
-    os_task_init(&task1, "task1", sem_test_sleep_task_handler, NULL,
-                 TASK1_PRIO, OS_WAIT_FOREVER, stack1,
-                 OS_STACK_ALIGN(SEM_TEST_STACK_SIZE));
-
-    os_task_init(&task2, "task2", sem_test_4_task2_handler, NULL,
-                 TASK2_PRIO, OS_WAIT_FOREVER, stack2,
-                 OS_STACK_ALIGN(SEM_TEST_STACK_SIZE));
-
-    os_task_init(&task3, "task3", sem_test_4_task3_handler, NULL, TASK3_PRIO,
-                 OS_WAIT_FOREVER, stack3, OS_STACK_ALIGN(SEM_TEST_STACK_SIZE));
-
-    os_task_init(&task4, "task4", sem_test_4_task4_handler, NULL, TASK4_PRIO,
-                 OS_WAIT_FOREVER, stack4, OS_STACK_ALIGN(SEM_TEST_STACK_SIZE));
-
-    os_start();
-}
-
-TEST_SUITE(os_sem_test_suite)
-{
-    os_sem_test_basic();
-    os_sem_test_case_1();
-    os_sem_test_case_2();
-    os_sem_test_case_3();
-    os_sem_test_case_4();
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/shell/include/shell/shell.h
----------------------------------------------------------------------
diff --git a/libs/shell/include/shell/shell.h b/libs/shell/include/shell/shell.h
deleted file mode 100644
index 48351a0..0000000
--- a/libs/shell/include/shell/shell.h
+++ /dev/null
@@ -1,48 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 __SHELL_H__
-#define __SHELL_H__
-
-#include <os/os.h>
-
-typedef int (*shell_cmd_func_t)(int argc, char **argv);
-struct shell_cmd {
-    char *sc_cmd;
-    shell_cmd_func_t sc_cmd_func;
-    STAILQ_ENTRY(shell_cmd) sc_next;
-};
-
-int shell_cmd_register(struct shell_cmd *sc);
-
-#define SHELL_NLIP_PKT_START1 (6)
-#define SHELL_NLIP_PKT_START2 (9)
-#define SHELL_NLIP_DATA_START1 (4)
-#define SHELL_NLIP_DATA_START2 (20)
-
-typedef int (*shell_nlip_input_func_t)(struct os_mbuf *, void *arg);
-int shell_nlip_input_register(shell_nlip_input_func_t nf, void *arg);
-int shell_nlip_output(struct os_mbuf *m);
-
-void shell_console_rx_cb(void);
-void shell_init(void);
-
-int shell_cmd_list_lock(void);
-int shell_cmd_list_unlock(void);
-
-#endif /* __SHELL_H__ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/shell/include/shell/shell_prompt.h
----------------------------------------------------------------------
diff --git a/libs/shell/include/shell/shell_prompt.h b/libs/shell/include/shell/shell_prompt.h
deleted file mode 100644
index f0e4dd3..0000000
--- a/libs/shell/include/shell/shell_prompt.h
+++ /dev/null
@@ -1,25 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 H_SHELL_PROMPT_
-#define H_SHELL_PROMPT_
-
-int shell_prompt_cmd(int argc, char **argv);
-
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/shell/pkg.yml
----------------------------------------------------------------------
diff --git a/libs/shell/pkg.yml b/libs/shell/pkg.yml
deleted file mode 100644
index 5e2cd69..0000000
--- a/libs/shell/pkg.yml
+++ /dev/null
@@ -1,48 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you 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.
-#
-
-pkg.name: libs/shell 
-pkg.description: Command processor for console-based applications.
-pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
-pkg.homepage: "http://mynewt.apache.org/"
-pkg.keywords:
-
-pkg.deps:
-    - libs/os
-    - libs/util
-pkg.req_apis:
-    - console
-
-pkg.init_function: shell_init
-pkg.init_stage: 5
-
-pkg.syscfg_defs:
-    SHELL_TASK:
-        description: 'TBD'
-        value: 0
-    SHELL_TASK_PRIO:
-        description: 'TBD'
-        type: 'task_priority'
-        value: 'any'
-    SHELL_STACK_SIZE:
-        description: 'TBD'
-        value: 512
-    SHELL_MAX_INPUT_LEN:
-        description: 'TBD'
-        value: 256


[34/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/src/os_sem.c
----------------------------------------------------------------------
diff --git a/kernel/os/src/os_sem.c b/kernel/os/src/os_sem.c
new file mode 100644
index 0000000..181e5de
--- /dev/null
+++ b/kernel/os/src/os_sem.c
@@ -0,0 +1,212 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include "os/os.h"
+#include <assert.h>
+
+/* XXX:
+ * 1) Should I check to see if we are within an ISR for some of these?
+ * 2) Would I do anything different for os_sem_release() if we were in an
+ *    ISR when this was called?
+ */
+
+/**
+ * os sem create
+ *  
+ * Create a semaphore and initialize it. 
+ * 
+ * @param sem Pointer to semaphore 
+ *        tokens: # of tokens the semaphore should contain initially.   
+ * 
+ * @return os_error_t 
+ *      OS_INVALID_PARM     Semaphore passed in was NULL.
+ *      OS_OK               no error.
+ */
+os_error_t
+os_sem_init(struct os_sem *sem, uint16_t tokens)
+{
+    if (!sem) {
+        return OS_INVALID_PARM;
+    }
+
+    sem->sem_tokens = tokens;
+    SLIST_FIRST(&sem->sem_head) = NULL;
+
+    return OS_OK;
+}
+
+/**
+ * os sem release
+ *  
+ * Release a semaphore. 
+ * 
+ * @param sem Pointer to the semaphore to be released
+ * 
+ * @return os_error_t 
+ *      OS_INVALID_PARM Semaphore passed in was NULL.
+ *      OS_OK No error
+ */
+os_error_t
+os_sem_release(struct os_sem *sem)
+{
+    int resched;
+    os_sr_t sr;
+    struct os_task *current;
+    struct os_task *rdy;
+
+    /* OS must be started to release semaphores */ 
+    if (!g_os_started) {
+        return (OS_NOT_STARTED);
+    }
+
+    /* Check for valid semaphore */
+    if (!sem) {
+        return OS_INVALID_PARM;
+    }
+
+    /* Get current task */
+    resched = 0;
+    current = os_sched_get_current_task();
+
+    OS_ENTER_CRITICAL(sr);
+
+    /* Check if tasks are waiting for the semaphore */
+    rdy = SLIST_FIRST(&sem->sem_head);
+    if (rdy) {
+        /* Clear flag that we are waiting on the semaphore; wake up task */
+        rdy->t_flags &= ~OS_TASK_FLAG_SEM_WAIT;
+        os_sched_wakeup(rdy);
+
+        /* Schedule if waiting task higher priority */
+        if (current->t_prio > rdy->t_prio) {
+            resched = 1;
+        }
+    } else {
+        /* Add to the number of tokens */
+        sem->sem_tokens++;
+    }
+
+    OS_EXIT_CRITICAL(sr);
+
+    /* Re-schedule if needed */
+    if (resched) {
+        os_sched(rdy);
+    }
+
+    return OS_OK;
+}
+
+/**
+ * os sem pend 
+ *  
+ * Pend (wait) for a semaphore. 
+ * 
+ * @param mu Pointer to semaphore.
+ * @param timeout Timeout, in os ticks. A timeout of 0 means do 
+ *                not wait if not available. A timeout of
+ *                0xFFFFFFFF means wait forever.
+ *              
+ * 
+ * @return os_error_t 
+ *      OS_INVALID_PARM     Semaphore passed in was NULL.
+ *      OS_TIMEOUT          Semaphore was owned by another task and timeout=0
+ *      OS_OK               no error.
+ */ 
+os_error_t
+os_sem_pend(struct os_sem *sem, uint32_t timeout)
+{
+    os_sr_t sr;
+    os_error_t rc;
+    int sched;
+    struct os_task *current;
+    struct os_task *entry;
+    struct os_task *last;
+
+    /* Check if OS is started */
+    if (!g_os_started) {
+        return (OS_NOT_STARTED);
+    }
+
+    /* Check for valid semaphore */
+    if (!sem) {
+        return OS_INVALID_PARM;
+    }
+
+    /* Assume we dont have to put task to sleep; get current task */
+    sched = 0;
+    current = os_sched_get_current_task();
+
+    OS_ENTER_CRITICAL(sr);
+
+    /* 
+     * If there is a token available, take it. If no token, either return
+     * with error if timeout was 0 or put this task to sleep.
+     */
+    if (sem->sem_tokens != 0) {
+        sem->sem_tokens--;
+        rc = OS_OK;
+    } else if (timeout == 0) {
+        rc = OS_TIMEOUT;
+    } else {
+        /* Silence gcc maybe-uninitialized warning. */
+        rc = OS_OK;
+
+        /* Link current task to tasks waiting for semaphore */
+        current->t_obj = sem; 
+        current->t_flags |= OS_TASK_FLAG_SEM_WAIT;
+        last = NULL;
+        if (!SLIST_EMPTY(&sem->sem_head)) {
+            /* Insert in priority order */
+            SLIST_FOREACH(entry, &sem->sem_head, t_obj_list) {
+                if (current->t_prio < entry->t_prio) { 
+                    break;
+                }
+                last = entry;
+            }
+        }
+
+        if (last) {
+            SLIST_INSERT_AFTER(last, current, t_obj_list);
+        } else {
+            SLIST_INSERT_HEAD(&sem->sem_head, current, t_obj_list);
+        }
+
+        /* We will put this task to sleep */
+        sched = 1;
+        os_sched_sleep(current, timeout);
+    }
+
+    OS_EXIT_CRITICAL(sr);
+
+    if (sched) {
+        os_sched(NULL);
+        /* Check if we timed out or got the semaphore */
+        if (current->t_flags & OS_TASK_FLAG_SEM_WAIT) {
+            OS_ENTER_CRITICAL(sr);
+            current->t_flags &= ~OS_TASK_FLAG_SEM_WAIT;
+            OS_EXIT_CRITICAL(sr);
+            rc = OS_TIMEOUT;
+        } else {
+            rc = OS_OK; 
+        }
+    }
+
+    return rc;
+}
+

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/src/os_task.c
----------------------------------------------------------------------
diff --git a/kernel/os/src/os_task.c b/kernel/os/src/os_task.c
new file mode 100644
index 0000000..9e2860b
--- /dev/null
+++ b/kernel/os/src/os_task.c
@@ -0,0 +1,216 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+
+#include "os/os.h"
+#include "os_priv.h"
+
+#include <string.h>
+
+uint8_t g_task_id;
+
+struct os_task_stailq g_os_task_list;
+
+static void
+_clear_stack(os_stack_t *stack_bottom, int size)
+{
+    int i;
+
+    for (i = 0; i < size; i++) {
+        stack_bottom[i] = OS_STACK_PATTERN;
+    }
+}
+
+static inline uint8_t
+os_task_next_id(void)
+{
+    uint8_t rc;
+    os_sr_t sr;
+
+    OS_ENTER_CRITICAL(sr);
+    rc = g_task_id;
+    g_task_id++;
+    OS_EXIT_CRITICAL(sr);
+
+    return (rc);
+}
+
+/**
+ * Return the number of tasks initialized.
+ *
+ * @return number of tasks initialized
+ */
+uint8_t
+os_task_count(void)
+{
+    return (g_task_id);
+}
+
+/**
+ * Initialize a task.
+ *
+ * This function initializes the task structure pointed to by t,
+ * clearing and setting it's stack pointer, provides sane defaults
+ * and sets the task as ready to run, and inserts it into the operating
+ * system scheduler.
+ *
+ * @param t The task to initialize
+ * @param name The name of the task to initialize
+ * @param func The task function to call
+ * @param arg The argument to pass to this task function
+ * @param prio The priority at which to run this task
+ * @param sanity_itvl The time at which this task should check in with the
+ *                    sanity task.  OS_WAIT_FOREVER means never check in
+ *                    here.
+ * @param stack_bottom A pointer to the bottom of a task's stack
+ * @param stack_size The overall size of the task's stack.
+ *
+ * @return 0 on success, non-zero on failure.
+ */
+int
+os_task_init(struct os_task *t, const char *name, os_task_func_t func,
+        void *arg, uint8_t prio, os_time_t sanity_itvl,
+        os_stack_t *stack_bottom, uint16_t stack_size)
+{
+    struct os_sanity_check *sc;
+    int rc;
+
+    memset(t, 0, sizeof(*t));
+
+    t->t_func = func;
+    t->t_arg = arg;
+
+    t->t_taskid = os_task_next_id();
+    t->t_prio = prio;
+
+    t->t_state = OS_TASK_READY;
+    t->t_name = name;
+    t->t_next_wakeup = 0;
+
+    rc = os_sanity_check_init(&t->t_sanity_check);
+    if (rc != OS_OK) {
+        goto err;
+    }
+
+    if (sanity_itvl != OS_WAIT_FOREVER) {
+        sc = (struct os_sanity_check *) &t->t_sanity_check;
+        sc->sc_checkin_itvl = sanity_itvl;
+
+        rc = os_sanity_check_register(sc);
+        if (rc != OS_OK) {
+            goto err;
+        }
+    }
+
+    _clear_stack(stack_bottom, stack_size);
+    t->t_stackptr = os_arch_task_stack_init(t, &stack_bottom[stack_size],
+            stack_size);
+    t->t_stacktop = &stack_bottom[stack_size];
+    t->t_stacksize = stack_size;
+
+    /* insert this task into the task list */
+    STAILQ_INSERT_TAIL(&g_os_task_list, t, t_os_task_list);
+
+    /* insert this task into the scheduler list */
+    rc = os_sched_insert(t);
+    if (rc != OS_OK) {
+        goto err;
+    }
+
+
+    return (0);
+err:
+    return (rc);
+}
+
+/**
+ * Iterate through tasks, and return the following information about them:
+ *
+ * - Priority
+ * - Task ID
+ * - State (ACTIVE, SLEEP)
+ * - Total Stack Usage
+ * - Stack Size
+ * - Context Switch Count
+ * - Runtime
+ * - Last & Next Sanity checkin
+ * - Task Name
+ *
+ * To get the first task in the list, call os_task_info_get_next() with a
+ * NULL pointer in the prev argument, and os_task_info_get_next() will
+ * return a pointer to the task structure, and fill out the os_task_info
+ * structure pointed to by oti.
+ *
+ * To get the next task in the list, provide the task structure returned
+ * by the previous call to os_task_info_get_next(), and os_task_info_get_next()
+ * will fill out the task structure pointed to by oti again, and return
+ * the next task in the list.
+ *
+ * @param prev The previous task returned by os_task_info_get_next(), or NULL
+ *             to begin iteration.
+ * @param oti  The OS task info structure to fill out.
+ *
+ * @return A pointer to the OS task that has been read, or NULL when finished
+ *         iterating through all tasks.
+ */
+struct os_task *
+os_task_info_get_next(const struct os_task *prev, struct os_task_info *oti)
+{
+    struct os_task *next;
+    os_stack_t *top;
+    os_stack_t *bottom;
+
+    if (prev != NULL) {
+        next = STAILQ_NEXT(prev, t_os_task_list);
+    } else {
+        next = STAILQ_FIRST(&g_os_task_list);
+    }
+
+    if (next == NULL) {
+        return (NULL);
+    }
+
+    /* Otherwise, copy OS task information into the OTI structure, and
+     * return 1, which means continue
+     */
+    oti->oti_prio = next->t_prio;
+    oti->oti_taskid = next->t_taskid;
+    oti->oti_state = next->t_state;
+
+    top = next->t_stacktop;
+    bottom = next->t_stacktop - next->t_stacksize;
+    while (bottom < top) {
+        if (*bottom != OS_STACK_PATTERN) {
+            break;
+        }
+        ++bottom;
+    }
+
+    oti->oti_stkusage = (uint16_t) (next->t_stacktop - bottom);
+    oti->oti_stksize = next->t_stacksize;
+    oti->oti_cswcnt = next->t_ctx_sw_cnt;
+    oti->oti_runtime = next->t_run_time;
+    oti->oti_last_checkin = next->t_sanity_check.sc_checkin_last;
+    oti->oti_next_checkin = next->t_sanity_check.sc_checkin_last +
+        next->t_sanity_check.sc_checkin_itvl;
+    strncpy(oti->oti_name, next->t_name, sizeof(oti->oti_name));
+
+    return (next);
+}
+

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/src/os_time.c
----------------------------------------------------------------------
diff --git a/kernel/os/src/os_time.c b/kernel/os/src/os_time.c
new file mode 100644
index 0000000..4ef439f
--- /dev/null
+++ b/kernel/os/src/os_time.c
@@ -0,0 +1,248 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include <util/util.h>
+#include <assert.h>
+
+#include "os/os.h"
+#include "os/queue.h"
+
+CTASSERT(sizeof(os_time_t) == 4);
+
+#define OS_USEC_PER_TICK    (1000000 / OS_TICKS_PER_SEC)
+
+os_time_t g_os_time;
+
+/*
+ * Time-of-day collateral.
+ */
+static struct {
+    os_time_t ostime;
+    struct os_timeval uptime;
+    struct os_timeval utctime;
+    struct os_timezone timezone;
+} basetod;
+
+static void
+os_deltatime(os_time_t delta, const struct os_timeval *base,
+    struct os_timeval *result)
+{
+    struct os_timeval tvdelta;
+
+    tvdelta.tv_sec = delta / OS_TICKS_PER_SEC;
+    tvdelta.tv_usec = (delta % OS_TICKS_PER_SEC) * OS_USEC_PER_TICK;
+    os_timeradd(base, &tvdelta, result);
+}
+
+/**
+ * Get the current OS time in ticks
+ *
+ * @return OS time in ticks
+ */
+os_time_t
+os_time_get(void)
+{
+    return (g_os_time);
+}
+
+static void
+os_time_tick(int ticks)
+{
+    os_sr_t sr;
+    os_time_t delta, prev_os_time;
+
+    assert(ticks >= 0);
+
+    OS_ENTER_CRITICAL(sr);
+    prev_os_time = g_os_time;
+    g_os_time += ticks;
+
+    /*
+     * Update 'basetod' when 'g_os_time' crosses the 0x00000000 and
+     * 0x80000000 thresholds.
+     */
+    if ((prev_os_time ^ g_os_time) >> 31) {
+        delta = g_os_time - basetod.ostime;
+        os_deltatime(delta, &basetod.uptime, &basetod.uptime);
+        os_deltatime(delta, &basetod.utctime, &basetod.utctime);
+        basetod.ostime = g_os_time;
+    }
+    OS_EXIT_CRITICAL(sr);
+}
+
+/**
+ * Move OS time forward ticks.
+ *
+ * @param ticks The number of ticks to move time forward.
+ */
+void
+os_time_advance(int ticks)
+{
+    assert(ticks >= 0);
+
+    if (ticks > 0) {
+        if (!os_started()) {
+            g_os_time += ticks;
+        } else {
+            os_time_tick(ticks);
+            os_callout_tick();
+            os_sched_os_timer_exp();
+            os_sched(NULL);
+        }
+    }
+}
+
+/**
+ * Puts the current task to sleep for the specified number of os ticks. There
+ * is no delay if ticks is <= 0.
+ *
+ * @param osticks Number of ticks to delay (<= 0 means no delay).
+ */
+void
+os_time_delay(int32_t osticks)
+{
+    os_sr_t sr;
+
+    if (osticks > 0) {
+        OS_ENTER_CRITICAL(sr);
+        os_sched_sleep(os_sched_get_current_task(), (os_time_t)osticks);
+        OS_EXIT_CRITICAL(sr);
+        os_sched(NULL);
+    }
+}
+
+/**
+ * Set the time of day.  This does not modify os time, but rather just modifies
+ * the offset by which we are tracking real time against os time.
+ *
+ * @param utctime A timeval representing the UTC time we are setting
+ * @param tz The time-zone to apply against the utctime being set.
+ *
+ * @return 0 on success, non-zero on failure.
+ */
+int
+os_settimeofday(struct os_timeval *utctime, struct os_timezone *tz)
+{
+    os_sr_t sr;
+    os_time_t delta;
+
+    OS_ENTER_CRITICAL(sr);
+    if (utctime != NULL) {
+        /*
+         * Update all time-of-day base values.
+         */
+        delta = os_time_get() - basetod.ostime;
+        os_deltatime(delta, &basetod.uptime, &basetod.uptime);
+        basetod.utctime = *utctime;
+        basetod.ostime += delta;
+    }
+
+    if (tz != NULL) {
+        basetod.timezone = *tz;
+    }
+    OS_EXIT_CRITICAL(sr);
+
+    return (0);
+}
+
+/**
+ * Get the current time of day.  Returns the time of day in UTC
+ * into the tv argument, and returns the timezone (if set) into
+ * tz.
+ *
+ * @param tv The structure to put the UTC time of day into
+ * @param tz The structure to put the timezone information into
+ *
+ * @return 0 on success, non-zero on failure
+ */
+int
+os_gettimeofday(struct os_timeval *tv, struct os_timezone *tz)
+{
+    os_sr_t sr;
+    os_time_t delta;
+
+    OS_ENTER_CRITICAL(sr);
+    if (tv != NULL) {
+        delta = os_time_get() - basetod.ostime;
+        os_deltatime(delta, &basetod.utctime, tv);
+    }
+
+    if (tz != NULL) {
+        *tz = basetod.timezone;
+    }
+    OS_EXIT_CRITICAL(sr);
+
+    return (0);
+}
+
+/**
+ * Get time since boot in microseconds.
+ *
+ * @return time since boot in microseconds
+ */
+int64_t
+os_get_uptime_usec(void)
+{
+  struct os_timeval tv;
+  os_time_t delta;
+  os_sr_t sr;
+  os_time_t ostime;
+
+
+  OS_ENTER_CRITICAL(sr);
+  tv = basetod.uptime;
+  ostime = basetod.ostime;
+  delta = os_time_get() - ostime;
+  OS_EXIT_CRITICAL(sr);
+
+  os_deltatime(delta, &tv, &tv);
+
+  return(tv.tv_sec * 1000000 + tv.tv_usec);
+}
+
+/**
+ * Converts milliseconds to OS ticks.
+ *
+ * @param ms                    The milliseconds input.
+ * @param out_ticks             The OS ticks output.
+ *
+ * @return                      0 on success; OS_EINVAL if the result is too
+ *                                  large to fit in a uint32_t.
+ */
+int
+os_time_ms_to_ticks(uint32_t ms, uint32_t *out_ticks)
+{
+    uint64_t ticks;
+
+#if OS_TICKS_PER_SEC == 1000
+    *out_ticks = ms;
+    return 0;
+#endif
+
+    _Static_assert(OS_TICKS_PER_SEC <= UINT32_MAX,
+                   "OS_TICKS_PER_SEC must be <= UINT32_MAX");
+
+    ticks = (uint64_t)ms * OS_TICKS_PER_SEC / 1000;
+    if (ticks > UINT32_MAX) {
+        return OS_EINVAL;
+    }
+
+    *out_ticks = ticks;
+    return 0;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/test/pkg.yml
----------------------------------------------------------------------
diff --git a/kernel/os/test/pkg.yml b/kernel/os/test/pkg.yml
new file mode 100644
index 0000000..378e257
--- /dev/null
+++ b/kernel/os/test/pkg.yml
@@ -0,0 +1,30 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+#
+pkg.name: kernel/os/test
+pkg.type: unittest
+pkg.description: "OS unit tests."
+pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
+pkg.homepage: "http://mynewt.apache.org/"
+pkg.keywords:
+
+pkg.deps: 
+    - kernel/os
+    - test/testutil
+
+pkg.deps.SELFTEST:
+    - sys/console/stub

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/test/src/arch/cortex_m4/os_test_arch_arm.c
----------------------------------------------------------------------
diff --git a/kernel/os/test/src/arch/cortex_m4/os_test_arch_arm.c b/kernel/os/test/src/arch/cortex_m4/os_test_arch_arm.c
new file mode 100644
index 0000000..35134f7
--- /dev/null
+++ b/kernel/os/test/src/arch/cortex_m4/os_test_arch_arm.c
@@ -0,0 +1,27 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include "testutil/testutil.h"
+#include "os_test_priv.h"
+
+void
+os_test_restart(void)
+{
+    tu_restart();
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/test/src/arch/sim/os_test_arch_sim.c
----------------------------------------------------------------------
diff --git a/kernel/os/test/src/arch/sim/os_test_arch_sim.c b/kernel/os/test/src/arch/sim/os_test_arch_sim.c
new file mode 100644
index 0000000..3b6cfbf
--- /dev/null
+++ b/kernel/os/test/src/arch/sim/os_test_arch_sim.c
@@ -0,0 +1,52 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include <stdio.h>
+#include <setjmp.h>
+#include <signal.h>
+#include <string.h>
+#include <sys/time.h>
+#include "testutil/testutil.h"
+#include "os/os.h"
+#include "os_test_priv.h"
+
+void
+os_test_restart(void)
+{
+    struct sigaction sa;
+    struct itimerval it;
+    int rc;
+
+    g_os_started = 0;
+
+    memset(&sa, 0, sizeof sa);
+    sa.sa_handler = SIG_IGN;
+
+    sigaction(SIGALRM, &sa, NULL);
+    sigaction(SIGVTALRM, &sa, NULL);
+
+    memset(&it, 0, sizeof(it));
+    rc = setitimer(ITIMER_VIRTUAL, &it, NULL);
+    if (rc != 0) {
+        perror("Cannot set itimer");
+        abort();
+    }
+
+    tu_restart();
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/test/src/callout_test.c
----------------------------------------------------------------------
diff --git a/kernel/os/test/src/callout_test.c b/kernel/os/test/src/callout_test.c
new file mode 100644
index 0000000..4e3811d
--- /dev/null
+++ b/kernel/os/test/src/callout_test.c
@@ -0,0 +1,330 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+ 
+#include "testutil/testutil.h"
+#include "os/os.h"
+#include "os_test_priv.h"
+#include "os/os_eventq.h"
+#include "os/os_callout.h"
+#include "os/os_time.h"
+
+/* Task 1 for sending */
+#define CALLOUT_STACK_SIZE        (5120)
+#define SEND_CALLOUT_TASK_PRIO        (1)
+struct os_task callout_task_struct_send;
+os_stack_t callout_task_stack_send[CALLOUT_STACK_SIZE];
+
+#define RECEIVE_CALLOUT_TASK_PRIO        (2)
+struct os_task callout_task_struct_receive;
+os_stack_t callout_task_stack_receive[CALLOUT_STACK_SIZE];
+
+/* Delearing variables for callout_func */
+struct os_callout_func callout_func_test;
+
+/* The event to be sent*/
+struct os_eventq callout_evq;
+struct os_event callout_ev;
+
+/* The callout_stop task */
+#define SEND_STOP_CALLOUT_TASK_PRIO        (3)
+struct os_task callout_task_struct_stop_send;
+os_stack_t callout_task_stack_stop_send[CALLOUT_STACK_SIZE];
+
+#define RECEIVE_STOP_CALLOUT_TASK_PRIO        (4)
+struct os_task callout_task_struct_stop_receive;
+os_stack_t callout_task_stack_stop_receive[CALLOUT_STACK_SIZE];
+
+/* Delearing variables for callout_stop_func */
+#define MULTI_SIZE    (2)
+struct os_callout_func callout_func_stop_test[MULTI_SIZE];
+
+/* The event to be sent*/
+struct os_eventq callout_stop_evq[MULTI_SIZE];
+struct os_event callout_stop_ev;
+
+/* Declearing varables for callout_speak */
+#define SPEAK_CALLOUT_TASK_PRIO        (5)
+struct os_task callout_task_struct_speak;
+os_stack_t callout_task_stack_speak[CALLOUT_STACK_SIZE];
+
+/* Declearing varaibles for listen */
+#define LISTEN_CALLOUT_TASK_PRIO        (6)
+struct os_task callout_task_struct_listen;
+os_stack_t callout_task_stack_listen[CALLOUT_STACK_SIZE];
+
+struct os_callout_func callout_func_speak;
+
+/* Global variables to be used by the callout functions */
+int p;
+int q;
+int t;
+/* This is the function for callout_init*/
+void
+my_callout_func(void *arg)
+{
+    p = 4;
+}
+
+/* This is the function for callout_init of stop test_case*/
+void
+my_callout_stop_func(void *arg)
+{
+    q = 1;
+}
+/* This is the function for callout_init for speak test_case*/
+void
+my_callout_speak_func(void *arg)
+{
+    t = 2;
+}
+
+/* This is a callout task to send data */
+void
+callout_task_send(void *arg )
+{
+   int i;
+    /* Should say whether callout is armed or not */
+    i= os_callout_queued(&callout_func_test.cf_c);
+    TEST_ASSERT(i == 0);
+
+    /* Arm the callout */
+    i = os_callout_reset(&callout_func_test.cf_c, OS_TICKS_PER_SEC/ 50);
+    TEST_ASSERT_FATAL(i == 0);
+
+    /* Should say whether callout is armed or not */
+    i = os_callout_queued(&callout_func_test.cf_c);
+    TEST_ASSERT(i == 1);
+
+    /* Send the callout */ 
+    os_time_delay(OS_TICKS_PER_SEC );
+}
+
+/* This is the callout to receive data */
+void
+callout_task_receive( void *arg)
+{
+    int i;
+    struct os_event *event;
+    struct os_callout_func *callout;
+    os_time_t now;
+    os_time_t tm;
+    os_sr_t sr; 
+    /* Recieve using the os_eventq_poll */
+    event = os_eventq_poll(&callout_func_test.cf_c.c_evq, 1, OS_WAIT_FOREVER);
+    TEST_ASSERT(event->ev_type ==  OS_EVENT_T_TIMER);
+    TEST_ASSERT(event->ev_arg == NULL);
+    callout = (struct os_callout_func *)event;
+    TEST_ASSERT(callout->cf_func == my_callout_func);
+
+    /* Should say whether callout is armed or not */
+    i = os_callout_queued(&callout_func_test.cf_c);
+    TEST_ASSERT(i == 0);
+
+    OS_ENTER_CRITICAL(sr);
+    now = os_time_get();
+    tm = os_callout_wakeup_ticks(now);
+    TEST_ASSERT(tm == OS_TIMEOUT_NEVER);
+    OS_EXIT_CRITICAL(sr);
+    
+    /* Finishes the test when OS has been started */
+    os_test_restart();
+
+}
+
+/* This is callout to send the stop_callout */
+void
+callout_task_stop_send( void *arg)
+{
+    int k;
+    int j;    
+     /* Should say whether callout is armed or not */
+    for(k = 0; k<MULTI_SIZE; k++){
+        j = os_callout_queued(&callout_func_stop_test[k].cf_c);
+        TEST_ASSERT(j == 0);
+    }
+
+
+    /* Show that  callout is not armed after calling callout_stop */
+    for(k = 0; k<MULTI_SIZE; k++){
+        os_callout_stop(&callout_func_stop_test[k].cf_c);
+        j = os_callout_queued(&callout_func_stop_test[k].cf_c);
+        TEST_ASSERT(j == 0);
+    }
+    /* Arm the callout */
+    for(k = 0; k<MULTI_SIZE; k++){
+        j = os_callout_reset(&callout_func_stop_test[k].cf_c, OS_TICKS_PER_SEC/ 50);
+        TEST_ASSERT_FATAL(j == 0);
+    }
+    os_time_delay( OS_TICKS_PER_SEC );
+}
+
+/* This is the callout to receive stop_callout data */
+void
+callout_task_stop_receive( void *arg )
+{
+    int k;
+    struct os_event *event;
+    struct os_callout_func *callout;
+    /* Recieving using the os_eventq_poll */
+    for(k=0; k<MULTI_SIZE; k++){
+        event = os_eventq_poll(&callout_func_stop_test[k].cf_c.c_evq, 1,
+           OS_WAIT_FOREVER);
+        TEST_ASSERT(event->ev_type ==  OS_EVENT_T_TIMER);
+        TEST_ASSERT(event->ev_arg == NULL);
+        callout = (struct os_callout_func *)event;
+        TEST_ASSERT(callout->cf_func == my_callout_stop_func);
+
+
+     }
+     
+    /* Show that event is removed from the queued after calling callout_stop */
+    for(k=0; k<MULTI_SIZE; k++){
+        os_callout_stop(&callout_func_stop_test[k].cf_c);
+        /* Testing that the event has been removed from queue */
+        TEST_ASSERT_FATAL(1); 
+     }
+    /* Finishes the test when OS has been started */
+    os_test_restart();
+
+}
+
+/* This is a callout task to send data */
+void
+callout_task_stop_speak( void *arg )
+{
+    int i;
+    /* Arm the callout */
+    i = os_callout_reset(&callout_func_speak.cf_c, OS_TICKS_PER_SEC/ 50);
+    TEST_ASSERT_FATAL(i == 0);
+
+    /* should say whether callout is armed or not */
+    i = os_callout_queued(&callout_func_speak.cf_c);
+    TEST_ASSERT(i == 1);
+
+    os_callout_stop(&callout_func_speak.cf_c);
+    
+    /* Send the callout */ 
+    os_time_delay(OS_TICKS_PER_SEC/ 100 );
+    /* Finishes the test when OS has been started */
+    os_test_restart();
+}
+
+void
+callout_task_stop_listen( void *arg )
+{
+    struct os_event *event;
+    struct os_callout_func *callout;
+    event = os_eventq_get(callout_func_speak.cf_c.c_evq);
+    TEST_ASSERT_FATAL(0);
+    callout = (struct os_callout_func *)event;
+    TEST_ASSERT(callout->cf_func == my_callout_speak_func);
+
+}
+
+/* Test case to test the basics of the callout */
+TEST_CASE(callout_test)
+{
+
+    /* Initializing the OS */
+    os_init();
+    
+    /* Initialize the sending task */
+    os_task_init(&callout_task_struct_send, "callout_task_send",
+        callout_task_send, NULL, SEND_CALLOUT_TASK_PRIO, OS_WAIT_FOREVER,
+        callout_task_stack_send, CALLOUT_STACK_SIZE);
+
+    /* Initialize the receive task */
+    os_task_init(&callout_task_struct_receive, "callout_task_receive",
+        callout_task_receive, NULL, RECEIVE_CALLOUT_TASK_PRIO, OS_WAIT_FOREVER,
+        callout_task_stack_receive, CALLOUT_STACK_SIZE);
+
+    os_eventq_init(&callout_evq);
+    
+    /* Initialize the callout function */
+    os_callout_func_init(&callout_func_test, &callout_evq,
+        my_callout_func, NULL);
+
+    /* Does not return until OS_restart is called */
+    os_start();
+}
+
+/* Test case of the callout_task_stop */
+TEST_CASE(callout_test_stop)
+{
+    int k;
+    /* Initializing the OS */
+    os_init();
+
+    /* Initialize the sending task */
+    os_task_init(&callout_task_struct_stop_send, "callout_task_stop_send",
+        callout_task_stop_send, NULL, SEND_STOP_CALLOUT_TASK_PRIO, OS_WAIT_FOREVER,
+        callout_task_stack_stop_send, CALLOUT_STACK_SIZE);
+
+    /* Initialize the receiving task */
+    os_task_init(&callout_task_struct_stop_receive, "callout_task_stop_receive",
+        callout_task_stop_receive, NULL, RECEIVE_STOP_CALLOUT_TASK_PRIO,
+        OS_WAIT_FOREVER, callout_task_stack_stop_receive, CALLOUT_STACK_SIZE);
+
+    for(k = 0; k< MULTI_SIZE; k++){
+        os_eventq_init(&callout_stop_evq[k]);
+    }
+    
+    /* Initialize the callout function */
+    for(k = 0; k<MULTI_SIZE; k++){
+        os_callout_func_init(&callout_func_stop_test[k], &callout_stop_evq[k],
+           my_callout_stop_func, NULL);
+    }
+
+    /* Does not return until OS_restart is called */
+    os_start();
+
+}
+
+/* Test case to test case for speak and listen */
+TEST_CASE(callout_test_speak)
+{
+    /* Initializing the OS */
+    os_init();
+    
+    /* Initialize the sending task */
+    os_task_init(&callout_task_struct_speak, "callout_task_speak",
+        callout_task_stop_speak, NULL, SPEAK_CALLOUT_TASK_PRIO, OS_WAIT_FOREVER,
+        callout_task_stack_speak, CALLOUT_STACK_SIZE);
+
+    /* Initialize the receive task */
+    os_task_init(&callout_task_struct_listen, "callout_task_listen",
+        callout_task_stop_listen, NULL, LISTEN_CALLOUT_TASK_PRIO, OS_WAIT_FOREVER,
+        callout_task_stack_listen, CALLOUT_STACK_SIZE);
+
+    os_eventq_init(&callout_evq);
+    
+    /* Initialize the callout function */
+    os_callout_func_init(&callout_func_speak, &callout_evq,
+        my_callout_speak_func, NULL);    
+    /* Does not return until OS_restart is called */
+    os_start();
+
+}
+
+TEST_SUITE(os_callout_test_suite)
+{   
+    callout_test();
+    callout_test_stop();
+    callout_test_speak();
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/test/src/eventq_test.c
----------------------------------------------------------------------
diff --git a/kernel/os/test/src/eventq_test.c b/kernel/os/test/src/eventq_test.c
new file mode 100644
index 0000000..3fceb0e
--- /dev/null
+++ b/kernel/os/test/src/eventq_test.c
@@ -0,0 +1,416 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+ 
+#include <string.h>
+#include "testutil/testutil.h"
+#include "os/os.h"
+#include "os_test_priv.h"
+#include "os/os_eventq.h"
+
+#define MY_STACK_SIZE        (5120)
+#define POLL_STACK_SIZE        (4096)
+/* Task 1 sending task */
+/* Define task stack and task object */
+#define SEND_TASK_PRIO        (1)
+struct os_task eventq_task_s;
+os_stack_t eventq_task_stack_s[MY_STACK_SIZE];
+
+/* Task 2 receiving task */
+#define RECEIVE_TASK_PRIO     (2)
+struct os_task eventq_task_r;
+os_stack_t eventq_task_stack_r[MY_STACK_SIZE];
+
+struct os_eventq my_eventq;
+
+#define SIZE_MULTI_EVENT        (4)
+struct os_eventq multi_eventq[SIZE_MULTI_EVENT];
+
+/* This is to set the events we will use below */
+struct os_event g_event;
+struct os_event m_event[SIZE_MULTI_EVENT];
+
+/* Setting the event to send and receive multiple data */
+uint8_t my_event_type = 1;
+
+/* Setting up data for the poll */
+/* Define the task stack for the eventq_task_poll_send */
+#define SEND_TASK_POLL_PRIO        (3)
+struct os_task eventq_task_poll_s;
+os_stack_t eventq_task_stack_poll_s[POLL_STACK_SIZE];
+
+/* Define the task stack for the eventq_task_poll_receive */
+#define RECEIVE_TASK_POLL_PRIO     (4)
+struct os_task eventq_task_poll_r;
+os_stack_t eventq_task_stack_poll_r[POLL_STACK_SIZE ];
+
+/* Setting the data for the poll timeout */
+/* Define the task stack for the eventq_task_poll_timeout_send */
+#define SEND_TASK_POLL_TIMEOUT_PRIO        (5)
+struct os_task eventq_task_poll_timeout_s;
+os_stack_t eventq_task_stack_poll_timeout_s[POLL_STACK_SIZE];
+
+/* Define the task stack for the eventq_task_poll_receive */
+#define RECEIVE_TASK_POLL_TIMEOUT_PRIO     (6)
+struct os_task eventq_task_poll_timeout_r;
+os_stack_t eventq_task_stack_poll_timeout_r[POLL_STACK_SIZE];
+
+/* Setting the data for the poll single */
+/* Define the task stack for the eventq_task_poll_single_send */
+#define SEND_TASK_POLL_SINGLE_PRIO        (7)
+struct os_task eventq_task_poll_single_s;
+os_stack_t eventq_task_stack_poll_single_s[POLL_STACK_SIZE];
+
+/* Define the task stack for the eventq_task_poll_single_receive */
+#define RECEIVE_TASK_POLL_SINGLE_PRIO     (8)
+struct os_task eventq_task_poll_single_r;
+os_stack_t eventq_task_stack_poll_single_r[POLL_STACK_SIZE];
+
+/* This is the task function  to send data */
+void
+eventq_task_send(void *arg)
+{
+    int i;
+
+    g_event.ev_queued = 0;
+    g_event.ev_type = my_event_type;
+    g_event.ev_arg = NULL;
+
+    os_eventq_put(&my_eventq, &g_event);
+
+    os_time_delay(OS_TICKS_PER_SEC / 2);
+
+    for (i = 0; i < SIZE_MULTI_EVENT; i++){
+        m_event[i].ev_type = i + 2;
+        m_event[i].ev_arg = NULL;
+
+        /* Put and send */
+        os_eventq_put(&multi_eventq[i], &m_event[i]);
+        os_time_delay(OS_TICKS_PER_SEC / 2);
+    }
+
+    /* This task sleeps until the receive task completes the test. */
+    os_time_delay(1000000);
+}
+
+/* This is the task function is the receiving function */
+void
+eventq_task_receive(void *arg)
+{
+    struct os_event *event;
+    int i;
+
+    event = os_eventq_get(&my_eventq);
+    TEST_ASSERT(event->ev_type == my_event_type);
+
+    /* Receiving multi event from the send task */
+    for (i = 0; i < SIZE_MULTI_EVENT; i++) {
+        event = os_eventq_get(&multi_eventq[i]);
+        TEST_ASSERT(event->ev_type == i + 2);
+    }
+
+    /* Finishes the test when OS has been started */
+    os_test_restart();
+}
+
+void
+eventq_task_poll_send(void *arg)
+{
+    struct os_eventq *eventqs[SIZE_MULTI_EVENT];
+    int i;
+
+    for (i = 0; i < SIZE_MULTI_EVENT; i++){
+        eventqs[i] = &multi_eventq[i];
+    }
+
+    for (i = 0; i < SIZE_MULTI_EVENT; i++){
+        m_event[i].ev_type = i + 10;
+        m_event[i].ev_arg = NULL;
+
+        /* Put and send */
+        os_eventq_put(eventqs[i], &m_event[i]);
+        os_time_delay(OS_TICKS_PER_SEC / 2);
+    }
+
+    /* This task sleeps until the receive task completes the test. */
+    os_time_delay(1000000);
+}
+
+void
+eventq_task_poll_receive(void *arg)
+{
+    struct os_eventq *eventqs[SIZE_MULTI_EVENT];
+    struct os_event *event;
+    int i;
+
+    for (i = 0; i < SIZE_MULTI_EVENT; i++){
+        eventqs[i] = &multi_eventq[i];
+    }
+
+    /* Recieving using the os_eventq_poll*/
+    for (i = 0; i < SIZE_MULTI_EVENT; i++) {
+        event = os_eventq_poll(eventqs, SIZE_MULTI_EVENT, OS_WAIT_FOREVER);
+        TEST_ASSERT(event->ev_type == i +10);
+    }
+
+    /* Finishes the test when OS has been started */
+    os_test_restart();
+
+}
+
+/* Sending with a time failure */
+void
+eventq_task_poll_timeout_send(void *arg)
+{
+    struct os_eventq *eventqs[SIZE_MULTI_EVENT];
+    int i;
+
+    for (i = 0; i < SIZE_MULTI_EVENT; i++){
+        eventqs[i] = &multi_eventq[i];
+    }
+
+    for (i = 0; i < SIZE_MULTI_EVENT; i++){
+         os_time_delay(OS_TICKS_PER_SEC);
+
+        /* Put and send */
+        os_eventq_put(eventqs[i], &m_event[i]);
+        os_time_delay(OS_TICKS_PER_SEC / 2);
+    }
+
+    /* This task sleeps until the receive task completes the test. */
+    os_time_delay(1000000);
+    
+}
+
+/* Receiving multiple event queues with a time failure */
+void
+eventq_task_poll_timeout_receive(void *arg)
+{
+    struct os_eventq *eventqs[SIZE_MULTI_EVENT];
+    struct os_event *event;
+    int i;
+
+    for (i = 0; i < SIZE_MULTI_EVENT; i++){
+        eventqs[i] = &multi_eventq[i];
+    }
+
+    /* Recieving using the os_eventq_poll_timeout*/
+    for (i = 0; i < SIZE_MULTI_EVENT; i++) {
+        event = os_eventq_poll(eventqs, SIZE_MULTI_EVENT, OS_TICKS_PER_SEC / 5);
+        TEST_ASSERT(event == NULL);
+    }
+
+    /* Finishes the test when OS has been started */
+    os_test_restart();
+
+}
+
+/* Sending a single event to poll */
+void
+eventq_task_poll_single_send(void *arg)
+{
+    struct os_eventq *eventqs[SIZE_MULTI_EVENT];
+    int i;
+    int position = 2;
+
+    for (i = 0; i < SIZE_MULTI_EVENT; i++){
+        eventqs[i] = &multi_eventq[i];
+    }
+
+    /* Put and send */
+    os_eventq_put(eventqs[position], &m_event[position]);
+    os_time_delay(OS_TICKS_PER_SEC / 2);
+
+    /* This task sleeps until the receive task completes the test. */
+    os_time_delay(1000000);
+}
+
+/* Recieving the single event */
+void
+eventq_task_poll_single_receive(void *arg)
+{
+    struct os_eventq *eventqs[SIZE_MULTI_EVENT];
+    struct os_event *event;
+    int i;
+
+    for (i = 0; i < SIZE_MULTI_EVENT; i++){
+        eventqs[i] = &multi_eventq[i];
+    }
+
+    /* Recieving using the os_eventq_poll*/
+    event = os_eventq_poll(eventqs, SIZE_MULTI_EVENT, OS_WAIT_FOREVER);
+    TEST_ASSERT(event->ev_type == 20);
+
+    /* Finishes the test when OS has been started */
+    os_test_restart();
+}
+
+TEST_CASE(event_test_sr)
+{
+    int i;
+
+    /* Initializing the OS */
+    os_init();
+    /* Initialize the task */
+    os_task_init(&eventq_task_s, "eventq_task_s", eventq_task_send, NULL,
+        SEND_TASK_PRIO, OS_WAIT_FOREVER, eventq_task_stack_s, MY_STACK_SIZE);
+
+    /* Receive events and check whether the eevnts are correctly received */
+    os_task_init(&eventq_task_r, "eventq_task_r", eventq_task_receive, NULL,
+        RECEIVE_TASK_PRIO, OS_WAIT_FOREVER, eventq_task_stack_r,
+        MY_STACK_SIZE);
+
+    os_eventq_init(&my_eventq);
+
+    for (i = 0; i < SIZE_MULTI_EVENT; i++){
+        os_eventq_init(&multi_eventq[i]);
+    }
+
+    /* Does not return until OS_restart is called */
+    os_start();
+
+}
+
+/* To test for the basic function of os_eventq_poll() */
+TEST_CASE(event_test_poll_sr)
+{
+    int i;
+
+    /* Initializing the OS */
+    os_init();
+    /* Initialize the task */
+    os_task_init(&eventq_task_poll_s, "eventq_task_poll_s", eventq_task_poll_send,
+        NULL, SEND_TASK_POLL_PRIO, OS_WAIT_FOREVER, eventq_task_stack_poll_s, 
+        POLL_STACK_SIZE);
+
+    /* Receive events and check whether the eevnts are correctly received */
+    os_task_init(&eventq_task_poll_r, "eventq_task_r", eventq_task_poll_receive,
+        NULL, RECEIVE_TASK_POLL_PRIO, OS_WAIT_FOREVER, eventq_task_stack_poll_r,
+        POLL_STACK_SIZE);
+
+    /* Initializing the eventqs. */
+    for (i = 0; i < SIZE_MULTI_EVENT; i++){
+        os_eventq_init(&multi_eventq[i]);
+    }
+
+    /* Does not return until OS_restart is called */
+    os_start();
+
+}
+
+/* Test case for poll timeout */
+TEST_CASE(event_test_poll_timeout_sr)
+{
+    int i;
+
+    /* Initializing the OS */
+    os_init();
+    /* Initialize the task */
+    os_task_init(&eventq_task_poll_timeout_s, "eventq_task_poll_timeout_s", 
+        eventq_task_poll_timeout_send, NULL, SEND_TASK_POLL_TIMEOUT_PRIO,
+        OS_WAIT_FOREVER, eventq_task_stack_poll_timeout_s, POLL_STACK_SIZE);
+
+    /* Receive events and check whether the eevnts are correctly received */
+    os_task_init(&eventq_task_poll_timeout_r, "eventq_task_timeout_r",
+        eventq_task_poll_timeout_receive, NULL, RECEIVE_TASK_POLL_TIMEOUT_PRIO,
+        OS_WAIT_FOREVER, eventq_task_stack_poll_timeout_r, POLL_STACK_SIZE);
+
+    /* Initializing the eventqs. */
+    for (i = 0; i < SIZE_MULTI_EVENT; i++){
+        os_eventq_init(&multi_eventq[i]);
+
+        m_event[i].ev_type = i + 10;
+        m_event[i].ev_arg = NULL;
+    }
+
+    /* Does not return until OS_restart is called */
+    os_start();
+
+}
+
+/* The case for poll single */
+/* Test case for poll timeout */
+TEST_CASE(event_test_poll_single_sr)
+{
+    int i;
+
+    /* Initializing the OS */
+    os_init();
+    /* Initialize the task */
+    os_task_init(&eventq_task_poll_single_s, "eventq_task_poll_single_s", 
+        eventq_task_poll_single_send, NULL, SEND_TASK_POLL_SINGLE_PRIO,
+        OS_WAIT_FOREVER, eventq_task_stack_poll_single_s, POLL_STACK_SIZE);
+
+    /* Receive events and check whether the eevnts are correctly received */
+    os_task_init(&eventq_task_poll_single_r, "eventq_task_single_r",
+        eventq_task_poll_single_receive, NULL, RECEIVE_TASK_POLL_SINGLE_PRIO,
+        OS_WAIT_FOREVER, eventq_task_stack_poll_single_r, POLL_STACK_SIZE);
+
+    for (i = 0; i < SIZE_MULTI_EVENT; i++){
+        os_eventq_init(&multi_eventq[i]);
+
+        m_event[i].ev_type = 10 * i;
+        m_event[i].ev_arg = NULL;
+    }
+
+    /* Does not return until OS_restart is called */
+    os_start();
+
+}
+
+/**
+ * Tests eventq_poll() with a timeout of 0.  This should not involve the
+ * scheduler at all, so it should work without starting the OS.
+ */
+TEST_CASE(event_test_poll_0timo)
+{
+    struct os_eventq *eventqs[SIZE_MULTI_EVENT];
+    struct os_event *evp;
+    struct os_event ev;
+    int i;
+
+    for (i = 0; i < SIZE_MULTI_EVENT; i++){
+        os_eventq_init(&multi_eventq[i]);
+        eventqs[i] = &multi_eventq[i];
+    }
+
+    evp = os_eventq_poll(eventqs, SIZE_MULTI_EVENT, 0);
+    TEST_ASSERT(evp == NULL);
+
+    /* Ensure no eventq thinks a task is waiting on it. */
+    for (i = 0; i < SIZE_MULTI_EVENT; i++) {
+        TEST_ASSERT(eventqs[i]->evq_task == NULL);
+    }
+
+    /* Put an event on one of the queues. */
+    memset(&ev, 0, sizeof ev);
+    ev.ev_type = 1;
+    os_eventq_put(eventqs[3], &ev);
+
+    evp = os_eventq_poll(eventqs, SIZE_MULTI_EVENT, 0);
+    TEST_ASSERT(evp == &ev);
+}
+
+TEST_SUITE(os_eventq_test_suite)
+{
+    event_test_sr();
+    event_test_poll_sr();
+    event_test_poll_timeout_sr();
+    event_test_poll_single_sr();
+    event_test_poll_0timo();
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/test/src/mbuf_test.c
----------------------------------------------------------------------
diff --git a/kernel/os/test/src/mbuf_test.c b/kernel/os/test/src/mbuf_test.c
new file mode 100644
index 0000000..dd4121d
--- /dev/null
+++ b/kernel/os/test/src/mbuf_test.c
@@ -0,0 +1,420 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include "testutil/testutil.h"
+#include "os/os.h"
+#include "os_test_priv.h"
+
+#include <string.h>
+
+/* 
+ * NOTE: currently, the buffer size cannot be changed as some tests are
+ * hard-coded for this size.
+ */
+#define MBUF_TEST_POOL_BUF_SIZE     (256)
+#define MBUF_TEST_POOL_BUF_COUNT    (10)
+
+#define MBUF_TEST_DATA_LEN          (1024)
+
+static os_membuf_t os_mbuf_membuf[OS_MEMPOOL_SIZE(MBUF_TEST_POOL_BUF_SIZE,
+        MBUF_TEST_POOL_BUF_COUNT)];
+
+static struct os_mbuf_pool os_mbuf_pool;
+static struct os_mempool os_mbuf_mempool;
+static uint8_t os_mbuf_test_data[MBUF_TEST_DATA_LEN];
+
+static void
+os_mbuf_test_setup(void)
+{
+    int rc;
+    int i;
+
+    rc = os_mempool_init(&os_mbuf_mempool, MBUF_TEST_POOL_BUF_COUNT,
+            MBUF_TEST_POOL_BUF_SIZE, &os_mbuf_membuf[0], "mbuf_pool");
+    TEST_ASSERT_FATAL(rc == 0, "Error creating memory pool %d", rc);
+
+    rc = os_mbuf_pool_init(&os_mbuf_pool, &os_mbuf_mempool,
+            MBUF_TEST_POOL_BUF_SIZE, MBUF_TEST_POOL_BUF_COUNT);
+    TEST_ASSERT_FATAL(rc == 0, "Error creating mbuf pool %d", rc);
+
+    for (i = 0; i < sizeof os_mbuf_test_data; i++) {
+        os_mbuf_test_data[i] = i;
+    }
+}
+
+static void
+os_mbuf_test_misc_assert_sane(struct os_mbuf *om, void *data,
+                              int buflen, int pktlen, int pkthdr_len)
+{
+    uint8_t *data_min;
+    uint8_t *data_max;
+    int totlen;
+    int i;
+
+    TEST_ASSERT_FATAL(om != NULL);
+
+    if (OS_MBUF_IS_PKTHDR(om)) {
+        TEST_ASSERT(OS_MBUF_PKTLEN(om) == pktlen);
+    }
+
+    totlen = 0;
+    for (i = 0; om != NULL; i++) {
+        if (i == 0) {
+            TEST_ASSERT(om->om_len == buflen);
+            TEST_ASSERT(om->om_pkthdr_len == pkthdr_len);
+        }
+
+        data_min = om->om_databuf + om->om_pkthdr_len;
+        data_max = om->om_databuf + om->om_omp->omp_databuf_len - om->om_len;
+        TEST_ASSERT(om->om_data >= data_min && om->om_data <= data_max);
+
+        if (data != NULL) {
+            TEST_ASSERT(memcmp(om->om_data, data + totlen, om->om_len) == 0);
+        }
+
+        totlen += om->om_len;
+        om = SLIST_NEXT(om, om_next);
+    }
+
+    TEST_ASSERT(totlen == pktlen);
+}
+
+
+TEST_CASE(os_mbuf_test_alloc)
+{
+    struct os_mbuf *m;
+    int rc;
+
+    os_mbuf_test_setup();
+
+    m = os_mbuf_get(&os_mbuf_pool, 0);
+    TEST_ASSERT_FATAL(m != NULL, "Error allocating mbuf");
+
+    rc = os_mbuf_free(m);
+    TEST_ASSERT_FATAL(rc == 0, "Error free'ing mbuf %d", rc);
+}
+
+TEST_CASE(os_mbuf_test_get_pkthdr)
+{
+    struct os_mbuf *m;
+ 
+    os_mbuf_test_setup();
+
+#if (MBUF_TEST_POOL_BUF_SIZE <= 256)
+    m = os_mbuf_get_pkthdr(&os_mbuf_pool, MBUF_TEST_POOL_BUF_SIZE - 1);
+    TEST_ASSERT_FATAL(m == NULL, "Error: should not have returned mbuf");
+#endif
+
+    m = os_mbuf_get(&os_mbuf_pool, MBUF_TEST_POOL_BUF_SIZE);
+    TEST_ASSERT_FATAL(m == NULL, "Error: should not have returned mbuf");
+}
+
+
+TEST_CASE(os_mbuf_test_dup)
+{
+    struct os_mbuf *om;
+    struct os_mbuf *om2;
+    struct os_mbuf *dup;
+    int rc;
+
+    os_mbuf_test_setup();
+
+    /* Test first allocating and duplicating a single mbuf */
+    om = os_mbuf_get(&os_mbuf_pool, 0);
+    TEST_ASSERT_FATAL(om != NULL, "Error allocating mbuf");
+
+    rc = os_mbuf_append(om, os_mbuf_test_data, 200);
+    TEST_ASSERT_FATAL(rc == 0);
+    os_mbuf_test_misc_assert_sane(om, os_mbuf_test_data, 200, 200, 0);
+
+    dup = os_mbuf_dup(om);
+    TEST_ASSERT_FATAL(dup != NULL, "NULL mbuf returned from dup");
+    TEST_ASSERT_FATAL(dup != om, "duplicate matches original.");
+    os_mbuf_test_misc_assert_sane(dup, os_mbuf_test_data, 200, 200, 0);
+
+    rc = os_mbuf_free(om);
+    TEST_ASSERT_FATAL(rc == 0, "Error free'ing mbuf om %d", rc);
+
+    rc = os_mbuf_free(dup);
+    TEST_ASSERT_FATAL(rc == 0, "Error free'ing mbuf dup %d", rc);
+
+    om = os_mbuf_get(&os_mbuf_pool, 0);
+    TEST_ASSERT_FATAL(om != NULL, "Error allocating mbuf");
+    rc = os_mbuf_append(om, os_mbuf_test_data, 200);
+    TEST_ASSERT_FATAL(rc == 0);
+    os_mbuf_test_misc_assert_sane(om, os_mbuf_test_data, 200, 200, 0);
+
+    om2 = os_mbuf_get(&os_mbuf_pool, 0);
+    TEST_ASSERT_FATAL(om2 != NULL, "Error allocating mbuf");
+    rc = os_mbuf_append(om2, os_mbuf_test_data + 200, 200);
+    TEST_ASSERT_FATAL(rc == 0);
+    os_mbuf_test_misc_assert_sane(om2, os_mbuf_test_data + 200, 200, 200, 0);
+
+    os_mbuf_concat(om, om2);
+    os_mbuf_test_misc_assert_sane(om, os_mbuf_test_data, 200, 400, 0);
+
+    dup = os_mbuf_dup(om);
+    TEST_ASSERT_FATAL(dup != NULL, "NULL mbuf returned from dup");
+    TEST_ASSERT_FATAL(dup != om, "Duplicate matches original");
+    TEST_ASSERT_FATAL(SLIST_NEXT(dup, om_next) != NULL,
+            "NULL chained element, duplicate should match original");
+
+    os_mbuf_test_misc_assert_sane(dup, os_mbuf_test_data, 200, 400, 0);
+
+    rc = os_mbuf_free_chain(om);
+    TEST_ASSERT_FATAL(rc == 0, "Cannot free mbuf chain %d", rc);
+
+    rc = os_mbuf_free_chain(dup);
+    TEST_ASSERT_FATAL(rc == 0, "Cannot free mbuf chain %d", rc);
+}
+
+TEST_CASE(os_mbuf_test_append)
+{
+    struct os_mbuf *om;
+    int rc;
+    uint8_t databuf[] = {0xa, 0xb, 0xc, 0xd};
+    uint8_t cmpbuf[] = {0xff, 0xff, 0xff, 0xff};
+
+    os_mbuf_test_setup();
+
+    om = os_mbuf_get(&os_mbuf_pool, 0);
+    TEST_ASSERT_FATAL(om != NULL, "Error allocating mbuf");
+    os_mbuf_test_misc_assert_sane(om, NULL, 0, 0, 0);
+
+    rc = os_mbuf_append(om, databuf, sizeof(databuf));
+    TEST_ASSERT_FATAL(rc == 0, "Cannot add %d bytes to mbuf",
+            sizeof(databuf));
+    os_mbuf_test_misc_assert_sane(om, databuf, sizeof databuf, sizeof databuf,
+                                  0);
+
+    memcpy(cmpbuf, OS_MBUF_DATA(om, uint8_t *), om->om_len);
+    TEST_ASSERT_FATAL(memcmp(cmpbuf, databuf, sizeof(databuf)) == 0,
+            "Databuf doesn't match cmpbuf");
+}
+
+TEST_CASE(os_mbuf_test_extend)
+{
+    struct os_mbuf *om;
+    void *v;
+
+    os_mbuf_test_setup();
+
+    /*** Series of successful extensions. */
+    om = os_mbuf_get_pkthdr(&os_mbuf_pool, 10);
+    TEST_ASSERT_FATAL(om != NULL);
+
+    TEST_ASSERT(OS_MBUF_TRAILINGSPACE(om) == 222);
+    TEST_ASSERT(SLIST_NEXT(om, om_next) == NULL);
+    os_mbuf_test_misc_assert_sane(om, NULL, 0, 0, 18);
+
+    v = os_mbuf_extend(om, 20);
+    TEST_ASSERT(v != NULL);
+    TEST_ASSERT(v == om->om_data);
+    TEST_ASSERT(om->om_len == 20);
+
+    TEST_ASSERT(OS_MBUF_TRAILINGSPACE(om) == 202);
+    TEST_ASSERT(SLIST_NEXT(om, om_next) == NULL);
+    os_mbuf_test_misc_assert_sane(om, NULL, 20, 20, 18);
+
+    v = os_mbuf_extend(om, 100);
+    TEST_ASSERT(v != NULL);
+    TEST_ASSERT(v == om->om_data + 20);
+    TEST_ASSERT(om->om_len == 120);
+
+    TEST_ASSERT(OS_MBUF_TRAILINGSPACE(om) == 102);
+    TEST_ASSERT(SLIST_NEXT(om, om_next) == NULL);
+    os_mbuf_test_misc_assert_sane(om, NULL, 120, 120, 18);
+
+    v = os_mbuf_extend(om, 101);
+    TEST_ASSERT(v != NULL);
+    TEST_ASSERT(v == om->om_data + 120);
+    TEST_ASSERT(om->om_len == 221);
+
+    TEST_ASSERT(OS_MBUF_TRAILINGSPACE(om) == 1);
+    TEST_ASSERT(SLIST_NEXT(om, om_next) == NULL);
+    os_mbuf_test_misc_assert_sane(om, NULL, 221, 221, 18);
+
+    v = os_mbuf_extend(om, 1);
+    TEST_ASSERT(v != NULL);
+    TEST_ASSERT(v == om->om_data + 221);
+    TEST_ASSERT(om->om_len == 222);
+
+    TEST_ASSERT(OS_MBUF_TRAILINGSPACE(om) == 0);
+    TEST_ASSERT(SLIST_NEXT(om, om_next) == NULL);
+    os_mbuf_test_misc_assert_sane(om, NULL, 222, 222, 18);
+
+    /* Overflow into next buffer. */
+    v = os_mbuf_extend(om, 1);
+    TEST_ASSERT(OS_MBUF_TRAILINGSPACE(om) == 0);
+    TEST_ASSERT(SLIST_NEXT(om, om_next) != NULL);
+
+    TEST_ASSERT(v == SLIST_NEXT(om, om_next)->om_data);
+    TEST_ASSERT(om->om_len == 222);
+    TEST_ASSERT(SLIST_NEXT(om, om_next)->om_len == 1);
+    os_mbuf_test_misc_assert_sane(om, NULL, 222, 223, 18);
+
+    /*** Attempt to extend by an amount larger than max buf size fails. */
+    v = os_mbuf_extend(om, 257);
+    TEST_ASSERT(v == NULL);
+    TEST_ASSERT(OS_MBUF_TRAILINGSPACE(om) == 0);
+    TEST_ASSERT(SLIST_NEXT(om, om_next) != NULL);
+
+    TEST_ASSERT(om->om_len == 222);
+    TEST_ASSERT(SLIST_NEXT(om, om_next)->om_len == 1);
+    os_mbuf_test_misc_assert_sane(om, NULL, 222, 223, 18);
+}
+
+TEST_CASE(os_mbuf_test_pullup)
+{
+    struct os_mbuf *om;
+    struct os_mbuf *om2;
+    int rc;
+
+    os_mbuf_test_setup();
+
+    /*** Free when too much os_mbuf_test_data is requested. */
+    om = os_mbuf_get_pkthdr(&os_mbuf_pool, 10);
+    TEST_ASSERT_FATAL(om != NULL);
+
+    om = os_mbuf_pullup(om, 1);
+    TEST_ASSERT(om == NULL);
+
+    /*** No effect when all os_mbuf_test_data is already at the start. */
+    om = os_mbuf_get_pkthdr(&os_mbuf_pool, 10);
+    TEST_ASSERT_FATAL(om != NULL);
+
+    rc = os_mbuf_append(om, os_mbuf_test_data, 1);
+    TEST_ASSERT_FATAL(rc == 0);
+    os_mbuf_test_misc_assert_sane(om, os_mbuf_test_data, 1, 1, 18);
+
+    om = os_mbuf_pullup(om, 1);
+    os_mbuf_test_misc_assert_sane(om, os_mbuf_test_data, 1, 1, 18);
+
+    /*** Spread os_mbuf_test_data across four mbufs. */
+    om2 = os_mbuf_get(&os_mbuf_pool, 10);
+    TEST_ASSERT_FATAL(om2 != NULL);
+    rc = os_mbuf_append(om2, os_mbuf_test_data + 1, 1);
+    TEST_ASSERT_FATAL(rc == 0);
+    os_mbuf_concat(om, om2);
+
+    om2 = os_mbuf_get(&os_mbuf_pool, 10);
+    TEST_ASSERT_FATAL(om2 != NULL);
+    rc = os_mbuf_append(om2, os_mbuf_test_data + 2, 1);
+    TEST_ASSERT_FATAL(rc == 0);
+    os_mbuf_concat(om, om2);
+
+    om2 = os_mbuf_get(&os_mbuf_pool, 10);
+    TEST_ASSERT_FATAL(om2 != NULL);
+    rc = os_mbuf_append(om2, os_mbuf_test_data + 3, 1);
+    TEST_ASSERT_FATAL(rc == 0);
+    os_mbuf_concat(om, om2);
+
+    TEST_ASSERT_FATAL(OS_MBUF_PKTLEN(om) == 4);
+
+    om = os_mbuf_pullup(om, 4);
+    os_mbuf_test_misc_assert_sane(om, os_mbuf_test_data, 4, 4, 18);
+
+    os_mbuf_free_chain(om);
+
+    /*** Require an allocation. */
+    om = os_mbuf_get_pkthdr(&os_mbuf_pool, 10);
+    TEST_ASSERT_FATAL(om != NULL);
+
+    om->om_data += 100;
+    rc = os_mbuf_append(om, os_mbuf_test_data, 100);
+    TEST_ASSERT_FATAL(rc == 0);
+
+    om2 = os_mbuf_get(&os_mbuf_pool, 10);
+    TEST_ASSERT_FATAL(om2 != NULL);
+    rc = os_mbuf_append(om2, os_mbuf_test_data + 100, 100);
+    TEST_ASSERT_FATAL(rc == 0);
+    os_mbuf_concat(om, om2);
+
+    om = os_mbuf_pullup(om, 200);
+    os_mbuf_test_misc_assert_sane(om, os_mbuf_test_data, 200, 200, 18);
+
+    /*** Partial pullup. */
+    om = os_mbuf_get_pkthdr(&os_mbuf_pool, 10);
+    TEST_ASSERT_FATAL(om != NULL);
+
+    om->om_data += 100;
+    rc = os_mbuf_append(om, os_mbuf_test_data, 100);
+    TEST_ASSERT_FATAL(rc == 0);
+
+    om2 = os_mbuf_get(&os_mbuf_pool, 10);
+    TEST_ASSERT_FATAL(om2 != NULL);
+    rc = os_mbuf_append(om2, os_mbuf_test_data + 100, 100);
+    TEST_ASSERT_FATAL(rc == 0);
+    os_mbuf_concat(om, om2);
+
+    om = os_mbuf_pullup(om, 150);
+    os_mbuf_test_misc_assert_sane(om, os_mbuf_test_data, 150, 200, 18);
+}
+
+TEST_CASE(os_mbuf_test_adj)
+{
+    struct os_mbuf *om;
+    int rc;
+
+    os_mbuf_test_setup();
+
+    om = os_mbuf_get_pkthdr(&os_mbuf_pool, 10);
+    TEST_ASSERT_FATAL(om != NULL);
+
+    rc = os_mbuf_append(om, os_mbuf_test_data, sizeof os_mbuf_test_data);
+    TEST_ASSERT_FATAL(rc == 0);
+
+    os_mbuf_test_misc_assert_sane(om, os_mbuf_test_data, 222,
+                                  sizeof os_mbuf_test_data, 18);
+
+    /* Remove from the front. */
+    os_mbuf_adj(om, 10);
+    os_mbuf_test_misc_assert_sane(om, os_mbuf_test_data + 10, 212,
+                                  sizeof os_mbuf_test_data - 10, 18);
+
+    /* Remove from the back. */
+    os_mbuf_adj(om, -10);
+    os_mbuf_test_misc_assert_sane(om, os_mbuf_test_data + 10, 212,
+                                  sizeof os_mbuf_test_data - 20, 18);
+
+    /* Remove entire first buffer. */
+    os_mbuf_adj(om, 212);
+    os_mbuf_test_misc_assert_sane(om, os_mbuf_test_data + 222, 0,
+                                  sizeof os_mbuf_test_data - 232, 18);
+
+    /* Remove next buffer. */
+    os_mbuf_adj(om, 256);
+    os_mbuf_test_misc_assert_sane(om, os_mbuf_test_data + 478, 0,
+                                  sizeof os_mbuf_test_data - 488, 18);
+
+    /* Remove more data than is present. */
+    os_mbuf_adj(om, 1000);
+    os_mbuf_test_misc_assert_sane(om, NULL, 0, 0, 18);
+}
+
+TEST_SUITE(os_mbuf_test_suite)
+{
+    os_mbuf_test_alloc();
+    os_mbuf_test_dup();
+    os_mbuf_test_append();
+    os_mbuf_test_pullup();
+    os_mbuf_test_extend();
+    os_mbuf_test_adj();
+    os_mbuf_test_get_pkthdr();
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/test/src/mempool_test.c
----------------------------------------------------------------------
diff --git a/kernel/os/test/src/mempool_test.c b/kernel/os/test/src/mempool_test.c
new file mode 100644
index 0000000..cd17c90
--- /dev/null
+++ b/kernel/os/test/src/mempool_test.c
@@ -0,0 +1,227 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+#include <stdio.h>
+#include <string.h>
+#include "testutil/testutil.h"
+#include "os/os.h"
+#include "os_test_priv.h"
+
+/* Create a memory pool for testing */
+#define NUM_MEM_BLOCKS  (10)
+#define MEM_BLOCK_SIZE  (80)
+
+/* Limit max blocks for testing */
+#define MEMPOOL_TEST_MAX_BLOCKS     (128)
+
+#if OS_CFG_ALIGNMENT == OS_CFG_ALIGN_4
+int alignment = 4;
+#else
+int alignment = 8;
+#endif
+
+/* Test memory pool structure */
+struct os_mempool g_TstMempool;
+
+/* Test memory pool buffer */
+os_membuf_t TstMembuf[OS_MEMPOOL_SIZE(NUM_MEM_BLOCKS, MEM_BLOCK_SIZE)];
+
+/* Array of block pointers. */
+void *block_array[MEMPOOL_TEST_MAX_BLOCKS];
+
+int verbose = 0;
+
+static int
+mempool_test_get_pool_size(int num_blocks, int block_size)
+{
+    int mem_pool_size;
+
+#if OS_CFG_ALIGNMENT == OS_CFG_ALIGN_4
+    mem_pool_size = (num_blocks * ((block_size + 3)/4) * sizeof(os_membuf_t));
+#else
+    mem_pool_size = (num_blocks * ((block_size + 7)/8) * sizeof(os_membuf_t));
+#endif
+
+    return mem_pool_size;
+}
+
+static void
+mempool_test(int num_blocks, int block_size)
+{
+    int cnt;
+    int true_block_size;
+    int mem_pool_size;
+    uint32_t test_block;
+    uint8_t *tstptr;
+    void **free_ptr;
+    void *block;
+    os_error_t rc;
+
+    /* Check for too many blocks */
+    TEST_ASSERT(num_blocks <= MEMPOOL_TEST_MAX_BLOCKS);
+
+    rc = os_mempool_init(&g_TstMempool, num_blocks, MEM_BLOCK_SIZE, 
+                         &TstMembuf[0], "TestMemPool");
+    TEST_ASSERT_FATAL(rc == 0, "Error creating memory pool %d", rc);
+
+    TEST_ASSERT(g_TstMempool.mp_num_free == num_blocks,
+                "Number of free blocks not equal to total blocks!");
+
+    TEST_ASSERT(SLIST_FIRST(&g_TstMempool) == (void *)&TstMembuf[0],
+                "Free list pointer does not point to first block!");
+
+    mem_pool_size = mempool_test_get_pool_size(num_blocks, block_size);
+    TEST_ASSERT(mem_pool_size == sizeof(TstMembuf),
+                "Total memory pool size not correct! (%d vs %lu)",
+                mem_pool_size, (unsigned long)sizeof(TstMembuf));
+
+    /* Get the real block size */
+#if (OS_CFG_ALIGNMENT == OS_CFG_ALIGN_4)
+    true_block_size = (g_TstMempool.mp_block_size + 3) & ~3;
+#else
+    true_block_size = (g_TstMempool.mp_block_size + 7) & ~7;
+#endif
+
+    /* Traverse free list. Better add up to number of blocks! */
+    cnt = 0;
+    free_ptr = (void **)&TstMembuf;
+    tstptr = (uint8_t *)&TstMembuf;
+    while (1) {
+        /* Increment # of elements by 1 */
+        ++cnt;
+
+        /* If the free list is NULL, leave */
+        if (*free_ptr == NULL) {
+            break;
+        }
+
+        TEST_ASSERT(((uint8_t *)*free_ptr - (uint8_t *)free_ptr) ==
+                        true_block_size,
+                    "Free pointers are more than one block apart!");
+
+        /* Move to next memory block */
+        tstptr += true_block_size;
+
+        TEST_ASSERT(*free_ptr == (void *)tstptr,
+                    "Error: free_ptr=%p testptr=%p\n", *free_ptr, tstptr);
+
+        free_ptr = *free_ptr;
+    }
+
+    /* Last one in list better be NULL */
+    TEST_ASSERT(cnt == g_TstMempool.mp_num_blocks,
+                "Free list contains too many elements (%u)", cnt);
+
+    /* Get a block */
+    block = os_memblock_get(&g_TstMempool);
+    TEST_ASSERT(block != NULL,
+                "Error: get block fails when pool should have elements");
+
+    TEST_ASSERT(g_TstMempool.mp_num_free == (num_blocks-1),
+                "Number of free blocks incorrect (%u vs %u)",
+                g_TstMempool.mp_num_free, (num_blocks-1));
+
+    /* Put back the block */
+    rc = os_memblock_put(&g_TstMempool, block);
+    TEST_ASSERT(rc == 0, "Put block fails with error code=%d\n", rc);
+
+    TEST_ASSERT(g_TstMempool.mp_num_free == num_blocks,
+                "Number of free blocks incorrect (%u vs %u)",
+                g_TstMempool.mp_num_free, num_blocks);
+
+    /* remove all the blocks. Make sure we get count. */
+    memset(block_array, 0, sizeof(block_array));
+    cnt = 0;
+    while (1) {
+        block = os_memblock_get(&g_TstMempool);
+        if (block == NULL) {
+            break;
+        }
+        block_array[cnt] = block;
+        ++cnt;
+        if (cnt == MEMPOOL_TEST_MAX_BLOCKS) {
+            break;
+        }
+    }
+
+    TEST_ASSERT((cnt == g_TstMempool.mp_num_blocks) && 
+                (cnt != MEMPOOL_TEST_MAX_BLOCKS),
+                "Got more blocks than mempool contains (%d vs %d)",
+                cnt, g_TstMempool.mp_num_blocks);
+
+    /* Better be no free blocks left! */
+    TEST_ASSERT(g_TstMempool.mp_num_free == 0,
+                "Got all blocks but number free not zero! (%d)",
+                g_TstMempool.mp_num_free);
+
+    /* Now put them all back */
+    for (cnt = 0; cnt < g_TstMempool.mp_num_blocks; ++cnt) {
+        rc = os_memblock_put(&g_TstMempool, block_array[cnt]);
+        TEST_ASSERT(rc == 0,
+                    "Error putting back block %p (cnt=%d err=%d)", 
+                    block_array[cnt], cnt, rc);
+    }
+
+    /* Better be no free blocks left! */
+    TEST_ASSERT(g_TstMempool.mp_num_free == g_TstMempool.mp_num_blocks,
+                "Put all blocks but number free not equal to total!");
+
+    /* Better get error when we try these things! */
+    rc = os_memblock_put(NULL, block_array[0]);
+    TEST_ASSERT(rc != 0,
+                "Should have got an error trying to put to null pool");
+
+    rc = os_memblock_put(&g_TstMempool, NULL);
+    TEST_ASSERT(rc != 0, "No error trying to put to NULL block");
+
+    TEST_ASSERT(os_memblock_get(NULL) == NULL,
+                "No error trying to get a block from NULL pool");
+
+    /* Attempt to free a block outside the range of the membuf */
+    test_block = g_TstMempool.mp_membuf_addr;
+    test_block -= 4;
+    rc = os_memblock_put(&g_TstMempool, (void *)test_block);
+    TEST_ASSERT(rc == OS_INVALID_PARM, "No error freeing bad block address");
+
+    test_block += (true_block_size * g_TstMempool.mp_num_blocks) + 100;
+    rc = os_memblock_put(&g_TstMempool, (void *)test_block);
+    TEST_ASSERT(rc == OS_INVALID_PARM, "No error freeing bad block address");
+
+    /* Attempt to free on bad boundary */
+    test_block = g_TstMempool.mp_membuf_addr;
+    test_block += (true_block_size / 2);
+    rc = os_memblock_put(&g_TstMempool, (void *)test_block);
+    TEST_ASSERT(rc == OS_INVALID_PARM, "No error freeing bad block address");
+}
+
+/**
+ * os mempool test 
+ *  
+ * Main test loop for memory pool testing. 
+ * 
+ * @return int 
+ */
+TEST_CASE(os_mempool_test_case)
+{
+    mempool_test(NUM_MEM_BLOCKS, MEM_BLOCK_SIZE);
+}
+
+TEST_SUITE(os_mempool_test_suite)
+{
+    os_mempool_test_case();
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/test/src/mutex_test.c
----------------------------------------------------------------------
diff --git a/kernel/os/test/src/mutex_test.c b/kernel/os/test/src/mutex_test.c
new file mode 100644
index 0000000..d23f099
--- /dev/null
+++ b/kernel/os/test/src/mutex_test.c
@@ -0,0 +1,407 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+#include <stdio.h>
+#include <string.h>
+#include <assert.h>
+#include <sys/time.h>
+#include "testutil/testutil.h"
+#include "os/os.h"
+#include "os/os_test.h"
+#include "os/os_cfg.h"
+#include "os/os_mutex.h"
+#include "os_test_priv.h"
+
+#ifdef ARCH_sim
+#define MUTEX_TEST_STACK_SIZE   1024
+#else
+#define MUTEX_TEST_STACK_SIZE   256
+#endif
+
+struct os_task task14;
+os_stack_t stack14[OS_STACK_ALIGN(MUTEX_TEST_STACK_SIZE)];
+
+struct os_task task15;
+os_stack_t stack15[OS_STACK_ALIGN(MUTEX_TEST_STACK_SIZE)];
+
+struct os_task task16;
+os_stack_t stack16[OS_STACK_ALIGN(MUTEX_TEST_STACK_SIZE)];
+
+struct os_task task17;
+os_stack_t stack17[OS_STACK_ALIGN(MUTEX_TEST_STACK_SIZE)];
+
+#define TASK14_PRIO (4)
+#define TASK15_PRIO (5)
+#define TASK16_PRIO (6)
+#define TASK17_PRIO (7)
+
+volatile int g_task14_val;
+volatile int g_task15_val;
+volatile int g_task16_val;
+volatile int g_task17_val;
+struct os_mutex g_mutex1;
+struct os_mutex g_mutex2;
+
+static volatile int g_mutex_test;
+
+/**
+ * mutex test basic 
+ *  
+ * Basic mutex tests
+ * 
+ * @return int 
+ */
+static void
+mutex_test_basic_handler(void *arg)
+{
+    struct os_mutex *mu;
+    struct os_task *t;
+    os_error_t err;
+
+    mu = &g_mutex1;
+    t = os_sched_get_current_task();
+
+    /* Test some error cases */
+    TEST_ASSERT(os_mutex_init(NULL)     == OS_INVALID_PARM);
+    TEST_ASSERT(os_mutex_release(NULL)  == OS_INVALID_PARM);
+    TEST_ASSERT(os_mutex_pend(NULL, 0)  == OS_INVALID_PARM);
+
+    /* Get the mutex */
+    err = os_mutex_pend(mu, 0);
+    TEST_ASSERT(err == 0,
+                "Did not get free mutex immediately (err=%d)", err);
+
+    /* Check mutex internals */
+    TEST_ASSERT(mu->mu_owner == t && mu->mu_level == 1 &&
+                mu->mu_prio == t->t_prio && SLIST_EMPTY(&mu->mu_head),
+                "Mutex internals not correct after getting mutex\n"
+                "Mutex: owner=%p prio=%u level=%u head=%p\n"
+                "Task: task=%p prio=%u",
+                mu->mu_owner, mu->mu_prio, mu->mu_level, 
+                SLIST_FIRST(&mu->mu_head),
+                t, t->t_prio);
+
+    /* Get the mutex again; should be level 2 */
+    err = os_mutex_pend(mu, 0);
+    TEST_ASSERT(err == 0, "Did not get my mutex immediately (err=%d)", err);
+
+    /* Check mutex internals */
+    TEST_ASSERT(mu->mu_owner == t && mu->mu_level == 2 &&
+                mu->mu_prio == t->t_prio && SLIST_EMPTY(&mu->mu_head),
+                "Mutex internals not correct after getting mutex\n"
+                "Mutex: owner=%p prio=%u level=%u head=%p\n"
+                "Task: task=%p prio=%u",
+                mu->mu_owner, mu->mu_prio, mu->mu_level, 
+                SLIST_FIRST(&mu->mu_head), t, t->t_prio);
+
+    /* Release mutex */
+    err = os_mutex_release(mu);
+    TEST_ASSERT(err == 0, "Could not release mutex I own (err=%d)", err);
+
+    /* Check mutex internals */
+    TEST_ASSERT(mu->mu_owner == t && mu->mu_level == 1 &&
+                mu->mu_prio == t->t_prio && SLIST_EMPTY(&mu->mu_head),
+                "Error: mutex internals not correct after getting mutex\n"
+                "Mutex: owner=%p prio=%u level=%u head=%p\n"
+                "Task: task=%p prio=%u",
+                mu->mu_owner, mu->mu_prio, mu->mu_level, 
+                SLIST_FIRST(&mu->mu_head), t, t->t_prio);
+
+    /* Release it again */
+    err = os_mutex_release(mu);
+    TEST_ASSERT(err == 0, "Could not release mutex I own (err=%d)", err);
+
+    /* Check mutex internals */
+    TEST_ASSERT(mu->mu_owner == NULL && mu->mu_level == 0 &&
+                mu->mu_prio == t->t_prio && SLIST_EMPTY(&mu->mu_head),
+                "Mutex internals not correct after getting mutex\n"
+                "Mutex: owner=%p prio=%u level=%u head=%p\n"
+                "Task: task=%p prio=%u",
+                mu->mu_owner, mu->mu_prio, mu->mu_level, 
+                SLIST_FIRST(&mu->mu_head), t, t->t_prio);
+
+    os_test_restart();
+}
+
+static void 
+mutex_test1_task14_handler(void *arg)
+{
+    os_error_t err;
+    struct os_task *t;
+    int iters;
+
+    t = os_sched_get_current_task();
+    TEST_ASSERT(t->t_func == mutex_test1_task14_handler);
+
+    for (iters = 0; iters < 3; iters++) {
+        os_time_delay(OS_TICKS_PER_SEC / 10);
+
+        g_task14_val = 1;
+
+        err = os_mutex_pend(&g_mutex1, OS_TICKS_PER_SEC / 10);
+        TEST_ASSERT(err == OS_OK);
+        TEST_ASSERT(g_task16_val == 1);
+
+        os_time_delay(OS_TICKS_PER_SEC / 10);
+    }
+
+    os_test_restart();
+}
+
+static void 
+mutex_test2_task14_handler(void *arg)
+{
+    os_error_t err;
+    struct os_task *t;
+    int iters;
+
+    t = os_sched_get_current_task();
+    TEST_ASSERT(t->t_func == mutex_test2_task14_handler);
+
+    for (iters = 0; iters < 3; iters++) {
+        err = os_mutex_pend(&g_mutex1, 0);
+        TEST_ASSERT(err == OS_OK, "err=%d", err);
+
+        g_task14_val = 1;
+        os_time_delay(OS_TICKS_PER_SEC / 10);
+
+        /* 
+         * Task17 should have its mutex wait flag set; at least the first time
+         * through!
+         */
+        if (iters == 0) {
+            TEST_ASSERT(task17.t_flags & OS_TASK_FLAG_MUTEX_WAIT);
+        }
+
+        if (g_mutex_test == 4) {
+            os_time_delay(150);
+        }
+
+        os_mutex_release(&g_mutex1);
+        os_time_delay(OS_TICKS_PER_SEC / 10);
+    }
+
+    os_test_restart();
+}
+
+static void 
+task15_handler(void *arg) 
+{
+    os_error_t err;
+    struct os_task *t;
+
+    if (g_mutex_test == 1) {
+        while (1) {
+            t = os_sched_get_current_task();
+            TEST_ASSERT(t->t_func == task15_handler);
+
+            os_time_delay(OS_TICKS_PER_SEC / 20);
+            while (1) {
+                /* Wait here forever */
+            }
+        }
+    } else {
+        if (g_mutex_test == 2) {
+            /* Sleep for 3 seconds */
+            t = os_sched_get_current_task();
+            os_time_delay(OS_TICKS_PER_SEC / 2);
+        } else if (g_mutex_test == 3) {
+            /* Sleep for 3 seconds */
+            t = os_sched_get_current_task();
+            os_time_delay(OS_TICKS_PER_SEC / 33);
+        }
+
+        while (1) {
+            t = os_sched_get_current_task();
+            TEST_ASSERT(t->t_func == task15_handler);
+
+            err = os_mutex_pend(&g_mutex1, OS_TICKS_PER_SEC * 10);
+            if (g_mutex_test == 4) {
+                TEST_ASSERT(err == OS_TIMEOUT);
+            } else {
+                TEST_ASSERT(err == OS_OK);
+            }
+
+            os_time_delay(OS_TICKS_PER_SEC / 10);
+        }
+    }
+}
+
+static void 
+task16_handler(void *arg) 
+{
+    os_error_t err;
+    struct os_task *t;
+
+    if (g_mutex_test == 1) {
+        while (1) {
+            t = os_sched_get_current_task();
+            TEST_ASSERT(t->t_func == task16_handler);
+
+            /* Get mutex 1 */
+            err = os_mutex_pend(&g_mutex1, OS_TIMEOUT_NEVER);
+            TEST_ASSERT(err == OS_OK);
+
+            while (g_task14_val != 1) {
+                /* Wait till task 1 wakes up and sets val. */
+            }
+
+            g_task16_val = 1;
+
+            err = os_mutex_release(&g_mutex1);
+            TEST_ASSERT(err == OS_OK);
+        }
+    } else {
+        if (g_mutex_test == 2) {
+            /* Sleep for 3 seconds */
+            t = os_sched_get_current_task();
+            os_time_delay(OS_TICKS_PER_SEC / 33);
+        } else if (g_mutex_test == 3) {
+            /* Sleep for 3 seconds */
+            t = os_sched_get_current_task();
+            os_time_delay(OS_TICKS_PER_SEC / 20);
+        }
+
+        while (1) {
+            t = os_sched_get_current_task();
+            TEST_ASSERT(t->t_func == task16_handler);
+
+            err = os_mutex_pend(&g_mutex1, OS_TICKS_PER_SEC * 10);
+            if (g_mutex_test == 4) {
+                TEST_ASSERT(err == OS_TIMEOUT);
+            } else {
+                TEST_ASSERT(err == OS_OK);
+            }
+
+            if (err == OS_OK) {
+                err = os_mutex_release(&g_mutex1);
+                TEST_ASSERT(err == OS_OK);
+            }
+
+            os_time_delay(OS_TICKS_PER_SEC * 10);
+        }
+    }
+}
+
+static void 
+task17_handler(void *arg)
+{
+    os_error_t err;
+    struct os_task *t;
+
+    while (1) {
+        t = os_sched_get_current_task();
+        TEST_ASSERT(t->t_func == task17_handler);
+
+        if (g_mutex_test == 5) {
+            err = os_mutex_pend(&g_mutex1, OS_TICKS_PER_SEC / 10);
+        } else {
+            err = os_mutex_pend(&g_mutex1, OS_TICKS_PER_SEC * 10);
+            TEST_ASSERT((t->t_flags & OS_TASK_FLAG_MUTEX_WAIT) == 0);
+        }
+
+        if (g_mutex_test == 4 || g_mutex_test == 5) {
+            TEST_ASSERT(err == OS_TIMEOUT);
+        } else {
+            TEST_ASSERT(err == OS_OK);
+        }
+
+        if (err == OS_OK) {
+            err = os_mutex_release(&g_mutex1);
+            TEST_ASSERT(err == OS_OK);
+        }
+
+        os_time_delay(OS_TICKS_PER_SEC * 10);
+    }
+}
+
+TEST_CASE(os_mutex_test_basic)
+{
+    os_init();
+
+    os_mutex_init(&g_mutex1);
+
+    os_task_init(&task14, "task14", mutex_test_basic_handler, NULL,
+                 TASK14_PRIO, OS_WAIT_FOREVER, stack14,
+                 OS_STACK_ALIGN(MUTEX_TEST_STACK_SIZE));
+
+    os_start();
+}
+
+TEST_CASE(os_mutex_test_case_1)
+{
+    int rc;
+
+    os_init();
+
+    g_mutex_test = 1;
+    g_task14_val = 0;
+    g_task15_val = 0;
+    g_task16_val = 0;
+
+    rc = os_mutex_init(&g_mutex1);
+    TEST_ASSERT(rc == 0);
+    rc = os_mutex_init(&g_mutex2);
+    TEST_ASSERT(rc == 0);
+
+    os_task_init(&task14, "task14", mutex_test1_task14_handler, NULL,
+                 TASK14_PRIO, OS_WAIT_FOREVER, stack14,
+                 OS_STACK_ALIGN(MUTEX_TEST_STACK_SIZE));
+
+    os_task_init(&task15, "task15", task15_handler, NULL, TASK15_PRIO, 
+            OS_WAIT_FOREVER, stack15, OS_STACK_ALIGN(MUTEX_TEST_STACK_SIZE));
+
+    os_task_init(&task16, "task16", task16_handler, NULL, TASK16_PRIO, 
+            OS_WAIT_FOREVER, stack16, OS_STACK_ALIGN(MUTEX_TEST_STACK_SIZE));
+
+    os_start();
+}
+
+TEST_CASE(os_mutex_test_case_2)
+{
+    os_init();
+
+    g_mutex_test = 2;
+    g_task14_val = 0;
+    g_task15_val = 0;
+    g_task16_val = 0;
+    os_mutex_init(&g_mutex1);
+    os_mutex_init(&g_mutex2);
+
+    os_task_init(&task14, "task14", mutex_test2_task14_handler, NULL,
+                 TASK14_PRIO, OS_WAIT_FOREVER, stack14,
+                 OS_STACK_ALIGN(MUTEX_TEST_STACK_SIZE));
+
+    os_task_init(&task15, "task15", task15_handler, NULL, TASK15_PRIO, 
+            OS_WAIT_FOREVER, stack15, OS_STACK_ALIGN(MUTEX_TEST_STACK_SIZE));
+
+    os_task_init(&task16, "task16", task16_handler, NULL, TASK16_PRIO, 
+            OS_WAIT_FOREVER, stack16, OS_STACK_ALIGN(MUTEX_TEST_STACK_SIZE));
+
+    os_task_init(&task17, "task17", task17_handler, NULL, TASK17_PRIO, 
+            OS_WAIT_FOREVER, stack17, OS_STACK_ALIGN(MUTEX_TEST_STACK_SIZE));
+ 
+    os_start();
+}
+
+TEST_SUITE(os_mutex_test_suite)
+{
+    os_mutex_test_basic();
+    os_mutex_test_case_1();
+    os_mutex_test_case_2();
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/test/src/os_test.c
----------------------------------------------------------------------
diff --git a/kernel/os/test/src/os_test.c b/kernel/os/test/src/os_test.c
new file mode 100644
index 0000000..e9d041b
--- /dev/null
+++ b/kernel/os/test/src/os_test.c
@@ -0,0 +1,53 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include <assert.h>
+#include <stddef.h>
+#include "syscfg/syscfg.h"
+#include "testutil/testutil.h"
+#include "os/os_test.h"
+#include "os_test_priv.h"
+
+int
+os_test_all(void)
+{
+    os_mempool_test_suite();
+    os_mutex_test_suite();
+    os_sem_test_suite();
+    os_mbuf_test_suite();
+    os_eventq_test_suite();
+    os_callout_test_suite();
+
+    return tu_case_failed;
+}
+
+#if MYNEWT_VAL(SELFTEST)
+
+int
+main(int argc, char **argv)
+{
+    tu_config.tc_print_results = 1;
+    tu_init();
+
+    os_test_all();
+
+    return tu_any_failed;
+}
+
+#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/test/src/os_test_priv.h
----------------------------------------------------------------------
diff --git a/kernel/os/test/src/os_test_priv.h b/kernel/os/test/src/os_test_priv.h
new file mode 100644
index 0000000..e923a6f
--- /dev/null
+++ b/kernel/os/test/src/os_test_priv.h
@@ -0,0 +1,32 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 H_OS_TEST_PRIV_
+#define H_OS_TEST_PRIV_
+
+void os_test_restart(void);
+
+int os_mempool_test_suite(void);
+int os_mbuf_test_suite(void);
+int os_mutex_test_suite(void);
+int os_sem_test_suite(void);
+int os_eventq_test_suite(void);
+int os_callout_test_suite(void);
+
+#endif


[23/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/console/stub/include/console/prompt.h
----------------------------------------------------------------------
diff --git a/libs/console/stub/include/console/prompt.h b/libs/console/stub/include/console/prompt.h
deleted file mode 100644
index a1d72c9..0000000
--- a/libs/console/stub/include/console/prompt.h
+++ /dev/null
@@ -1,35 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 __CONSOLE_PROMPT_H__
-#define __CONSOLE_PROMPT_H__
-nclude/console/prompt.h
-
-#include <stdarg.h>
-
-/* print console prompt */
-void console_print_prompt(void);
-/* set the console prompt character */
-void console_set_prompt(char);
-
-
-extern char console_prompt[2];
-
-
-#endif /* __CONSOLE_PROMPT_H__ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/console/stub/pkg.yml
----------------------------------------------------------------------
diff --git a/libs/console/stub/pkg.yml b/libs/console/stub/pkg.yml
deleted file mode 100644
index c5e530c..0000000
--- a/libs/console/stub/pkg.yml
+++ /dev/null
@@ -1,27 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you 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.
-#
-
-pkg.name: libs/console/stub
-pkg.description: Stub for text-based IO interface.
-pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
-pkg.homepage: "http://mynewt.apache.org/"
-pkg.keywords:
-
-pkg.deps:
-pkg.apis: console

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/crash_test/include/crash_test/crash_test.h
----------------------------------------------------------------------
diff --git a/libs/crash_test/include/crash_test/crash_test.h b/libs/crash_test/include/crash_test/crash_test.h
deleted file mode 100644
index 73135fd..0000000
--- a/libs/crash_test/include/crash_test/crash_test.h
+++ /dev/null
@@ -1,27 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 __CRASH_TEST_H__
-#define __CRASH_TEST_H__
-
-/*
- * Adds the crash commands to your shell/newtmgr.
- */
-int crash_test_init(void);
-
-#endif /* __CRASH_TEST_H__ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/crash_test/pkg.yml
----------------------------------------------------------------------
diff --git a/libs/crash_test/pkg.yml b/libs/crash_test/pkg.yml
deleted file mode 100644
index c5514d9..0000000
--- a/libs/crash_test/pkg.yml
+++ /dev/null
@@ -1,42 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you 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.
-#
-
-pkg.name: libs/crash_test
-pkg.description: Generate different kinds of faults
-pkg.homepage: "http://mynewt.apache.org/"
-pkg.keywords:
-
-pkg.deps.CRASH_TEST_CLI:
-    - libs/shell
-pkg.req_apis.CRASH_TEST_CLI:
-    - console
-pkg.req_apis.CRASH_TEST_NEWTMGR:
-    - newtmgr
-
-pkg.deps.CRASH_TEST_NEWTMGR:
-    - libs/newtmgr
-    - libs/json
-
-pkg.syscfg_defs:
-    CRASH_TEST_CLI:
-        description: 'TBD'
-        value: 1
-    CRASH_TEST_NEWTMGR:
-        description: 'TBD'
-        value: 1

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/crash_test/src/crash_cli.c
----------------------------------------------------------------------
diff --git a/libs/crash_test/src/crash_cli.c b/libs/crash_test/src/crash_cli.c
deleted file mode 100644
index 4d49bef..0000000
--- a/libs/crash_test/src/crash_cli.c
+++ /dev/null
@@ -1,49 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include "syscfg/syscfg.h"
-
-#if MYNEWT_VAL(CRASH_TEST_CLI)
-#include <inttypes.h>
-#include <os/os.h>
-#include <console/console.h>
-#include <shell/shell.h>
-#include <stdio.h>
-#include <string.h>
-
-#include "crash_test/crash_test.h"
-#include "crash_test_priv.h"
-
-static int crash_cli_cmd(int argc, char **argv);
-struct shell_cmd crash_cmd_struct = {
-    .sc_cmd = "crash",
-    .sc_cmd_func = crash_cli_cmd
-};
-
-static int
-crash_cli_cmd(int argc, char **argv)
-{
-    if (argc >= 2 && crash_device(argv[1]) == 0) {
-        return 0;
-    }
-    console_printf("Usage crash [div0|jump0|ref0|assert]\n");
-    return 0;
-}
-
-#endif /* MYNEWT_VAL(CRASH_TEST_CLI) */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/crash_test/src/crash_nmgr.c
----------------------------------------------------------------------
diff --git a/libs/crash_test/src/crash_nmgr.c b/libs/crash_test/src/crash_nmgr.c
deleted file mode 100644
index d9bf4b0..0000000
--- a/libs/crash_test/src/crash_nmgr.c
+++ /dev/null
@@ -1,75 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include "syscfg/syscfg.h"
-
-#if MYNEWT_VAL(CRASH_TEST_NEWTMGR)
-
-#include <string.h>
-
-#include "newtmgr/newtmgr.h"
-#include "json/json.h"
-#include "console/console.h"
-
-#include "crash_test/crash_test.h"
-#include "crash_test_priv.h"
-
-static int crash_test_nmgr_write(struct nmgr_jbuf *);
-
-static const struct nmgr_handler crash_test_nmgr_handler[] = {
-    [0] = { crash_test_nmgr_write, crash_test_nmgr_write }
-};
-
-struct nmgr_group crash_test_nmgr_group = {
-    .ng_handlers = (struct nmgr_handler *)crash_test_nmgr_handler,
-    .ng_handlers_count = 1,
-    .ng_group_id = NMGR_GROUP_ID_CRASH
-};
-
-static int
-crash_test_nmgr_write(struct nmgr_jbuf *njb)
-{
-    char tmp_str[64];
-    const struct json_attr_t attr[2] = {
-        [0] = {
-            .attribute = "t",
-            .type = t_string,
-            .addr.string = tmp_str,
-            .len = sizeof(tmp_str)
-        },
-        [1] = {
-            .attribute = NULL
-        }
-    };
-    int rc;
-
-    rc = json_read_object(&njb->njb_buf, attr);
-    if (rc) {
-        rc = NMGR_ERR_EINVAL;
-    } else {
-        rc = crash_device(tmp_str);
-        if (rc) {
-            rc = NMGR_ERR_EINVAL;
-        }
-    }
-    nmgr_jbuf_setoerr(njb, rc);
-    return 0;
-}
-
-#endif /* MYNEWT_VAL(CRASH_TEST_NEWTMGR) */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/crash_test/src/crash_test.c
----------------------------------------------------------------------
diff --git a/libs/crash_test/src/crash_test.c b/libs/crash_test/src/crash_test.c
deleted file mode 100644
index a6e2ea2..0000000
--- a/libs/crash_test/src/crash_test.c
+++ /dev/null
@@ -1,72 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-#include <inttypes.h>
-#include <stdio.h>
-#include <string.h>
-#include <assert.h>
-
-#include "syscfg/syscfg.h"
-#include "os/os.h"
-#include "console/console.h"
-
-#include "crash_test/crash_test.h"
-#include "crash_test_priv.h"
-
-#if MYNEWT_VAL(CRASH_TEST_CLI)
-#include "shell/shell.h"
-#endif
-#if MYNEWT_VAL(CRASH_TEST_NEWTMGR)
-#include "newtmgr/newtmgr.h"
-#endif
-
-int
-crash_device(char *how)
-{
-    volatile int val1, val2, val3;
-
-    if (!strcmp(how, "div0")) {
-
-        val1 = 42;
-        val2 = 0;
-
-        val3 = val1 / val2;
-        console_printf("42/0 = %d\n", val3);
-    } else if (!strcmp(how, "jump0")) {
-        ((void (*)(void))0)();
-    } else if (!strcmp(how, "ref0")) {
-        val1 = *(int *)0;
-    } else if (!strcmp(how, "assert")) {
-        assert(0);
-    } else {
-        return -1;
-    }
-    return 0;
-}
-
-int
-crash_test_init(void)
-{
-#if MYNEWT_VAL(CRASH_TEST_CLI)
-    shell_cmd_register(&crash_cmd_struct);
-#endif
-#if MYNEWT_VAL(CRASH_TEST_NEWTMGR)
-    nmgr_group_register(&crash_test_nmgr_group);
-#endif
-    return 0;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/crash_test/src/crash_test_priv.h
----------------------------------------------------------------------
diff --git a/libs/crash_test/src/crash_test_priv.h b/libs/crash_test/src/crash_test_priv.h
deleted file mode 100644
index 09dc5a3..0000000
--- a/libs/crash_test/src/crash_test_priv.h
+++ /dev/null
@@ -1,31 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 __CRASH_TEST_PRIV_H__
-#define __CRASH_TEST_PRIV_H__
-
-#if MYNEWT_VAL(CRASH_TEST_CLI)
-extern struct shell_cmd crash_cmd_struct;
-#endif
-#if MYNEWT_VAL(CRASH_TEST_NEWTMGR)
-extern struct nmgr_group crash_test_nmgr_group;
-#endif
-
-int crash_device(char *how);
-
-#endif /* __CRASH_TEST_PRIV_H__ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/README.md
----------------------------------------------------------------------
diff --git a/libs/elua/README.md b/libs/elua/README.md
deleted file mode 100644
index d6ae607..0000000
--- a/libs/elua/README.md
+++ /dev/null
@@ -1,7 +0,0 @@
-#
-# Lua parser from http://www.eluaproject.net
-#
-# lifted from git://github.com/elua/elua.git
-#  tag be3e050d382c03d253aca3bd4e27e3847d47feba
-#
-# 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/LICENSE
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/LICENSE b/libs/elua/elua_base/LICENSE
deleted file mode 100644
index e4c8126..0000000
--- a/libs/elua/elua_base/LICENSE
+++ /dev/null
@@ -1,62 +0,0 @@
-Copyright (c) 2007, 2008, 2009, 2010, 2011 Dado Sutter and Bogdan Marinescu
-
-eLua is Open Source and is freely distributed under the MIT licence.
-
-The Lua part of eLua is licensed under the Lua licensing terms, which you
-can find at http://www.lua.org/license.html.
-
-The XMODEM code is adapted from the FreeBSD at91 library, which was written
-by M. Warner Losh and is released under the BSD license.
-
-The "pack" module is adapted from the "lpack" module by Luiz Henrique de
-Figueiredo and it's placed in the public domain.
-
-The "bit" module is adapted from the "bitlib" library by Reuben Thomas,
-distributed under a MIT license.
-
-The "integer only lua" is based on the "Go Long Lua!" patch by John D.
-Ramsdell (from the Lua Power Patches page) and is placed in the public
-domain.
-
-The multiple memory allocator (dlmalloc) is written by Doug Lea and is
-placed on the public domain.
-
-The TCP/IP stack is adapted from uIP, written by Adam Dunkels and released
-under a BSD license.
-
-The FAT file sistem is based on FatFs, written by Elm Chan (http://elm-chan.org). 
-A copy of the FatFs license can be found in the LICENSE.fatfs file.
-
-The RPC implementation is based on Russell Smith's Lua-RPC (http://q12.org/lua/index.html). 
-A copy of the Lua-RPC license can be found in the LICENSE.luarpc file.
-
-Manufacturer provided CPU support libraries are licensed under their own
-terms, check src/platform/*platform-name* for details.
-
-linenoise (https://github.com/antirez/linenoise, eLua's readline replacement) 
-is released under a BSD license. 
-
-The rest of the eLua code is licensed under MIT, listed below:
-
-The MIT License
-
-Copyright (c) 2007, 2008, 2009, 2010 Dado Sutter and Bogdan Marinescu
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to
-deal in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-THE SOFTWARE.
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/LICENSE.luarpc
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/LICENSE.luarpc b/libs/elua/elua_base/LICENSE.luarpc
deleted file mode 100644
index 518ecff..0000000
--- a/libs/elua/elua_base/LICENSE.luarpc
+++ /dev/null
@@ -1,32 +0,0 @@
-Lua-RPC library, Copyright (C) 2001 Russell L. Smith. All rights reserved.
-   Email: russ@q12.org   Web: www.q12.org
-For documentation, see http://www.q12.org/lua
-
-Permission is hereby granted, without written agreement and without
-license or royalty fees, to use, copy, modify, and distribute this
-software and its documentation for any purpose, including commercial
-applications, subject to the following conditions:
-
- - The above copyright notice and this permission notice shall appear
-   in all copies or substantial portions of this software.
-
- - The origin of this software must not be misrepresented; you must
-   not claim that you wrote the original software. If you use this
-   software in a product, an acknowledgment in the product
-   documentation would be greatly appreciated (but it is not
-   required).
-
- - Altered source versions must be plainly marked as such, and must
-   not be misrepresented as being the original software.
-
-The authors specifically disclaim any warranties, including, but not
-limited to, the implied warranties of merchantability and fitness for
-a particular purpose. The software provided hereunder is on an "as is"
-basis, and the authors have no obligation to provide maintenance,
-support, updates, enhancements, or modifications. In no event shall
-the authors be held liable to any party for direct, indirect, special,
-incidental, or consequential damages arising out of the use of this
-software and its documentation.
-
-This implementation contains no third-party code.
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/include/elua_base/elua.h
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/include/elua_base/elua.h b/libs/elua/elua_base/include/elua_base/elua.h
deleted file mode 100644
index e1396e4..0000000
--- a/libs/elua/elua_base/include/elua_base/elua.h
+++ /dev/null
@@ -1,27 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 __ELUA_BASE_H__
-#define __ELUA_BASE_H__
-
-int lua_main( int argc, char **argv );
-
-void lua_init(void);
-
-#endif /* __ELUA_BASE_H__ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/pkg.yml
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/pkg.yml b/libs/elua/elua_base/pkg.yml
deleted file mode 100644
index 9714507..0000000
--- a/libs/elua/elua_base/pkg.yml
+++ /dev/null
@@ -1,50 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you 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.
-#
-
-pkg.name: libs/elua/elua_base
-pkg.description: Lua interpreter for embedded systems.
-pkg.author:
-    - "Bogdan Marinescu"
-    - "Dado Sutter"
-pkg.homepage: "http://www.eluaproject.net/"
-pkg.keywords:
-    - lua
-    - scripting
-    - interpreter
-
-pkg.cflags:
-    - "-DLUA_OPTIMIZE_MEMORY=2"
-    - "-DLUA_CROSS_COMPILER"
-    - "-DLUA_USE_MKSTEMP"
-    - "-DLUA_NUMBER_INTEGRAL"
-    - "-DMYNEWT"
-pkg.req_apis:
-    - console
-pkg.deps:
-    - fs/fs
-pkg.deps.ELUA_CLI:
-    - libs/shell
-
-pkg.init_function: lua_init
-pkg.init_stage: 5
-
-pkg.syscfg_defs:
-    ELUA_CLI:
-        description: 'TBD'
-        value: 'MYNEWT_PKG_LIBS_SHELL'

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/lapi.c
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/lapi.c b/libs/elua/elua_base/src/lapi.c
deleted file mode 100644
index 9dd9e0b..0000000
--- a/libs/elua/elua_base/src/lapi.c
+++ /dev/null
@@ -1,1161 +0,0 @@
-/*
-** $Id: lapi.c,v 2.55.1.5 2008/07/04 18:41:18 roberto Exp $
-** Lua API
-** See Copyright Notice in lua.h
-*/
-
-
-#include <assert.h>
-#include <math.h>
-#include <stdarg.h>
-#include <string.h>
-
-#define lapi_c
-#define LUA_CORE
-
-#include "lua.h"
-
-#include "lapi.h"
-#include "ldebug.h"
-#include "ldo.h"
-#include "lfunc.h"
-#include "lgc.h"
-#include "lmem.h"
-#include "lobject.h"
-#include "lstate.h"
-#include "lstring.h"
-#include "ltable.h"
-#include "ltm.h"
-#include "lundump.h"
-#include "lvm.h"
-#include "lrotable.h"
-
-
-const char lua_ident[] =
-  "$Lua: " LUA_RELEASE " " LUA_COPYRIGHT " $\n"
-  "$Authors: " LUA_AUTHORS " $\n"
-  "$URL: www.lua.org $\n";
-
-
-
-#define api_checknelems(L, n)	api_check(L, (n) <= (L->top - L->base))
-
-#define api_checkvalidindex(L, i)	api_check(L, (i) != luaO_nilobject)
-
-#define api_incr_top(L)   {api_check(L, L->top < L->ci->top); L->top++;}
-
-
-
-static TValue *index2adr (lua_State *L, int idx) {
-  if (idx > 0) {
-    TValue *o = L->base + (idx - 1);
-    api_check(L, idx <= L->ci->top - L->base);
-    if (o >= L->top) return cast(TValue *, luaO_nilobject);
-    else return o;
-  }
-  else if (idx > LUA_REGISTRYINDEX) {
-    api_check(L, idx != 0 && -idx <= L->top - L->base);
-    return L->top + idx;
-  }
-  else switch (idx) {  /* pseudo-indices */
-    case LUA_REGISTRYINDEX: return registry(L);
-    case LUA_ENVIRONINDEX: {
-      Closure *func = curr_func(L);
-      sethvalue(L, &L->env, func ? func->c.env : hvalue(gt(L)));
-      return &L->env;
-    }
-    case LUA_GLOBALSINDEX: return gt(L);
-    default: {
-      Closure *func = curr_func(L);
-      if (!func) return cast(TValue *, luaO_nilobject);
-      idx = LUA_GLOBALSINDEX - idx;
-      return (idx <= func->c.nupvalues)
-                ? &func->c.upvalue[idx-1]
-                : cast(TValue *, luaO_nilobject);
-    }
-  }
-}
-
-
-static Table *getcurrenv (lua_State *L) {
-  if (L->ci == L->base_ci)  /* no enclosing function? */
-    return hvalue(gt(L));  /* use global table as environment */
-  else {
-    Closure *func = curr_func(L);
-    return func ? func->c.env : hvalue(gt(L));
-  }
-}
-
-
-void luaA_pushobject (lua_State *L, const TValue *o) {
-  setobj2s(L, L->top, o);
-  api_incr_top(L);
-}
-
-
-LUA_API int lua_checkstack (lua_State *L, int size) {
-  int res = 1;
-  lua_lock(L);
-  if (size > LUAI_MAXCSTACK || (L->top - L->base + size) > LUAI_MAXCSTACK)
-    res = 0;  /* stack overflow */
-  else if (size > 0) {
-    luaD_checkstack(L, size);
-    if (L->ci->top < L->top + size)
-      L->ci->top = L->top + size;
-  }
-  lua_unlock(L);
-  return res;
-}
-
-
-LUA_API void lua_xmove (lua_State *from, lua_State *to, int n) {
-  int i;
-  if (from == to) return;
-  lua_lock(to);
-  api_checknelems(from, n);
-  api_check(from, G(from) == G(to));
-  api_check(from, to->ci->top - to->top >= n);
-  from->top -= n;
-  for (i = 0; i < n; i++) {
-    setobj2s(to, to->top++, from->top + i);
-  }
-  lua_unlock(to);
-}
-
-
-LUA_API void lua_setlevel (lua_State *from, lua_State *to) {
-  to->nCcalls = from->nCcalls;
-}
-
-
-LUA_API lua_CFunction lua_atpanic (lua_State *L, lua_CFunction panicf) {
-  lua_CFunction old;
-  lua_lock(L);
-  old = G(L)->panic;
-  G(L)->panic = panicf;
-  lua_unlock(L);
-  return old;
-}
-
-
-LUA_API lua_State *lua_newthread (lua_State *L) {
-  lua_State *L1;
-  lua_lock(L);
-  luaC_checkGC(L);
-  L1 = luaE_newthread(L);
-  setthvalue(L, L->top, L1);
-  api_incr_top(L);
-  lua_unlock(L);
-  luai_userstatethread(L, L1);
-  return L1;
-}
-
-
-
-/*
-** basic stack manipulation
-*/
-
-
-LUA_API int lua_gettop (lua_State *L) {
-  return cast_int(L->top - L->base);
-}
-
-
-LUA_API void lua_settop (lua_State *L, int idx) {
-  lua_lock(L);
-  if (idx >= 0) {
-    api_check(L, idx <= L->stack_last - L->base);
-    while (L->top < L->base + idx)
-      setnilvalue(L->top++);
-    L->top = L->base + idx;
-  }
-  else {
-    api_check(L, -(idx+1) <= (L->top - L->base));
-    L->top += idx+1;  /* `subtract' index (index is negative) */
-  }
-  lua_unlock(L);
-}
-
-
-LUA_API void lua_remove (lua_State *L, int idx) {
-  StkId p;
-  lua_lock(L);
-  p = index2adr(L, idx);
-  api_checkvalidindex(L, p);
-  while (++p < L->top) setobjs2s(L, p-1, p);
-  L->top--;
-  lua_unlock(L);
-}
-
-
-LUA_API void lua_insert (lua_State *L, int idx) {
-  StkId p;
-  StkId q;
-  lua_lock(L);
-  p = index2adr(L, idx);
-  api_checkvalidindex(L, p);
-  for (q = L->top; q>p; q--) setobjs2s(L, q, q-1);
-  setobjs2s(L, p, L->top);
-  lua_unlock(L);
-}
-
-
-LUA_API void lua_replace (lua_State *L, int idx) {
-  StkId o;
-  lua_lock(L);
-  /* explicit test for incompatible code */
-  if (idx == LUA_ENVIRONINDEX && L->ci == L->base_ci)
-    luaG_runerror(L, "no calling environment");
-  api_checknelems(L, 1);
-  o = index2adr(L, idx);
-  api_checkvalidindex(L, o);
-  if (idx == LUA_ENVIRONINDEX) {
-    Closure *func = curr_func(L);
-    if (!func)
-      luaG_runerror(L, "attempt to set environment on lightfunction");
-    else {
-      api_check(L, ttistable(L->top - 1)); 
-      func->c.env = hvalue(L->top - 1);
-      luaC_barrier(L, func, L->top - 1);
-    }
-  }
-  else {
-    setobj(L, o, L->top - 1);
-    if (curr_func(L) && idx < LUA_GLOBALSINDEX)  /* function upvalue? */
-      luaC_barrier(L, curr_func(L), L->top - 1);
-  }
-  L->top--;
-  lua_unlock(L);
-}
-
-
-LUA_API void lua_pushvalue (lua_State *L, int idx) {
-  lua_lock(L);
-  setobj2s(L, L->top, index2adr(L, idx));
-  api_incr_top(L);
-  lua_unlock(L);
-}
-
-
-
-/*
-** access functions (stack -> C)
-*/
-
-
-LUA_API int lua_type (lua_State *L, int idx) {
-  StkId o = index2adr(L, idx);
-  return (o == luaO_nilobject) ? LUA_TNONE : ttype(o);
-}
-
-
-LUA_API const char *lua_typename (lua_State *L, int t) {
-  UNUSED(L);
-  return (t == LUA_TNONE) ? "no value" : luaT_typenames[t];
-}
-
-
-LUA_API int lua_iscfunction (lua_State *L, int idx) {
-  StkId o = index2adr(L, idx);
-  return iscfunction(o);
-}
-
-
-LUA_API int lua_isnumber (lua_State *L, int idx) {
-  TValue n;
-  const TValue *o = index2adr(L, idx);
-  return tonumber(o, &n);
-}
-
-
-LUA_API int lua_isstring (lua_State *L, int idx) {
-  int t = lua_type(L, idx);
-  return (t == LUA_TSTRING || t == LUA_TNUMBER);
-}
-
-
-LUA_API int lua_isuserdata (lua_State *L, int idx) {
-  const TValue *o = index2adr(L, idx);
-  return (ttisuserdata(o) || ttislightuserdata(o));
-}
-
-
-LUA_API int lua_rawequal (lua_State *L, int index1, int index2) {
-  StkId o1 = index2adr(L, index1);
-  StkId o2 = index2adr(L, index2);
-  return (o1 == luaO_nilobject || o2 == luaO_nilobject) ? 0
-         : luaO_rawequalObj(o1, o2);
-}
-
-
-LUA_API int lua_equal (lua_State *L, int index1, int index2) {
-  StkId o1, o2;
-  int i;
-  lua_lock(L);  /* may call tag method */
-  o1 = index2adr(L, index1);
-  o2 = index2adr(L, index2);
-  i = (o1 == luaO_nilobject || o2 == luaO_nilobject) ? 0 : equalobj(L, o1, o2);
-  lua_unlock(L);
-  return i;
-}
-
-
-LUA_API int lua_lessthan (lua_State *L, int index1, int index2) {
-  StkId o1, o2;
-  int i;
-  lua_lock(L);  /* may call tag method */
-  o1 = index2adr(L, index1);
-  o2 = index2adr(L, index2);
-  i = (o1 == luaO_nilobject || o2 == luaO_nilobject) ? 0
-       : luaV_lessthan(L, o1, o2);
-  lua_unlock(L);
-  return i;
-}
-
-
-
-LUA_API lua_Number lua_tonumber (lua_State *L, int idx) {
-  TValue n;
-  const TValue *o = index2adr(L, idx);
-  if (tonumber(o, &n))
-    return nvalue(o);
-  else
-    return 0;
-}
-
-
-LUA_API lua_Integer lua_tointeger (lua_State *L, int idx) {
-  TValue n;
-  const TValue *o = index2adr(L, idx);
-  if (tonumber(o, &n)) {
-    lua_Integer res;
-    lua_Number num = nvalue(o);
-    lua_number2integer(res, num);
-    return res;
-  }
-  else
-    return 0;
-}
-
-
-LUA_API int lua_toboolean (lua_State *L, int idx) {
-  const TValue *o = index2adr(L, idx);
-  return !l_isfalse(o);
-}
-
-
-LUA_API const char *lua_tolstring (lua_State *L, int idx, size_t *len) {
-  StkId o = index2adr(L, idx);
-  if (!ttisstring(o)) {
-    lua_lock(L);  /* `luaV_tostring' may create a new string */
-    if (!luaV_tostring(L, o)) {  /* conversion failed? */
-      if (len != NULL) *len = 0;
-      lua_unlock(L);
-      return NULL;
-    }
-    luaC_checkGC(L);
-    o = index2adr(L, idx);  /* previous call may reallocate the stack */
-    lua_unlock(L);
-  }
-  if (len != NULL) *len = tsvalue(o)->len;
-  return svalue(o);
-}
-
-
-LUA_API size_t lua_objlen (lua_State *L, int idx) {
-  StkId o = index2adr(L, idx);
-  switch (ttype(o)) {
-    case LUA_TSTRING: return tsvalue(o)->len;
-    case LUA_TUSERDATA: return uvalue(o)->len;
-    case LUA_TTABLE: return luaH_getn(hvalue(o));
-    case LUA_TROTABLE: return luaH_getn_ro(rvalue(o));
-    case LUA_TNUMBER: {
-      size_t l;
-      lua_lock(L);  /* `luaV_tostring' may create a new string */
-      l = (luaV_tostring(L, o) ? tsvalue(o)->len : 0);
-      lua_unlock(L);
-      return l;
-    }
-    default: return 0;
-  }
-}
-
-
-LUA_API lua_CFunction lua_tocfunction (lua_State *L, int idx) {
-  StkId o = index2adr(L, idx);
-  return (!iscfunction(o)) ? NULL : clvalue(o)->c.f;
-}
-
-
-LUA_API void *lua_touserdata (lua_State *L, int idx) {
-  StkId o = index2adr(L, idx);
-  switch (ttype(o)) {
-    case LUA_TUSERDATA: return (rawuvalue(o) + 1);
-    case LUA_TLIGHTUSERDATA: return pvalue(o);
-    default: return NULL;
-  }
-}
-
-
-LUA_API lua_State *lua_tothread (lua_State *L, int idx) {
-  StkId o = index2adr(L, idx);
-  return (!ttisthread(o)) ? NULL : thvalue(o);
-}
-
-
-LUA_API const void *lua_topointer (lua_State *L, int idx) {
-  StkId o = index2adr(L, idx);
-  switch (ttype(o)) {
-    case LUA_TTABLE: return hvalue(o);
-    case LUA_TFUNCTION: return clvalue(o);
-    case LUA_TTHREAD: return thvalue(o);
-    case LUA_TUSERDATA:
-    case LUA_TLIGHTUSERDATA:
-      return lua_touserdata(L, idx);
-    case LUA_TROTABLE: 
-    case LUA_TLIGHTFUNCTION:
-      return pvalue(o);
-    default: return NULL;
-  }
-}
-
-
-
-/*
-** push functions (C -> stack)
-*/
-
-
-LUA_API void lua_pushnil (lua_State *L) {
-  lua_lock(L);
-  setnilvalue(L->top);
-  api_incr_top(L);
-  lua_unlock(L);
-}
-
-
-LUA_API void lua_pushnumber (lua_State *L, lua_Number n) {
-  lua_lock(L);
-  setnvalue(L->top, n);
-  api_incr_top(L);
-  lua_unlock(L);
-}
-
-
-LUA_API void lua_pushinteger (lua_State *L, lua_Integer n) {
-  lua_lock(L);
-  setnvalue(L->top, cast_num(n));
-  api_incr_top(L);
-  lua_unlock(L);
-}
-
-
-LUA_API void lua_pushlstring (lua_State *L, const char *s, size_t len) {
-  lua_lock(L);
-  luaC_checkGC(L);
-  setsvalue2s(L, L->top, luaS_newlstr(L, s, len));
-  api_incr_top(L);
-  lua_unlock(L);
-}
-
-
-LUA_API void lua_pushrolstring (lua_State *L, const char *s, size_t len) {
-  lua_lock(L);
-  luaC_checkGC(L);
-  setsvalue2s(L, L->top, luaS_newrolstr(L, s, len));
-  api_incr_top(L);
-  lua_unlock(L);
-}
-
-
-LUA_API void lua_pushstring (lua_State *L, const char *s) {
-  if (s == NULL)
-    lua_pushnil(L);
-  else
-    lua_pushlstring(L, s, strlen(s));
-}
-
-
-LUA_API const char *lua_pushvfstring (lua_State *L, const char *fmt,
-                                      va_list argp) {
-  const char *ret;
-  lua_lock(L);
-  luaC_checkGC(L);
-  ret = luaO_pushvfstring(L, fmt, argp);
-  lua_unlock(L);
-  return ret;
-}
-
-
-LUA_API const char *lua_pushfstring (lua_State *L, const char *fmt, ...) {
-  const char *ret;
-  va_list argp;
-  lua_lock(L);
-  luaC_checkGC(L);
-  va_start(argp, fmt);
-  ret = luaO_pushvfstring(L, fmt, argp);
-  va_end(argp);
-  lua_unlock(L);
-  return ret;
-}
-
-
-LUA_API void lua_pushcclosure (lua_State *L, lua_CFunction fn, int n) {
-  Closure *cl;
-  lua_lock(L);
-  luaC_checkGC(L);
-  api_checknelems(L, n);
-  cl = luaF_newCclosure(L, n, getcurrenv(L));
-  cl->c.f = fn;
-  L->top -= n;
-  while (n--)
-    setobj2n(L, &cl->c.upvalue[n], L->top+n);
-  setclvalue(L, L->top, cl);
-  lua_assert(iswhite(obj2gco(cl)));
-  api_incr_top(L);
-  lua_unlock(L);
-}
-
-
-LUA_API void lua_pushboolean (lua_State *L, int b) {
-  lua_lock(L);
-  setbvalue(L->top, (b != 0));  /* ensure that true is 1 */
-  api_incr_top(L);
-  lua_unlock(L);
-}
-
-
-LUA_API void lua_pushlightuserdata (lua_State *L, void *p) {
-  lua_lock(L);
-  setpvalue(L->top, p);
-  api_incr_top(L);
-  lua_unlock(L);
-}
-
-LUA_API void lua_pushrotable (lua_State *L, void *p) {
-  lua_lock(L);
-  setrvalue(L->top, p);
-  api_incr_top(L);
-  lua_unlock(L);
-}
-
-LUA_API void lua_pushlightfunction(lua_State *L, void *p) {
-  lua_lock(L);
-  setfvalue(L->top, p);
-  api_incr_top(L);
-  lua_unlock(L);
-}
-
-
-LUA_API int lua_pushthread (lua_State *L) {
-  lua_lock(L);
-  setthvalue(L, L->top, L);
-  api_incr_top(L);
-  lua_unlock(L);
-  return (G(L)->mainthread == L);
-}
-
-
-
-/*
-** get functions (Lua -> stack)
-*/
-
-
-LUA_API void lua_gettable (lua_State *L, int idx) {
-  StkId t;
-  lua_lock(L);
-  t = index2adr(L, idx);
-  api_checkvalidindex(L, t);
-  luaV_gettable(L, t, L->top - 1, L->top - 1);
-  lua_unlock(L);
-}
-
-
-LUA_API void lua_getfield (lua_State *L, int idx, const char *k) {
-  StkId t;
-  TValue key;
-  lua_lock(L);
-  t = index2adr(L, idx);
-  api_checkvalidindex(L, t);
-  fixedstack(L);
-  setsvalue(L, &key, luaS_new(L, k));
-  unfixedstack(L);
-  luaV_gettable(L, t, &key, L->top);
-  api_incr_top(L);
-  lua_unlock(L);
-}
-
-
-LUA_API void lua_rawget (lua_State *L, int idx) {
-  StkId t;
-  const TValue *res;
-  lua_lock(L);
-  t = index2adr(L, idx);
-  api_check(L, ttistable(t) || ttisrotable(t));
-  res = ttistable(t) ? luaH_get(hvalue(t), L->top - 1) : luaH_get_ro(rvalue(t), L->top - 1);
-  setobj2s(L, L->top - 1, res);    
-  lua_unlock(L);
-}
-
-
-LUA_API void lua_rawgeti (lua_State *L, int idx, int n) {
-  StkId o;
-  lua_lock(L);
-  o = index2adr(L, idx);
-  api_check(L, ttistable(o) || ttisrotable(o));
-  setobj2s(L, L->top, ttistable(o) ? luaH_getnum(hvalue(o), n) : luaH_getnum_ro(rvalue(o), n))
-  api_incr_top(L);
-  lua_unlock(L);
-}
-
-
-LUA_API void lua_createtable (lua_State *L, int narray, int nrec) {
-  lua_lock(L);
-  luaC_checkGC(L);
-  sethvalue(L, L->top, luaH_new(L, narray, nrec));
-  api_incr_top(L);
-  lua_unlock(L);
-}
-
-
-LUA_API int lua_getmetatable (lua_State *L, int objindex) {
-  const TValue *obj;
-  Table *mt = NULL;
-  int res;
-  lua_lock(L);
-  obj = index2adr(L, objindex);
-  switch (ttype(obj)) {
-    case LUA_TTABLE:
-      mt = hvalue(obj)->metatable;
-      break;
-    case LUA_TUSERDATA:
-      mt = uvalue(obj)->metatable;
-      break;
-    case LUA_TROTABLE:
-      mt = (Table*)luaR_getmeta(rvalue(obj));
-      break; 
-    default:
-      mt = G(L)->mt[ttype(obj)];
-      break;
-  }
-  if (mt == NULL)
-    res = 0;
-  else {
-    if(luaR_isrotable(mt))
-      setrvalue(L->top, mt)
-    else
-      sethvalue(L, L->top, mt)
-    api_incr_top(L);
-    res = 1;
-  }
-  lua_unlock(L);
-  return res;
-}
-
-
-LUA_API void lua_getfenv (lua_State *L, int idx) {
-  StkId o;
-  lua_lock(L);
-  o = index2adr(L, idx);
-  api_checkvalidindex(L, o);
-  switch (ttype(o)) {
-    case LUA_TFUNCTION:
-      sethvalue(L, L->top, clvalue(o)->c.env);
-      break;
-    case LUA_TUSERDATA:
-      sethvalue(L, L->top, uvalue(o)->env);
-      break;
-    case LUA_TTHREAD:
-      setobj2s(L, L->top,  gt(thvalue(o)));
-      break;
-    default:
-      setnilvalue(L->top);
-      break;
-  }
-  api_incr_top(L);
-  lua_unlock(L);
-}
-
-
-/*
-** set functions (stack -> Lua)
-*/
-
-
-LUA_API void lua_settable (lua_State *L, int idx) {
-  StkId t;
-  lua_lock(L);
-  api_checknelems(L, 2);
-  t = index2adr(L, idx);
-  api_checkvalidindex(L, t);
-  luaV_settable(L, t, L->top - 2, L->top - 1);
-  L->top -= 2;  /* pop index and value */
-  lua_unlock(L);
-}
-
-
-LUA_API void lua_setfield (lua_State *L, int idx, const char *k) {
-  StkId t;
-  lua_lock(L);
-  api_checknelems(L, 1);
-  t = index2adr(L, idx);
-  api_checkvalidindex(L, t);
-  setsvalue2s(L, L->top, luaS_new(L, k));
-  api_incr_top(L);
-  luaV_settable(L, t, L->top - 1, L->top - 2);
-  L->top -= 2;  /* pop key and value */
-  lua_unlock(L);
-}
-
-
-LUA_API void lua_rawset (lua_State *L, int idx) {
-  StkId t;
-  lua_lock(L);
-  api_checknelems(L, 2);
-  t = index2adr(L, idx);
-  api_check(L, ttistable(t));
-  fixedstack(L);
-  setobj2t(L, luaH_set(L, hvalue(t), L->top-2), L->top-1);
-  unfixedstack(L);
-  luaC_barriert(L, hvalue(t), L->top-1);
-  L->top -= 2;
-  lua_unlock(L);
-}
-
-
-LUA_API void lua_rawseti (lua_State *L, int idx, int n) {
-  StkId o;
-  lua_lock(L);
-  api_checknelems(L, 1);
-  o = index2adr(L, idx);
-  api_check(L, ttistable(o));
-  fixedstack(L);
-  setobj2t(L, luaH_setnum(L, hvalue(o), n), L->top-1);
-  unfixedstack(L);
-  luaC_barriert(L, hvalue(o), L->top-1);
-  L->top--;
-  lua_unlock(L);
-}
-
-
-LUA_API int lua_setmetatable (lua_State *L, int objindex) {
-  TValue *obj;
-  Table *mt;
-  int isrometa = 0;
-  lua_lock(L);
-  api_checknelems(L, 1);
-  obj = index2adr(L, objindex);
-  api_checkvalidindex(L, obj);
-  if (ttisnil(L->top - 1))
-    mt = NULL;
-  else {
-    api_check(L, ttistable(L->top - 1) || ttisrotable(L->top - 1));
-    if (ttistable(L->top - 1))
-      mt = hvalue(L->top - 1);
-    else {
-      mt = (Table*)rvalue(L->top - 1);
-      isrometa = 1;
-    }
-  }
-  switch (ttype(obj)) {
-    case LUA_TTABLE: {
-      hvalue(obj)->metatable = mt;
-      if (mt && !isrometa)
-        luaC_objbarriert(L, hvalue(obj), mt);
-      break;
-    }
-    case LUA_TUSERDATA: {
-      uvalue(obj)->metatable = mt;
-      if (mt && !isrometa)
-        luaC_objbarrier(L, rawuvalue(obj), mt);
-      break;
-    }
-    default: {
-      G(L)->mt[ttype(obj)] = mt;
-      break;
-    }
-  }
-  L->top--;
-  lua_unlock(L);
-  return 1;
-}
-
-
-LUA_API int lua_setfenv (lua_State *L, int idx) {
-  StkId o;
-  int res = 1;
-  lua_lock(L);
-  api_checknelems(L, 1);
-  o = index2adr(L, idx);
-  api_checkvalidindex(L, o);
-  api_check(L, ttistable(L->top - 1));
-  switch (ttype(o)) {
-    case LUA_TFUNCTION:
-      clvalue(o)->c.env = hvalue(L->top - 1);
-      break;
-    case LUA_TUSERDATA:
-      uvalue(o)->env = hvalue(L->top - 1);
-      break;
-    case LUA_TTHREAD:
-      sethvalue(L, gt(thvalue(o)), hvalue(L->top - 1));
-      break;
-    default:
-      res = 0;
-      break;
-  }
-  if (res) luaC_objbarrier(L, gcvalue(o), hvalue(L->top - 1));
-  L->top--;
-  lua_unlock(L);
-  return res;
-}
-
-
-/*
-** `load' and `call' functions (run Lua code)
-*/
-
-
-#define adjustresults(L,nres) \
-    { if (nres == LUA_MULTRET && L->top >= L->ci->top) L->ci->top = L->top; }
-
-
-#define checkresults(L,na,nr) \
-     api_check(L, (nr) == LUA_MULTRET || (L->ci->top - L->top >= (nr) - (na)))
-	
-
-LUA_API void lua_call (lua_State *L, int nargs, int nresults) {
-  StkId func;
-  lua_lock(L);
-  api_checknelems(L, nargs+1);
-  checkresults(L, nargs, nresults);
-  func = L->top - (nargs+1);
-  luaD_call(L, func, nresults);
-  adjustresults(L, nresults);
-  lua_unlock(L);
-}
-
-
-
-/*
-** Execute a protected call.
-*/
-struct CallS {  /* data to `f_call' */
-  StkId func;
-  int nresults;
-};
-
-
-static void f_call (lua_State *L, void *ud) {
-  struct CallS *c = cast(struct CallS *, ud);
-  luaD_call(L, c->func, c->nresults);
-}
-
-
-
-LUA_API int lua_pcall (lua_State *L, int nargs, int nresults, int errfunc) {
-  struct CallS c;
-  int status;
-  ptrdiff_t func;
-  lua_lock(L);
-  api_checknelems(L, nargs+1);
-  checkresults(L, nargs, nresults);
-  if (errfunc == 0)
-    func = 0;
-  else {
-    StkId o = index2adr(L, errfunc);
-    api_checkvalidindex(L, o);
-    func = savestack(L, o);
-  }
-  c.func = L->top - (nargs+1);  /* function to be called */
-  c.nresults = nresults;
-  status = luaD_pcall(L, f_call, &c, savestack(L, c.func), func);
-  adjustresults(L, nresults);
-  lua_unlock(L);
-  return status;
-}
-
-
-/*
-** Execute a protected C call.
-*/
-struct CCallS {  /* data to `f_Ccall' */
-  lua_CFunction func;
-  void *ud;
-};
-
-
-static void f_Ccall (lua_State *L, void *ud) {
-  struct CCallS *c = cast(struct CCallS *, ud);
-  Closure *cl;
-  cl = luaF_newCclosure(L, 0, getcurrenv(L));
-  cl->c.f = c->func;
-  setclvalue(L, L->top, cl);  /* push function */
-  api_incr_top(L);
-  setpvalue(L->top, c->ud);  /* push only argument */
-  api_incr_top(L);
-  luaD_call(L, L->top - 2, 0);
-}
-
-
-LUA_API int lua_cpcall (lua_State *L, lua_CFunction func, void *ud) {
-  struct CCallS c;
-  int status;
-  lua_lock(L);
-  c.func = func;
-  c.ud = ud;
-  status = luaD_pcall(L, f_Ccall, &c, savestack(L, L->top), 0);
-  lua_unlock(L);
-  return status;
-}
-
-
-LUA_API int lua_load (lua_State *L, lua_Reader reader, void *data,
-                      const char *chunkname) {
-  ZIO z;
-  int status;
-  lua_lock(L);
-  if (!chunkname) chunkname = "?";
-  luaZ_init(L, &z, reader, data);
-  status = luaD_protectedparser(L, &z, chunkname);
-  lua_unlock(L);
-  return status;
-}
-
-
-LUA_API int lua_dump (lua_State *L, lua_Writer writer, void *data) {
-  int status;
-  TValue *o;
-  lua_lock(L);
-  api_checknelems(L, 1);
-  o = L->top - 1;
-  if (isLfunction(o))
-    status = luaU_dump(L, clvalue(o)->l.p, writer, data, 0);
-  else
-    status = 1;
-  lua_unlock(L);
-  return status;
-}
-
-
-LUA_API int  lua_status (lua_State *L) {
-  return L->status;
-}
-
-
-/*
-** Garbage-collection function
-*/
-
-LUA_API int lua_gc (lua_State *L, int what, int data) {
-  int res = 0;
-  global_State *g;
-  lua_lock(L);
-  g = G(L);
-  switch (what) {
-    case LUA_GCSTOP: {
-      set_block_gc(L);
-      break;
-    }
-    case LUA_GCRESTART: {
-      unset_block_gc(L);
-      break;
-    }
-    case LUA_GCCOLLECT: {
-      luaC_fullgc(L);
-      break;
-    }
-    case LUA_GCCOUNT: {
-      /* GC values are expressed in Kbytes: #bytes/2^10 */
-      res = cast_int(g->totalbytes >> 10);
-      break;
-    }
-    case LUA_GCCOUNTB: {
-      res = cast_int(g->totalbytes & 0x3ff);
-      break;
-    }
-    case LUA_GCSTEP: {
-      if(is_block_gc(L)) {
-        res = 1; /* gc is block so we need to pretend that the collection cycle finished. */
-        break;
-      }
-      lu_mem a = (cast(lu_mem, data) << 10);
-      if (a <= g->totalbytes)
-        g->GCthreshold = g->totalbytes - a;
-      else
-        g->GCthreshold = 0;
-      while (g->GCthreshold <= g->totalbytes) {
-        luaC_step(L);
-        if (g->gcstate == GCSpause) {  /* end of cycle? */
-          res = 1;  /* signal it */
-          break;
-        }
-      }
-      break;
-    }
-    case LUA_GCSETPAUSE: {
-      res = g->gcpause;
-      g->gcpause = data;
-      break;
-    }
-    case LUA_GCSETSTEPMUL: {
-      res = g->gcstepmul;
-      g->gcstepmul = data;
-      break;
-    }
-    case LUA_GCSETMEMLIMIT: {
-      /* GC values are expressed in Kbytes: #bytes/2^10 */
-      lu_mem new_memlimit = (cast(lu_mem, data) << 10);
-      if(new_memlimit > 0 && new_memlimit < g->totalbytes) {
-        /* run a full GC to make totalbytes < the new limit. */
-        luaC_fullgc(L);
-        if(new_memlimit < g->totalbytes)
-          new_memlimit = (g->totalbytes + 1024) & ~(1024-1); /* round up to next multiple of 1024 */
-      }
-      g->memlimit = new_memlimit;
-      /* new memlimit might be > then requested memlimit. */
-      res = cast_int(new_memlimit >> 10);
-      break;
-    }
-    case LUA_GCGETMEMLIMIT: {
-      res = cast_int(g->memlimit >> 10);
-      break;
-    }
-    default: res = -1;  /* invalid option */
-  }
-  lua_unlock(L);
-  return res;
-}
-
-
-
-/*
-** miscellaneous functions
-*/
-
-
-LUA_API int lua_error (lua_State *L) {
-  lua_lock(L);
-  api_checknelems(L, 1);
-  luaG_errormsg(L);
-  lua_unlock(L);
-  return 0;  /* to avoid warnings */
-}
-
-
-LUA_API int lua_next (lua_State *L, int idx) {
-  StkId t;
-  int more;
-  lua_lock(L);
-  t = index2adr(L, idx);
-  api_check(L, ttistable(t) || ttisrotable(t));
-  more = ttistable(t) ? luaH_next(L, hvalue(t), L->top - 1) : luaH_next_ro(L, rvalue(t), L->top - 1);
-  if (more) {
-    api_incr_top(L);
-  }
-  else  /* no more elements */
-    L->top -= 1;  /* remove key */
-  lua_unlock(L);
-  return more;
-}
-
-
-LUA_API void lua_concat (lua_State *L, int n) {
-  lua_lock(L);
-  api_checknelems(L, n);
-  if (n >= 2) {
-    luaC_checkGC(L);
-    luaV_concat(L, n, cast_int(L->top - L->base) - 1);
-    L->top -= (n-1);
-  }
-  else if (n == 0) {  /* push empty string */
-    setsvalue2s(L, L->top, luaS_newlstr(L, "", 0));
-    api_incr_top(L);
-  }
-  /* else n == 1; nothing to do */
-  lua_unlock(L);
-}
-
-
-LUA_API lua_Alloc lua_getallocf (lua_State *L, void **ud) {
-  lua_Alloc f;
-  lua_lock(L);
-  if (ud) *ud = G(L)->ud;
-  f = G(L)->frealloc;
-  lua_unlock(L);
-  return f;
-}
-
-
-LUA_API void lua_setallocf (lua_State *L, lua_Alloc f, void *ud) {
-  lua_lock(L);
-  G(L)->ud = ud;
-  G(L)->frealloc = f;
-  lua_unlock(L);
-}
-
-
-LUA_API void *lua_newuserdata (lua_State *L, size_t size) {
-  Udata *u;
-  lua_lock(L);
-  luaC_checkGC(L);
-  u = luaS_newudata(L, size, getcurrenv(L));
-  setuvalue(L, L->top, u);
-  api_incr_top(L);
-  lua_unlock(L);
-  return u + 1;
-}
-
-
-
-
-static const char *aux_upvalue (StkId fi, int n, TValue **val) {
-  Closure *f;
-  if (!ttisfunction(fi)) return NULL;
-  f = clvalue(fi);
-  if (f->c.isC) {
-    if (!(1 <= n && n <= f->c.nupvalues)) return NULL;
-    *val = &f->c.upvalue[n-1];
-    return "";
-  }
-  else {
-    Proto *p = f->l.p;
-    if (!(1 <= n && n <= p->sizeupvalues)) return NULL;
-    *val = f->l.upvals[n-1]->v;
-    return getstr(p->upvalues[n-1]);
-  }
-}
-
-
-LUA_API const char *lua_getupvalue (lua_State *L, int funcindex, int n) {
-  const char *name;
-  TValue *val;
-  lua_lock(L);
-  name = aux_upvalue(index2adr(L, funcindex), n, &val);
-  if (name) {
-    setobj2s(L, L->top, val);
-    api_incr_top(L);
-  }
-  lua_unlock(L);
-  return name;
-}
-
-
-LUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n) {
-  const char *name;
-  TValue *val;
-  StkId fi;
-  lua_lock(L);
-  fi = index2adr(L, funcindex);
-  api_checknelems(L, 1);
-  name = aux_upvalue(fi, n, &val);
-  if (name) {
-    L->top--;
-    setobj(L, val, L->top);
-    luaC_barrier(L, clvalue(fi), L->top);
-  }
-  lua_unlock(L);
-  return name;
-}
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/lapi.h
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/lapi.h b/libs/elua/elua_base/src/lapi.h
deleted file mode 100644
index 2c3fab2..0000000
--- a/libs/elua/elua_base/src/lapi.h
+++ /dev/null
@@ -1,16 +0,0 @@
-/*
-** $Id: lapi.h,v 2.2.1.1 2007/12/27 13:02:25 roberto Exp $
-** Auxiliary functions from Lua API
-** See Copyright Notice in lua.h
-*/
-
-#ifndef lapi_h
-#define lapi_h
-
-
-#include "lobject.h"
-
-
-LUAI_FUNC void luaA_pushobject (lua_State *L, const TValue *o);
-
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/lauxlib.c
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/lauxlib.c b/libs/elua/elua_base/src/lauxlib.c
deleted file mode 100644
index 2527e9f..0000000
--- a/libs/elua/elua_base/src/lauxlib.c
+++ /dev/null
@@ -1,867 +0,0 @@
-/*
-** $Id: lauxlib.c,v 1.159.1.3 2008/01/21 13:20:51 roberto Exp $
-** Auxiliary functions for building Lua libraries
-** See Copyright Notice in lua.h
-*/
-
-
-#include <ctype.h>
-#include <errno.h>
-#include <stdarg.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#ifdef MYNEWT
-#include <console/console.h>
-#endif
-
-/* This file uses only the official API of Lua.
-** Any function declared here could be written as an application function.
-*/
-
-#define lauxlib_c
-#define LUA_LIB
-
-#include "lua.h"
-
-#include "lrotable.h"
-
-#include "lauxlib.h"
-#include "lgc.h"
-#include "ldo.h"
-#include "lobject.h"
-#include "lstate.h"
-#include "legc.h"
-#ifndef LUA_CROSS_COMPILER
-#include "devman.h"
-#endif
-#ifdef MYNEWT
-#include <fs/fs.h>
-#endif
-
-#define FREELIST_REF	0	/* free list of references */
-
-
-/* convert a stack index to positive */
-#define abs_index(L, i)		((i) > 0 || (i) <= LUA_REGISTRYINDEX ? (i) : \
-					lua_gettop(L) + (i) + 1)
-
-// Parameters for luaI_openlib
-#define LUA_USECCLOSURES          0
-#define LUA_USELIGHTFUNCTIONS     1
-
-/*
-** {======================================================
-** Error-report functions
-** =======================================================
-*/
-
-
-LUALIB_API int luaL_argerror (lua_State *L, int narg, const char *extramsg) {
-  lua_Debug ar;
-  if (!lua_getstack(L, 0, &ar))  /* no stack frame? */
-    return luaL_error(L, "bad argument #%d (%s)", narg, extramsg);
-  lua_getinfo(L, "n", &ar);
-  if (strcmp(ar.namewhat, "method") == 0) {
-    narg--;  /* do not count `self' */
-    if (narg == 0)  /* error is in the self argument itself? */
-      return luaL_error(L, "calling " LUA_QS " on bad self (%s)",
-                           ar.name, extramsg);
-  }
-  if (ar.name == NULL)
-    ar.name = "?";
-  return luaL_error(L, "bad argument #%d to " LUA_QS " (%s)",
-                        narg, ar.name, extramsg);
-}
-
-
-LUALIB_API int luaL_typerror (lua_State *L, int narg, const char *tname) {
-  const char *msg = lua_pushfstring(L, "%s expected, got %s",
-                                    tname, luaL_typename(L, narg));
-  return luaL_argerror(L, narg, msg);
-}
-
-
-static void tag_error (lua_State *L, int narg, int tag) {
-  luaL_typerror(L, narg, lua_typename(L, tag));
-}
-
-
-LUALIB_API void luaL_where (lua_State *L, int level) {
-  lua_Debug ar;
-  if (lua_getstack(L, level, &ar)) {  /* check function at level */
-    lua_getinfo(L, "Sl", &ar);  /* get info about it */
-    if (ar.currentline > 0) {  /* is there info? */
-      lua_pushfstring(L, "%s:%d: ", ar.short_src, ar.currentline);
-      return;
-    }
-  }
-  lua_pushliteral(L, "");  /* else, no information available... */
-}
-
-
-LUALIB_API int luaL_error (lua_State *L, const char *fmt, ...) {
-  va_list argp;
-  va_start(argp, fmt);
-  luaL_where(L, 1);
-  lua_pushvfstring(L, fmt, argp);
-  va_end(argp);
-  lua_concat(L, 2);
-  return lua_error(L);
-}
-
-/* }====================================================== */
-
-
-LUALIB_API int luaL_checkoption (lua_State *L, int narg, const char *def,
-                                 const char *const lst[]) {
-  const char *name = (def) ? luaL_optstring(L, narg, def) :
-                             luaL_checkstring(L, narg);
-  int i;
-  for (i=0; lst[i]; i++)
-    if (strcmp(lst[i], name) == 0)
-      return i;
-  return luaL_argerror(L, narg,
-                       lua_pushfstring(L, "invalid option " LUA_QS, name));
-}
-
-
-LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) {
-  lua_getfield(L, LUA_REGISTRYINDEX, tname);  /* get registry.name */
-  if (!lua_isnil(L, -1))  /* name already in use? */
-    return 0;  /* leave previous value on top, but return 0 */
-  lua_pop(L, 1);
-  lua_newtable(L);  /* create metatable */
-  lua_pushvalue(L, -1);
-  lua_setfield(L, LUA_REGISTRYINDEX, tname);  /* registry.name = metatable */
-  return 1;
-}
-
-LUALIB_API int luaL_rometatable (lua_State *L, const char* tname, void *p) {
-  lua_getfield(L, LUA_REGISTRYINDEX, tname);  /* get registry.name */
-  if (!lua_isnil(L, -1))  /* name already in use? */
-    return 0;  /* leave previous value on top, but return 0 */
-  lua_pop(L, 1);
-  lua_pushrotable(L, p);
-  lua_pushvalue(L, -1);
-  lua_setfield(L, LUA_REGISTRYINDEX, tname);  /* registry.name = metatable */
-  return 1;
-}
-
-LUALIB_API void *luaL_checkudata (lua_State *L, int ud, const char *tname) {
-  void *p = lua_touserdata(L, ud);
-  if (p != NULL) {  /* value is a userdata? */
-    if (lua_getmetatable(L, ud)) {  /* does it have a metatable? */
-      lua_getfield(L, LUA_REGISTRYINDEX, tname);  /* get correct metatable */
-      if (lua_rawequal(L, -1, -2)) {  /* does it have the correct mt? */
-        lua_pop(L, 2);  /* remove both metatables */
-        return p;
-      }
-    }
-  }
-  luaL_typerror(L, ud, tname);  /* else error */
-  return NULL;  /* to avoid warnings */
-}
-
-
-LUALIB_API void luaL_checkstack (lua_State *L, int space, const char *mes) {
-  if (!lua_checkstack(L, space))
-    luaL_error(L, "stack overflow (%s)", mes);
-}
-
-
-LUALIB_API void luaL_checktype (lua_State *L, int narg, int t) {
-  if (lua_type(L, narg) != t)
-    tag_error(L, narg, t);
-}
-
-LUALIB_API void luaL_checkanyfunction (lua_State *L, int narg) {
-  if (lua_type(L, narg) != LUA_TFUNCTION && lua_type(L, narg) != LUA_TLIGHTFUNCTION) {
-    const char *msg = lua_pushfstring(L, "function or lightfunction expected, got %s",
-                                      luaL_typename(L, narg));
-    luaL_argerror(L, narg, msg);    
-  }
-}
-
-LUALIB_API void luaL_checkanytable (lua_State *L, int narg) {
-  if (lua_type(L, narg) != LUA_TTABLE && lua_type(L, narg) != LUA_TROTABLE) {
-    const char *msg = lua_pushfstring(L, "table or rotable expected, got %s",
-                                      luaL_typename(L, narg));
-    luaL_argerror(L, narg, msg);    
-  }
-}
-
-
-LUALIB_API void luaL_checkany (lua_State *L, int narg) {
-  if (lua_type(L, narg) == LUA_TNONE)
-    luaL_argerror(L, narg, "value expected");
-}
-
-
-LUALIB_API const char *luaL_checklstring (lua_State *L, int narg, size_t *len) {
-  const char *s = lua_tolstring(L, narg, len);
-  if (!s) tag_error(L, narg, LUA_TSTRING);
-  return s;
-}
-
-
-LUALIB_API const char *luaL_optlstring (lua_State *L, int narg,
-                                        const char *def, size_t *len) {
-  if (lua_isnoneornil(L, narg)) {
-    if (len)
-      *len = (def ? strlen(def) : 0);
-    return def;
-  }
-  else return luaL_checklstring(L, narg, len);
-}
-
-
-LUALIB_API lua_Number luaL_checknumber (lua_State *L, int narg) {
-  lua_Number d = lua_tonumber(L, narg);
-  if (d == 0 && !lua_isnumber(L, narg))  /* avoid extra test when d is not 0 */
-    tag_error(L, narg, LUA_TNUMBER);
-  return d;
-}
-
-
-LUALIB_API lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number def) {
-  return luaL_opt(L, luaL_checknumber, narg, def);
-}
-
-
-LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int narg) {
-  lua_Integer d = lua_tointeger(L, narg);
-  if (d == 0 && !lua_isnumber(L, narg))  /* avoid extra test when d is not 0 */
-    tag_error(L, narg, LUA_TNUMBER);
-  return d;
-}
-
-
-LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int narg,
-                                                      lua_Integer def) {
-  return luaL_opt(L, luaL_checkinteger, narg, def);
-}
-
-
-LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) {
-  if (!lua_getmetatable(L, obj))  /* no metatable? */
-    return 0;
-  lua_pushstring(L, event);
-  lua_rawget(L, -2);
-  if (lua_isnil(L, -1)) {
-    lua_pop(L, 2);  /* remove metatable and metafield */
-    return 0;
-  }
-  else {
-    lua_remove(L, -2);  /* remove only metatable */
-    return 1;
-  }
-}
-
-
-LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) {
-  obj = abs_index(L, obj);
-  if (!luaL_getmetafield(L, obj, event))  /* no metafield? */
-    return 0;
-  lua_pushvalue(L, obj);
-  lua_call(L, 1, 1);
-  return 1;
-}
-
-
-LUALIB_API void (luaL_register) (lua_State *L, const char *libname,
-                                const luaL_Reg *l) {
-  luaI_openlib(L, libname, l, 0, LUA_USECCLOSURES);
-}
-
-LUALIB_API void (luaL_register_light) (lua_State *L, const char *libname,
-                                const luaL_Reg *l) {
-#if LUA_OPTIMIZE_MEMORY > 0                              
-  luaI_openlib(L, libname, l, 0, LUA_USELIGHTFUNCTIONS);
-#else
-  luaI_openlib(L, libname, l, 0, LUA_USECCLOSURES);
-#endif  
-}
-
-static int libsize (const luaL_Reg *l) {
-  int size = 0;
-  for (; l->name; l++) size++;
-  return size;
-}
-
-
-LUALIB_API void luaI_openlib (lua_State *L, const char *libname,
-                              const luaL_Reg *l, int nup, int ftype) {
-  if (libname) {
-    int size = libsize(l);
-    /* check whether lib already exists */
-    luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 1);
-    lua_getfield(L, -1, libname);  /* get _LOADED[libname] */
-    if (!lua_istable(L, -1)) {  /* not found? */
-      lua_pop(L, 1);  /* remove previous result */
-      /* try global variable (and create one if it does not exist) */
-      if (luaL_findtable(L, LUA_GLOBALSINDEX, libname, size) != NULL)
-        luaL_error(L, "name conflict for module " LUA_QS, libname);
-      lua_pushvalue(L, -1);
-      lua_setfield(L, -3, libname);  /* _LOADED[libname] = new table */
-    }
-    lua_remove(L, -2);  /* remove _LOADED table */
-    lua_insert(L, -(nup+1));  /* move library table to below upvalues */
-  }
-  for (; l->name; l++) {
-    int i;
-    for (i=0; i<nup; i++)  /* copy upvalues to the top */
-      lua_pushvalue(L, -nup);
-    if (ftype == LUA_USELIGHTFUNCTIONS)
-      lua_pushlightfunction(L, l->func);
-    else
-      lua_pushcclosure(L, l->func, nup);
-    lua_setfield(L, -(nup+2), l->name);
-  }
-  lua_pop(L, nup);  /* remove upvalues */
-}
-
-
-
-/*
-** {======================================================
-** getn-setn: size for arrays
-** =======================================================
-*/
-
-#if defined(LUA_COMPAT_GETN)
-
-static int checkint (lua_State *L, int topop) {
-  int n = (lua_type(L, -1) == LUA_TNUMBER) ? lua_tointeger(L, -1) : -1;
-  lua_pop(L, topop);
-  return n;
-}
-
-
-static void getsizes (lua_State *L) {
-  lua_getfield(L, LUA_REGISTRYINDEX, "LUA_SIZES");
-  if (lua_isnil(L, -1)) {  /* no `size' table? */
-    lua_pop(L, 1);  /* remove nil */
-    lua_newtable(L);  /* create it */
-    lua_pushvalue(L, -1);  /* `size' will be its own metatable */
-    lua_setmetatable(L, -2);
-    lua_pushliteral(L, "kv");
-    lua_setfield(L, -2, "__mode");  /* metatable(N).__mode = "kv" */
-    lua_pushvalue(L, -1);
-    lua_setfield(L, LUA_REGISTRYINDEX, "LUA_SIZES");  /* store in register */
-  }
-}
-
-
-LUALIB_API void luaL_setn (lua_State *L, int t, int n) {
-  t = abs_index(L, t);
-  lua_pushliteral(L, "n");
-  lua_rawget(L, t);
-  if (checkint(L, 1) >= 0) {  /* is there a numeric field `n'? */
-    lua_pushliteral(L, "n");  /* use it */
-    lua_pushinteger(L, n);
-    lua_rawset(L, t);
-  }
-  else {  /* use `sizes' */
-    getsizes(L);
-    lua_pushvalue(L, t);
-    lua_pushinteger(L, n);
-    lua_rawset(L, -3);  /* sizes[t] = n */
-    lua_pop(L, 1);  /* remove `sizes' */
-  }
-}
-
-
-LUALIB_API int luaL_getn (lua_State *L, int t) {
-  int n;
-  t = abs_index(L, t);
-  lua_pushliteral(L, "n");  /* try t.n */
-  lua_rawget(L, t);
-  if ((n = checkint(L, 1)) >= 0) return n;
-  getsizes(L);  /* else try sizes[t] */
-  lua_pushvalue(L, t);
-  lua_rawget(L, -2);
-  if ((n = checkint(L, 2)) >= 0) return n;
-  return (int)lua_objlen(L, t);
-}
-
-#endif
-
-/* }====================================================== */
-
-
-
-LUALIB_API const char *luaL_gsub (lua_State *L, const char *s, const char *p,
-                                                               const char *r) {
-  const char *wild;
-  size_t l = strlen(p);
-  luaL_Buffer b;
-  luaL_buffinit(L, &b);
-  while ((wild = strstr(s, p)) != NULL) {
-    luaL_addlstring(&b, s, wild - s);  /* push prefix */
-    luaL_addstring(&b, r);  /* push replacement in place of pattern */
-    s = wild + l;  /* continue after `p' */
-  }
-  luaL_addstring(&b, s);  /* push last suffix */
-  luaL_pushresult(&b);
-  return lua_tostring(L, -1);
-}
-
-
-LUALIB_API const char *luaL_findtable (lua_State *L, int idx,
-                                       const char *fname, int szhint) {
-  const char *e;
-  lua_pushvalue(L, idx);
-  do {
-    e = strchr(fname, '.');
-    if (e == NULL) e = fname + strlen(fname);
-    lua_pushlstring(L, fname, e - fname);
-    lua_rawget(L, -2);
-    if (lua_isnil(L, -1)) {
-      /* If looking for a global variable, check the rotables too */
-      void *ptable = luaR_findglobal(fname, e - fname);
-      if (ptable) {
-        lua_pop(L, 1);
-        lua_pushrotable(L, ptable);
-      }
-    }
-    if (lua_isnil(L, -1)) {  /* no such field? */
-      lua_pop(L, 1);  /* remove this nil */
-      lua_createtable(L, 0, (*e == '.' ? 1 : szhint)); /* new table for field */
-      lua_pushlstring(L, fname, e - fname);
-      lua_pushvalue(L, -2);
-      lua_settable(L, -4);  /* set new table into field */
-    }
-    else if (!lua_istable(L, -1) && !lua_isrotable(L, -1)) {  /* field has a non-table value? */
-      lua_pop(L, 2);  /* remove table and value */
-      return fname;  /* return problematic part of the name */
-    }
-    lua_remove(L, -2);  /* remove previous table */
-    fname = e + 1;
-  } while (*e == '.');
-  return NULL;
-}
-
-
-
-/*
-** {======================================================
-** Generic Buffer manipulation
-** =======================================================
-*/
-
-
-#define bufflen(B)	((B)->p - (B)->buffer)
-#define bufffree(B)	((size_t)(LUAL_BUFFERSIZE - bufflen(B)))
-
-#define LIMIT	(LUA_MINSTACK/2)
-
-
-static int emptybuffer (luaL_Buffer *B) {
-  size_t l = bufflen(B);
-  if (l == 0) return 0;  /* put nothing on stack */
-  else {
-    lua_pushlstring(B->L, B->buffer, l);
-    B->p = B->buffer;
-    B->lvl++;
-    return 1;
-  }
-}
-
-
-static void adjuststack (luaL_Buffer *B) {
-  if (B->lvl > 1) {
-    lua_State *L = B->L;
-    int toget = 1;  /* number of levels to concat */
-    size_t toplen = lua_strlen(L, -1);
-    do {
-      size_t l = lua_strlen(L, -(toget+1));
-      if (B->lvl - toget + 1 >= LIMIT || toplen > l) {
-        toplen += l;
-        toget++;
-      }
-      else break;
-    } while (toget < B->lvl);
-    lua_concat(L, toget);
-    B->lvl = B->lvl - toget + 1;
-  }
-}
-
-
-LUALIB_API char *luaL_prepbuffer (luaL_Buffer *B) {
-  if (emptybuffer(B))
-    adjuststack(B);
-  return B->buffer;
-}
-
-
-LUALIB_API void luaL_addlstring (luaL_Buffer *B, const char *s, size_t l) {
-  while (l--)
-    luaL_addchar(B, *s++);
-}
-
-
-LUALIB_API void luaL_addstring (luaL_Buffer *B, const char *s) {
-  luaL_addlstring(B, s, strlen(s));
-}
-
-
-LUALIB_API void luaL_pushresult (luaL_Buffer *B) {
-  emptybuffer(B);
-  lua_concat(B->L, B->lvl);
-  B->lvl = 1;
-}
-
-
-LUALIB_API void luaL_addvalue (luaL_Buffer *B) {
-  lua_State *L = B->L;
-  size_t vl;
-  const char *s = lua_tolstring(L, -1, &vl);
-  if (vl <= bufffree(B)) {  /* fit into buffer? */
-    memcpy(B->p, s, vl);  /* put it there */
-    B->p += vl;
-    lua_pop(L, 1);  /* remove from stack */
-  }
-  else {
-    if (emptybuffer(B))
-      lua_insert(L, -2);  /* put buffer before new value */
-    B->lvl++;  /* add new value into B stack */
-    adjuststack(B);
-  }
-}
-
-
-LUALIB_API void luaL_buffinit (lua_State *L, luaL_Buffer *B) {
-  B->L = L;
-  B->p = B->buffer;
-  B->lvl = 0;
-}
-
-/* }====================================================== */
-
-
-LUALIB_API int luaL_ref (lua_State *L, int t) {
-  int ref;
-  t = abs_index(L, t);
-  if (lua_isnil(L, -1)) {
-    lua_pop(L, 1);  /* remove from stack */
-    return LUA_REFNIL;  /* `nil' has a unique fixed reference */
-  }
-  lua_rawgeti(L, t, FREELIST_REF);  /* get first free element */
-  ref = (int)lua_tointeger(L, -1);  /* ref = t[FREELIST_REF] */
-  lua_pop(L, 1);  /* remove it from stack */
-  if (ref != 0) {  /* any free element? */
-    lua_rawgeti(L, t, ref);  /* remove it from list */
-    lua_rawseti(L, t, FREELIST_REF);  /* (t[FREELIST_REF] = t[ref]) */
-  }
-  else {  /* no free elements */
-    ref = (int)lua_objlen(L, t);
-    ref++;  /* create new reference */
-  }
-  lua_rawseti(L, t, ref);
-  return ref;
-}
-
-
-LUALIB_API void luaL_unref (lua_State *L, int t, int ref) {
-  if (ref >= 0) {
-    t = abs_index(L, t);
-    lua_rawgeti(L, t, FREELIST_REF);
-    lua_rawseti(L, t, ref);  /* t[ref] = t[FREELIST_REF] */
-    lua_pushinteger(L, ref);
-    lua_rawseti(L, t, FREELIST_REF);  /* t[FREELIST_REF] = ref */
-  }
-}
-
-
-
-/*
-** {======================================================
-** Load functions
-** =======================================================
-*/
-
-typedef struct LoadF {
-  int extraline;
-#ifndef MYNEWT
-  FILE *f;
-#else
-  struct fs_file *f;
-  int readstatus;
-#endif
-  char buff[LUAL_BUFFERSIZE];
-  const char *srcp;
-  size_t totsize;
-} LoadF;
-
-
-static const char *getF (lua_State *L, void *ud, size_t *size) {
-  LoadF *lf = (LoadF *)ud;
-  (void)L;
-  if (L == NULL && size == NULL) // special request: detect 'direct mode'
-    return lf->srcp;
-  if (lf->extraline) {
-    lf->extraline = 0;
-    *size = 1;
-    return "\n";
-  }
-  if (lf->srcp == NULL) { // no direct access
-#ifndef MYNEWT
-    if (feof(lf->f)) return NULL;
-    *size = fread(lf->buff, 1, sizeof(lf->buff), lf->f);
-#else
-    int rc;
-    uint32_t out_len;
-
-    rc = fs_read(lf->f, sizeof(lf->buff), lf->buff, &out_len);
-    if (rc || out_len == 0) {
-      if (rc) {
-        lf->readstatus = rc;
-      }
-      return NULL;
-    }
-    *size = out_len;
-    return lf->buff;
-#endif
-    return (*size > 0) ? lf->buff : NULL;
-  } else { // direct access, return the whole file as a single buffer
-    if (lf->totsize) {
-      *size = lf->totsize;
-      lf->totsize = 0;
-      return lf->srcp;
-    } else
-      return NULL;
-  }
-}
-
-
-static int errfile (lua_State *L, const char *what, int fnameindex) {
-  const char *serr = strerror(errno);
-  const char *filename = lua_tostring(L, fnameindex) + 1;
-  lua_pushfstring(L, "cannot %s %s: %s", what, filename, serr);
-  lua_remove(L, fnameindex);
-  return LUA_ERRFILE;
-}
-
-#ifndef MYNEWT
-LUALIB_API int luaL_loadfile (lua_State *L, const char *filename) {
-  LoadF lf;
-  int status, readstatus;
-  int c;
-  const char *srcp = NULL;
-  int fnameindex = lua_gettop(L) + 1;  /* index of filename on the stack */
-  lf.extraline = lf.totsize = 0;
-  if (filename == NULL) {
-    lua_pushliteral(L, "=stdin");
-    lf.f = stdin;
-  }
-  else {
-    lua_pushfstring(L, "@%s", filename);
-    lf.f = fopen(filename, "r");
-    if (lf.f == NULL) return errfile(L, "open", fnameindex);
-#ifndef LUA_CROSS_COMPILER
-    srcp = dm_getaddr(fileno(lf.f));
-    if (srcp) {
-      fseek(lf.f, 0, SEEK_END);
-      lf.totsize = ftell(lf.f);
-      fseek(lf.f, 0, SEEK_SET);
-    }
-#endif
-  }
-  c = getc(lf.f);
-  if (c == '#') {  /* Unix exec. file? */
-    lf.extraline = 1;
-    while ((c = getc(lf.f)) != EOF && c != '\n') ;  /* skip first line */
-    if (c == '\n') c = getc(lf.f);
-  }
-  if (c == LUA_SIGNATURE[0] && filename) {  /* binary file? */
-    lf.f = freopen(filename, "rb", lf.f);  /* reopen in binary mode */
-    if (lf.f == NULL) return errfile(L, "reopen", fnameindex);
-    /* skip eventual `#!...' */
-   while ((c = getc(lf.f)) != EOF && c != LUA_SIGNATURE[0]) ;
-    lf.extraline = 0;
-  }
-  ungetc(c, lf.f);
-  if (srcp) {
-    lf.srcp = srcp + ftell(lf.f);
-    lf.totsize -= ftell(lf.f);
-  } else
-    lf.srcp = NULL;
-  status = lua_load(L, getF, &lf, lua_tostring(L, -1));
-  readstatus = ferror(lf.f);
-  if (filename) fclose(lf.f);  /* close file (even in case of errors) */
-  if (readstatus) {
-    lua_settop(L, fnameindex);  /* ignore results from `lua_load' */
-    return errfile(L, "read", fnameindex);
-  }
-  lua_remove(L, fnameindex);
-  return status;
-}
-
-#else
-
-int
-luaL_fs_getc(struct fs_file *nf)
-{
-  int rc;
-  uint32_t out_len;
-  char ch;
-
-  rc = fs_read(nf, 1, &ch, &out_len);
-  if (rc || out_len == 0) {
-    return -1;
-  }
-  return ch;
-}
-
-LUALIB_API int luaL_loadfile (lua_State *L, const char *filename) {
-  LoadF lf;
-  int status;
-  struct fs_file *nf;
-  int rc;
-  int c;
-  int fnameindex = lua_gettop(L) + 1;  /* index of filename on the stack */
-  lf.extraline = lf.totsize = 0;
-  if (filename == NULL) {
-    lua_pushliteral(L, "=stdin");
-    return errfile(L, "open", fnameindex);
-  }
-  else {
-    lua_pushfstring(L, "@%s", filename);
-
-    rc = fs_open(filename, FS_ACCESS_READ, &nf);
-    if (rc || nf == NULL) {
-        return errfile(L, "fs_open", fnameindex);
-    }
-    lf.f = nf;
-  }
-  c = luaL_fs_getc(lf.f);
-  if (c == '#') {  /* Unix exec. file? */
-    lf.extraline = 1;
-    while ((c = luaL_fs_getc(lf.f)) != -1 && c != '\n') ;/* skip first line */
-    if (c == '\n') c = luaL_fs_getc(lf.f);
-  }
-  if (c == LUA_SIGNATURE[0] && filename) {  /* binary file? */
-    rc = fs_seek(lf.f, 0);  /* move back to beginning */
-    if (rc) return errfile(L, "fs_seek", fnameindex);
-    /* skip eventual `#!...' */
-   while ((c = luaL_fs_getc(lf.f)) != -1 && c != LUA_SIGNATURE[0]) ;
-    lf.extraline = 0;
-  }
-  fs_seek(lf.f, fs_getpos(lf.f) - 1);
-  lf.readstatus = 0;
-  lf.srcp = NULL;
-  status = lua_load(L, getF, &lf, lua_tostring(L, -1));
-  if (filename) fs_close(lf.f);  /* close file (even in case of errors) */
-  if (lf.readstatus) {
-    lua_settop(L, fnameindex);  /* ignore results from `lua_load' */
-    return errfile(L, "read", fnameindex);
-  }
-  lua_remove(L, fnameindex);
-  return status;
-}
-
-#endif
-
-typedef struct LoadS {
-  const char *s;
-  size_t size;
-} LoadS;
-
-
-static const char *getS (lua_State *L, void *ud, size_t *size) {
-  LoadS *ls = (LoadS *)ud;
-  (void)L;
-  if (L == NULL && size == NULL) // direct mode check
-    return NULL;
-  if (ls->size == 0) return NULL;
-  *size = ls->size;
-  ls->size = 0;
-  return ls->s;
-}
-
-
-LUALIB_API int luaL_loadbuffer (lua_State *L, const char *buff, size_t size,
-                                const char *name) {
-  LoadS ls;
-  ls.s = buff;
-  ls.size = size;
-  return lua_load(L, getS, &ls, name);
-}
-
-
-LUALIB_API int (luaL_loadstring) (lua_State *L, const char *s) {
-  return luaL_loadbuffer(L, s, strlen(s), s);
-}
-
-
-
-/* }====================================================== */
-
-
-static int l_check_memlimit(lua_State *L, size_t needbytes) {
-  global_State *g = G(L);
-  int cycle_count = 0;
-  lu_mem limit = g->memlimit - needbytes;
-  /* don't allow allocation if it requires more memory then the total limit. */
-  if (needbytes > g->memlimit) return 1;
-  /* make sure the GC is not disabled. */
-  if (!is_block_gc(L)) {
-    while (g->totalbytes >= limit) {
-      /* only allow the GC to finished atleast 1 full cycle. */
-      if (g->gcstate == GCSpause && ++cycle_count > 1) break;
-      luaC_step(L);
-    }
-  }
-  return (g->totalbytes >= limit) ? 1 : 0;
-}
-
-
-static void *l_alloc (void *ud, void *ptr, size_t osize, size_t nsize) {
-  lua_State *L = (lua_State *)ud;
-  int mode = L == NULL ? 0 : G(L)->egcmode;
-  void *nptr;
-
-  if (nsize == 0) {
-    free(ptr);
-    return NULL;
-  }
-  if (L != NULL && (mode & EGC_ALWAYS)) /* always collect memory if requested */
-    luaC_fullgc(L);
-  if(nsize > osize && L != NULL) {
-#if defined(LUA_STRESS_EMERGENCY_GC)
-    luaC_fullgc(L);
-#endif
-    if(G(L)->memlimit > 0 && (mode & EGC_ON_MEM_LIMIT) && l_check_memlimit(L, nsize - osize))
-      return NULL;
-  }
-  nptr = realloc(ptr, nsize);
-  if (nptr == NULL && L != NULL && (mode & EGC_ON_ALLOC_FAILURE)) {
-    luaC_fullgc(L); /* emergency full collection. */
-    nptr = realloc(ptr, nsize); /* try allocation again */
-  }
-  return nptr;
-}
-
-
-static int panic (lua_State *L) {
-  (void)L;  /* to avoid warnings */
-#ifndef MYNEWT
-  fprintf(stderr, "PANIC: unprotected error in call to Lua API (%s)\n",
-                   lua_tostring(L, -1));
-#else
-  console_printf("PANIC: unprotected error in call to Lua API (%s)\n",
-    lua_tostring(L, -1));
-#endif
-  return 0;
-}
-
-
-LUALIB_API lua_State *luaL_newstate (void) {
-  lua_State *L = lua_newstate(l_alloc, NULL);
-  lua_setallocf(L, l_alloc, L); /* allocator need lua_State. */
-  if (L) lua_atpanic(L, &panic);
-  return L;
-}
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/lauxlib.h
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/lauxlib.h b/libs/elua/elua_base/src/lauxlib.h
deleted file mode 100644
index 3ff11a3..0000000
--- a/libs/elua/elua_base/src/lauxlib.h
+++ /dev/null
@@ -1,179 +0,0 @@
-/*
-** $Id: lauxlib.h,v 1.88.1.1 2007/12/27 13:02:25 roberto Exp $
-** Auxiliary functions for building Lua libraries
-** See Copyright Notice in lua.h
-*/
-
-
-#ifndef lauxlib_h
-#define lauxlib_h
-
-
-#include <stddef.h>
-#include <stdio.h>
-
-#include "lua.h"
-
-
-#if defined(LUA_COMPAT_GETN)
-LUALIB_API int (luaL_getn) (lua_State *L, int t);
-LUALIB_API void (luaL_setn) (lua_State *L, int t, int n);
-#else
-#define luaL_getn(L,i)          ((int)lua_objlen(L, i))
-#define luaL_setn(L,i,j)        ((void)0)  /* no op! */
-#endif
-
-#if defined(LUA_COMPAT_OPENLIB)
-#define luaI_openlib	luaL_openlib
-#endif
-
-
-/* extra error code for `luaL_load' */
-#define LUA_ERRFILE     (LUA_ERRERR+1)
-
-
-typedef struct luaL_Reg {
-  const char *name;
-  lua_CFunction func;
-} luaL_Reg;
-
-
-
-LUALIB_API void (luaI_openlib) (lua_State *L, const char *libname,
-                                const luaL_Reg *l, int nup, int ftype);
-LUALIB_API void (luaL_register) (lua_State *L, const char *libname,
-                                const luaL_Reg *l);
-LUALIB_API void (luaL_register_light) (lua_State *L, const char *libname,
-                                const luaL_Reg *l);                                
-LUALIB_API int (luaL_getmetafield) (lua_State *L, int obj, const char *e);
-LUALIB_API int (luaL_callmeta) (lua_State *L, int obj, const char *e);
-LUALIB_API int (luaL_typerror) (lua_State *L, int narg, const char *tname);
-LUALIB_API int (luaL_argerror) (lua_State *L, int numarg, const char *extramsg);
-LUALIB_API const char *(luaL_checklstring) (lua_State *L, int numArg,
-                                                          size_t *l);
-LUALIB_API const char *(luaL_optlstring) (lua_State *L, int numArg,
-                                          const char *def, size_t *l);
-LUALIB_API lua_Number (luaL_checknumber) (lua_State *L, int numArg);
-LUALIB_API lua_Number (luaL_optnumber) (lua_State *L, int nArg, lua_Number def);
-
-LUALIB_API lua_Integer (luaL_checkinteger) (lua_State *L, int numArg);
-LUALIB_API lua_Integer (luaL_optinteger) (lua_State *L, int nArg,
-                                          lua_Integer def);
-
-LUALIB_API void (luaL_checkstack) (lua_State *L, int sz, const char *msg);
-LUALIB_API void (luaL_checktype) (lua_State *L, int narg, int t);
-LUALIB_API void (luaL_checkany) (lua_State *L, int narg);
-LUALIB_API void (luaL_checkanyfunction) (lua_State *L, int narg);
-LUALIB_API void (luaL_checkanytable) (lua_State *L, int narg);
-
-LUALIB_API int   (luaL_newmetatable) (lua_State *L, const char *tname);
-LUALIB_API int   (luaL_rometatable) (lua_State *L, const char* tname, void *p);
-LUALIB_API void *(luaL_checkudata) (lua_State *L, int ud, const char *tname);
-
-LUALIB_API void (luaL_where) (lua_State *L, int lvl);
-LUALIB_API int (luaL_error) (lua_State *L, const char *fmt, ...);
-
-LUALIB_API int (luaL_checkoption) (lua_State *L, int narg, const char *def,
-                                   const char *const lst[]);
-
-LUALIB_API int (luaL_ref) (lua_State *L, int t);
-LUALIB_API void (luaL_unref) (lua_State *L, int t, int ref);
-
-LUALIB_API int (luaL_loadfile) (lua_State *L, const char *filename);
-LUALIB_API int (luaL_loadbuffer) (lua_State *L, const char *buff, size_t sz,
-                                  const char *name);
-LUALIB_API int (luaL_loadstring) (lua_State *L, const char *s);
-
-LUALIB_API lua_State *(luaL_newstate) (void);
-
-
-LUALIB_API const char *(luaL_gsub) (lua_State *L, const char *s, const char *p,
-                                                  const char *r);
-
-LUALIB_API const char *(luaL_findtable) (lua_State *L, int idx,
-                                         const char *fname, int szhint);
-
-
-
-
-/*
-** ===============================================================
-** some useful macros
-** ===============================================================
-*/
-
-#define luaL_argcheck(L, cond,numarg,extramsg)	\
-		((void)((cond) || luaL_argerror(L, (numarg), (extramsg))))
-#define luaL_checkstring(L,n)	(luaL_checklstring(L, (n), NULL))
-#define luaL_optstring(L,n,d)	(luaL_optlstring(L, (n), (d), NULL))
-#define luaL_checkint(L,n)	((int)luaL_checkinteger(L, (n)))
-#define luaL_optint(L,n,d)	((int)luaL_optinteger(L, (n), (d)))
-#define luaL_checklong(L,n)	((long)luaL_checkinteger(L, (n)))
-#define luaL_optlong(L,n,d)	((long)luaL_optinteger(L, (n), (d)))
-
-#define luaL_typename(L,i)	lua_typename(L, lua_type(L,(i)))
-
-#define luaL_dofile(L, fn) \
-	(luaL_loadfile(L, fn) || lua_pcall(L, 0, LUA_MULTRET, 0))
-
-#define luaL_dostring(L, s) \
-	(luaL_loadstring(L, s) || lua_pcall(L, 0, LUA_MULTRET, 0))
-
-#define luaL_getmetatable(L,n)	(lua_getfield(L, LUA_REGISTRYINDEX, (n)))
-
-#define luaL_opt(L,f,n,d)	(lua_isnoneornil(L,(n)) ? (d) : f(L,(n)))
-
-/*
-** {======================================================
-** Generic Buffer manipulation
-** =======================================================
-*/
-
-
-
-typedef struct luaL_Buffer {
-  char *p;			/* current position in buffer */
-  int lvl;  /* number of strings in the stack (level) */
-  lua_State *L;
-  char buffer[LUAL_BUFFERSIZE];
-} luaL_Buffer;
-
-#define luaL_addchar(B,c) \
-  ((void)((B)->p < ((B)->buffer+LUAL_BUFFERSIZE) || luaL_prepbuffer(B)), \
-   (*(B)->p++ = (char)(c)))
-
-/* compatibility only */
-#define luaL_putchar(B,c)	luaL_addchar(B,c)
-
-#define luaL_addsize(B,n)	((B)->p += (n))
-
-LUALIB_API void (luaL_buffinit) (lua_State *L, luaL_Buffer *B);
-LUALIB_API char *(luaL_prepbuffer) (luaL_Buffer *B);
-LUALIB_API void (luaL_addlstring) (luaL_Buffer *B, const char *s, size_t l);
-LUALIB_API void (luaL_addstring) (luaL_Buffer *B, const char *s);
-LUALIB_API void (luaL_addvalue) (luaL_Buffer *B);
-LUALIB_API void (luaL_pushresult) (luaL_Buffer *B);
-
-
-/* }====================================================== */
-
-
-/* compatibility with ref system */
-
-/* pre-defined references */
-#define LUA_NOREF       (-2)
-#define LUA_REFNIL      (-1)
-
-#define lua_ref(L,lock) ((lock) ? luaL_ref(L, LUA_REGISTRYINDEX) : \
-      (lua_pushstring(L, "unlocked references are obsolete"), lua_error(L), 0))
-
-#define lua_unref(L,ref)        luaL_unref(L, LUA_REGISTRYINDEX, (ref))
-
-#define lua_getref(L,ref)       lua_rawgeti(L, LUA_REGISTRYINDEX, (ref))
-
-
-#define luaL_reg	luaL_Reg
-
-#endif
-
-


[26/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/cmsis-core/src/ext/core_cm3.h
----------------------------------------------------------------------
diff --git a/libs/cmsis-core/src/ext/core_cm3.h b/libs/cmsis-core/src/ext/core_cm3.h
deleted file mode 100644
index 122c9aa..0000000
--- a/libs/cmsis-core/src/ext/core_cm3.h
+++ /dev/null
@@ -1,1627 +0,0 @@
-/**************************************************************************//**
- * @file     core_cm3.h
- * @brief    CMSIS Cortex-M3 Core Peripheral Access Layer Header File
- * @version  V3.20
- * @date     25. February 2013
- *
- * @note
- *
- ******************************************************************************/
-/* Copyright (c) 2009 - 2013 ARM LIMITED
-
-   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 ARM 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 COPYRIGHT HOLDERS AND CONTRIBUTORS BE
-   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-   POSSIBILITY OF SUCH DAMAGE.
-   ---------------------------------------------------------------------------*/
-
-
-#if defined ( __ICCARM__ )
- #pragma system_include  /* treat file as system include file for MISRA check */
-#endif
-
-#ifdef __cplusplus
- extern "C" {
-#endif
-
-#ifndef __CORE_CM3_H_GENERIC
-#define __CORE_CM3_H_GENERIC
-
-/** \page CMSIS_MISRA_Exceptions  MISRA-C:2004 Compliance Exceptions
-  CMSIS violates the following MISRA-C:2004 rules:
-
-   \li Required Rule 8.5, object/function definition in header file.<br>
-     Function definitions in header files are used to allow 'inlining'.
-
-   \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.<br>
-     Unions are used for effective representation of core registers.
-
-   \li Advisory Rule 19.7, Function-like macro defined.<br>
-     Function-like macros are used to allow more efficient code.
- */
-
-
-/*******************************************************************************
- *                 CMSIS definitions
- ******************************************************************************/
-/** \ingroup Cortex_M3
-  @{
- */
-
-/*  CMSIS CM3 definitions */
-#define __CM3_CMSIS_VERSION_MAIN  (0x03)                                   /*!< [31:16] CMSIS HAL main version   */
-#define __CM3_CMSIS_VERSION_SUB   (0x20)                                   /*!< [15:0]  CMSIS HAL sub version    */
-#define __CM3_CMSIS_VERSION       ((__CM3_CMSIS_VERSION_MAIN << 16) | \
-                                    __CM3_CMSIS_VERSION_SUB          )     /*!< CMSIS HAL version number         */
-
-#define __CORTEX_M                (0x03)                                   /*!< Cortex-M Core                    */
-
-
-#if   defined ( __CC_ARM )
-  #define __ASM            __asm                                      /*!< asm keyword for ARM Compiler          */
-  #define __INLINE         __inline                                   /*!< inline keyword for ARM Compiler       */
-  #define __STATIC_INLINE  static __inline
-
-#elif defined ( __ICCARM__ )
-  #define __ASM            __asm                                      /*!< asm keyword for IAR Compiler          */
-  #define __INLINE         inline                                     /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */
-  #define __STATIC_INLINE  static inline
-
-#elif defined ( __TMS470__ )
-  #define __ASM            __asm                                      /*!< asm keyword for TI CCS Compiler       */
-  #define __STATIC_INLINE  static inline
-
-#elif defined ( __GNUC__ )
-  #define __ASM            __asm                                      /*!< asm keyword for GNU Compiler          */
-  #define __INLINE         inline                                     /*!< inline keyword for GNU Compiler       */
-  #define __STATIC_INLINE  static inline
-
-#elif defined ( __TASKING__ )
-  #define __ASM            __asm                                      /*!< asm keyword for TASKING Compiler      */
-  #define __INLINE         inline                                     /*!< inline keyword for TASKING Compiler   */
-  #define __STATIC_INLINE  static inline
-
-#endif
-
-/** __FPU_USED indicates whether an FPU is used or not. This core does not support an FPU at all
-*/
-#define __FPU_USED       0
-
-#if defined ( __CC_ARM )
-  #if defined __TARGET_FPU_VFP
-    #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
-  #endif
-
-#elif defined ( __ICCARM__ )
-  #if defined __ARMVFP__
-    #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
-  #endif
-
-#elif defined ( __TMS470__ )
-  #if defined __TI__VFP_SUPPORT____
-    #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
-  #endif
-
-#elif defined ( __GNUC__ )
-  #if defined (__VFP_FP__) && !defined(__SOFTFP__)
-    #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
-  #endif
-
-#elif defined ( __TASKING__ )
-  #if defined __FPU_VFP__
-    #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
-  #endif
-#endif
-
-#include <stdint.h>                      /* standard types definitions                      */
-#include <core_cmInstr.h>                /* Core Instruction Access                         */
-#include <core_cmFunc.h>                 /* Core Function Access                            */
-
-#endif /* __CORE_CM3_H_GENERIC */
-
-#ifndef __CMSIS_GENERIC
-
-#ifndef __CORE_CM3_H_DEPENDANT
-#define __CORE_CM3_H_DEPENDANT
-
-/* check device defines and use defaults */
-#if defined __CHECK_DEVICE_DEFINES
-  #ifndef __CM3_REV
-    #define __CM3_REV               0x0200
-    #warning "__CM3_REV not defined in device header file; using default!"
-  #endif
-
-  #ifndef __MPU_PRESENT
-    #define __MPU_PRESENT             0
-    #warning "__MPU_PRESENT not defined in device header file; using default!"
-  #endif
-
-  #ifndef __NVIC_PRIO_BITS
-    #define __NVIC_PRIO_BITS          4
-    #warning "__NVIC_PRIO_BITS not defined in device header file; using default!"
-  #endif
-
-  #ifndef __Vendor_SysTickConfig
-    #define __Vendor_SysTickConfig    0
-    #warning "__Vendor_SysTickConfig not defined in device header file; using default!"
-  #endif
-#endif
-
-/* IO definitions (access restrictions to peripheral registers) */
-/**
-    \defgroup CMSIS_glob_defs CMSIS Global Defines
-
-    <strong>IO Type Qualifiers</strong> are used
-    \li to specify the access to peripheral variables.
-    \li for automatic generation of peripheral register debug information.
-*/
-#ifdef __cplusplus
-  #define   __I     volatile             /*!< Defines 'read only' permissions                 */
-#else
-  #define   __I     volatile const       /*!< Defines 'read only' permissions                 */
-#endif
-#define     __O     volatile             /*!< Defines 'write only' permissions                */
-#define     __IO    volatile             /*!< Defines 'read / write' permissions              */
-
-/*@} end of group Cortex_M3 */
-
-
-
-/*******************************************************************************
- *                 Register Abstraction
-  Core Register contain:
-  - Core Register
-  - Core NVIC Register
-  - Core SCB Register
-  - Core SysTick Register
-  - Core Debug Register
-  - Core MPU Register
- ******************************************************************************/
-/** \defgroup CMSIS_core_register Defines and Type Definitions
-    \brief Type definitions and defines for Cortex-M processor based devices.
-*/
-
-/** \ingroup    CMSIS_core_register
-    \defgroup   CMSIS_CORE  Status and Control Registers
-    \brief  Core Register type definitions.
-  @{
- */
-
-/** \brief  Union type to access the Application Program Status Register (APSR).
- */
-typedef union
-{
-  struct
-  {
-#if (__CORTEX_M != 0x04)
-    uint32_t _reserved0:27;              /*!< bit:  0..26  Reserved                           */
-#else
-    uint32_t _reserved0:16;              /*!< bit:  0..15  Reserved                           */
-    uint32_t GE:4;                       /*!< bit: 16..19  Greater than or Equal flags        */
-    uint32_t _reserved1:7;               /*!< bit: 20..26  Reserved                           */
-#endif
-    uint32_t Q:1;                        /*!< bit:     27  Saturation condition flag          */
-    uint32_t V:1;                        /*!< bit:     28  Overflow condition code flag       */
-    uint32_t C:1;                        /*!< bit:     29  Carry condition code flag          */
-    uint32_t Z:1;                        /*!< bit:     30  Zero condition code flag           */
-    uint32_t N:1;                        /*!< bit:     31  Negative condition code flag       */
-  } b;                                   /*!< Structure used for bit  access                  */
-  uint32_t w;                            /*!< Type      used for word access                  */
-} APSR_Type;
-
-
-/** \brief  Union type to access the Interrupt Program Status Register (IPSR).
- */
-typedef union
-{
-  struct
-  {
-    uint32_t ISR:9;                      /*!< bit:  0.. 8  Exception number                   */
-    uint32_t _reserved0:23;              /*!< bit:  9..31  Reserved                           */
-  } b;                                   /*!< Structure used for bit  access                  */
-  uint32_t w;                            /*!< Type      used for word access                  */
-} IPSR_Type;
-
-
-/** \brief  Union type to access the Special-Purpose Program Status Registers (xPSR).
- */
-typedef union
-{
-  struct
-  {
-    uint32_t ISR:9;                      /*!< bit:  0.. 8  Exception number                   */
-#if (__CORTEX_M != 0x04)
-    uint32_t _reserved0:15;              /*!< bit:  9..23  Reserved                           */
-#else
-    uint32_t _reserved0:7;               /*!< bit:  9..15  Reserved                           */
-    uint32_t GE:4;                       /*!< bit: 16..19  Greater than or Equal flags        */
-    uint32_t _reserved1:4;               /*!< bit: 20..23  Reserved                           */
-#endif
-    uint32_t T:1;                        /*!< bit:     24  Thumb bit        (read 0)          */
-    uint32_t IT:2;                       /*!< bit: 25..26  saved IT state   (read 0)          */
-    uint32_t Q:1;                        /*!< bit:     27  Saturation condition flag          */
-    uint32_t V:1;                        /*!< bit:     28  Overflow condition code flag       */
-    uint32_t C:1;                        /*!< bit:     29  Carry condition code flag          */
-    uint32_t Z:1;                        /*!< bit:     30  Zero condition code flag           */
-    uint32_t N:1;                        /*!< bit:     31  Negative condition code flag       */
-  } b;                                   /*!< Structure used for bit  access                  */
-  uint32_t w;                            /*!< Type      used for word access                  */
-} xPSR_Type;
-
-
-/** \brief  Union type to access the Control Registers (CONTROL).
- */
-typedef union
-{
-  struct
-  {
-    uint32_t nPRIV:1;                    /*!< bit:      0  Execution privilege in Thread mode */
-    uint32_t SPSEL:1;                    /*!< bit:      1  Stack to be used                   */
-    uint32_t FPCA:1;                     /*!< bit:      2  FP extension active flag           */
-    uint32_t _reserved0:29;              /*!< bit:  3..31  Reserved                           */
-  } b;                                   /*!< Structure used for bit  access                  */
-  uint32_t w;                            /*!< Type      used for word access                  */
-} CONTROL_Type;
-
-/*@} end of group CMSIS_CORE */
-
-
-/** \ingroup    CMSIS_core_register
-    \defgroup   CMSIS_NVIC  Nested Vectored Interrupt Controller (NVIC)
-    \brief      Type definitions for the NVIC Registers
-  @{
- */
-
-/** \brief  Structure type to access the Nested Vectored Interrupt Controller (NVIC).
- */
-typedef struct
-{
-  __IO uint32_t ISER[8];                 /*!< Offset: 0x000 (R/W)  Interrupt Set Enable Register           */
-       uint32_t RESERVED0[24];
-  __IO uint32_t ICER[8];                 /*!< Offset: 0x080 (R/W)  Interrupt Clear Enable Register         */
-       uint32_t RSERVED1[24];
-  __IO uint32_t ISPR[8];                 /*!< Offset: 0x100 (R/W)  Interrupt Set Pending Register          */
-       uint32_t RESERVED2[24];
-  __IO uint32_t ICPR[8];                 /*!< Offset: 0x180 (R/W)  Interrupt Clear Pending Register        */
-       uint32_t RESERVED3[24];
-  __IO uint32_t IABR[8];                 /*!< Offset: 0x200 (R/W)  Interrupt Active bit Register           */
-       uint32_t RESERVED4[56];
-  __IO uint8_t  IP[240];                 /*!< Offset: 0x300 (R/W)  Interrupt Priority Register (8Bit wide) */
-       uint32_t RESERVED5[644];
-  __O  uint32_t STIR;                    /*!< Offset: 0xE00 ( /W)  Software Trigger Interrupt Register     */
-}  NVIC_Type;
-
-/* Software Triggered Interrupt Register Definitions */
-#define NVIC_STIR_INTID_Pos                 0                                          /*!< STIR: INTLINESNUM Position */
-#define NVIC_STIR_INTID_Msk                (0x1FFUL << NVIC_STIR_INTID_Pos)            /*!< STIR: INTLINESNUM Mask */
-
-/*@} end of group CMSIS_NVIC */
-
-
-/** \ingroup  CMSIS_core_register
-    \defgroup CMSIS_SCB     System Control Block (SCB)
-    \brief      Type definitions for the System Control Block Registers
-  @{
- */
-
-/** \brief  Structure type to access the System Control Block (SCB).
- */
-typedef struct
-{
-  __I  uint32_t CPUID;                   /*!< Offset: 0x000 (R/ )  CPUID Base Register                                   */
-  __IO uint32_t ICSR;                    /*!< Offset: 0x004 (R/W)  Interrupt Control and State Register                  */
-  __IO uint32_t VTOR;                    /*!< Offset: 0x008 (R/W)  Vector Table Offset Register                          */
-  __IO uint32_t AIRCR;                   /*!< Offset: 0x00C (R/W)  Application Interrupt and Reset Control Register      */
-  __IO uint32_t SCR;                     /*!< Offset: 0x010 (R/W)  System Control Register                               */
-  __IO uint32_t CCR;                     /*!< Offset: 0x014 (R/W)  Configuration Control Register                        */
-  __IO uint8_t  SHP[12];                 /*!< Offset: 0x018 (R/W)  System Handlers Priority Registers (4-7, 8-11, 12-15) */
-  __IO uint32_t SHCSR;                   /*!< Offset: 0x024 (R/W)  System Handler Control and State Register             */
-  __IO uint32_t CFSR;                    /*!< Offset: 0x028 (R/W)  Configurable Fault Status Register                    */
-  __IO uint32_t HFSR;                    /*!< Offset: 0x02C (R/W)  HardFault Status Register                             */
-  __IO uint32_t DFSR;                    /*!< Offset: 0x030 (R/W)  Debug Fault Status Register                           */
-  __IO uint32_t MMFAR;                   /*!< Offset: 0x034 (R/W)  MemManage Fault Address Register                      */
-  __IO uint32_t BFAR;                    /*!< Offset: 0x038 (R/W)  BusFault Address Register                             */
-  __IO uint32_t AFSR;                    /*!< Offset: 0x03C (R/W)  Auxiliary Fault Status Register                       */
-  __I  uint32_t PFR[2];                  /*!< Offset: 0x040 (R/ )  Processor Feature Register                            */
-  __I  uint32_t DFR;                     /*!< Offset: 0x048 (R/ )  Debug Feature Register                                */
-  __I  uint32_t ADR;                     /*!< Offset: 0x04C (R/ )  Auxiliary Feature Register                            */
-  __I  uint32_t MMFR[4];                 /*!< Offset: 0x050 (R/ )  Memory Model Feature Register                         */
-  __I  uint32_t ISAR[5];                 /*!< Offset: 0x060 (R/ )  Instruction Set Attributes Register                   */
-       uint32_t RESERVED0[5];
-  __IO uint32_t CPACR;                   /*!< Offset: 0x088 (R/W)  Coprocessor Access Control Register                   */
-} SCB_Type;
-
-/* SCB CPUID Register Definitions */
-#define SCB_CPUID_IMPLEMENTER_Pos          24                                             /*!< SCB CPUID: IMPLEMENTER Position */
-#define SCB_CPUID_IMPLEMENTER_Msk          (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos)          /*!< SCB CPUID: IMPLEMENTER Mask */
-
-#define SCB_CPUID_VARIANT_Pos              20                                             /*!< SCB CPUID: VARIANT Position */
-#define SCB_CPUID_VARIANT_Msk              (0xFUL << SCB_CPUID_VARIANT_Pos)               /*!< SCB CPUID: VARIANT Mask */
-
-#define SCB_CPUID_ARCHITECTURE_Pos         16                                             /*!< SCB CPUID: ARCHITECTURE Position */
-#define SCB_CPUID_ARCHITECTURE_Msk         (0xFUL << SCB_CPUID_ARCHITECTURE_Pos)          /*!< SCB CPUID: ARCHITECTURE Mask */
-
-#define SCB_CPUID_PARTNO_Pos                4                                             /*!< SCB CPUID: PARTNO Position */
-#define SCB_CPUID_PARTNO_Msk               (0xFFFUL << SCB_CPUID_PARTNO_Pos)              /*!< SCB CPUID: PARTNO Mask */
-
-#define SCB_CPUID_REVISION_Pos              0                                             /*!< SCB CPUID: REVISION Position */
-#define SCB_CPUID_REVISION_Msk             (0xFUL << SCB_CPUID_REVISION_Pos)              /*!< SCB CPUID: REVISION Mask */
-
-/* SCB Interrupt Control State Register Definitions */
-#define SCB_ICSR_NMIPENDSET_Pos            31                                             /*!< SCB ICSR: NMIPENDSET Position */
-#define SCB_ICSR_NMIPENDSET_Msk            (1UL << SCB_ICSR_NMIPENDSET_Pos)               /*!< SCB ICSR: NMIPENDSET Mask */
-
-#define SCB_ICSR_PENDSVSET_Pos             28                                             /*!< SCB ICSR: PENDSVSET Position */
-#define SCB_ICSR_PENDSVSET_Msk             (1UL << SCB_ICSR_PENDSVSET_Pos)                /*!< SCB ICSR: PENDSVSET Mask */
-
-#define SCB_ICSR_PENDSVCLR_Pos             27                                             /*!< SCB ICSR: PENDSVCLR Position */
-#define SCB_ICSR_PENDSVCLR_Msk             (1UL << SCB_ICSR_PENDSVCLR_Pos)                /*!< SCB ICSR: PENDSVCLR Mask */
-
-#define SCB_ICSR_PENDSTSET_Pos             26                                             /*!< SCB ICSR: PENDSTSET Position */
-#define SCB_ICSR_PENDSTSET_Msk             (1UL << SCB_ICSR_PENDSTSET_Pos)                /*!< SCB ICSR: PENDSTSET Mask */
-
-#define SCB_ICSR_PENDSTCLR_Pos             25                                             /*!< SCB ICSR: PENDSTCLR Position */
-#define SCB_ICSR_PENDSTCLR_Msk             (1UL << SCB_ICSR_PENDSTCLR_Pos)                /*!< SCB ICSR: PENDSTCLR Mask */
-
-#define SCB_ICSR_ISRPREEMPT_Pos            23                                             /*!< SCB ICSR: ISRPREEMPT Position */
-#define SCB_ICSR_ISRPREEMPT_Msk            (1UL << SCB_ICSR_ISRPREEMPT_Pos)               /*!< SCB ICSR: ISRPREEMPT Mask */
-
-#define SCB_ICSR_ISRPENDING_Pos            22                                             /*!< SCB ICSR: ISRPENDING Position */
-#define SCB_ICSR_ISRPENDING_Msk            (1UL << SCB_ICSR_ISRPENDING_Pos)               /*!< SCB ICSR: ISRPENDING Mask */
-
-#define SCB_ICSR_VECTPENDING_Pos           12                                             /*!< SCB ICSR: VECTPENDING Position */
-#define SCB_ICSR_VECTPENDING_Msk           (0x1FFUL << SCB_ICSR_VECTPENDING_Pos)          /*!< SCB ICSR: VECTPENDING Mask */
-
-#define SCB_ICSR_RETTOBASE_Pos             11                                             /*!< SCB ICSR: RETTOBASE Position */
-#define SCB_ICSR_RETTOBASE_Msk             (1UL << SCB_ICSR_RETTOBASE_Pos)                /*!< SCB ICSR: RETTOBASE Mask */
-
-#define SCB_ICSR_VECTACTIVE_Pos             0                                             /*!< SCB ICSR: VECTACTIVE Position */
-#define SCB_ICSR_VECTACTIVE_Msk            (0x1FFUL << SCB_ICSR_VECTACTIVE_Pos)           /*!< SCB ICSR: VECTACTIVE Mask */
-
-/* SCB Vector Table Offset Register Definitions */
-#if (__CM3_REV < 0x0201)                   /* core r2p1 */
-#define SCB_VTOR_TBLBASE_Pos               29                                             /*!< SCB VTOR: TBLBASE Position */
-#define SCB_VTOR_TBLBASE_Msk               (1UL << SCB_VTOR_TBLBASE_Pos)                  /*!< SCB VTOR: TBLBASE Mask */
-
-#define SCB_VTOR_TBLOFF_Pos                 7                                             /*!< SCB VTOR: TBLOFF Position */
-#define SCB_VTOR_TBLOFF_Msk                (0x3FFFFFUL << SCB_VTOR_TBLOFF_Pos)            /*!< SCB VTOR: TBLOFF Mask */
-#else
-#define SCB_VTOR_TBLOFF_Pos                 7                                             /*!< SCB VTOR: TBLOFF Position */
-#define SCB_VTOR_TBLOFF_Msk                (0x1FFFFFFUL << SCB_VTOR_TBLOFF_Pos)           /*!< SCB VTOR: TBLOFF Mask */
-#endif
-
-/* SCB Application Interrupt and Reset Control Register Definitions */
-#define SCB_AIRCR_VECTKEY_Pos              16                                             /*!< SCB AIRCR: VECTKEY Position */
-#define SCB_AIRCR_VECTKEY_Msk              (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos)            /*!< SCB AIRCR: VECTKEY Mask */
-
-#define SCB_AIRCR_VECTKEYSTAT_Pos          16                                             /*!< SCB AIRCR: VECTKEYSTAT Position */
-#define SCB_AIRCR_VECTKEYSTAT_Msk          (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos)        /*!< SCB AIRCR: VECTKEYSTAT Mask */
-
-#define SCB_AIRCR_ENDIANESS_Pos            15                                             /*!< SCB AIRCR: ENDIANESS Position */
-#define SCB_AIRCR_ENDIANESS_Msk            (1UL << SCB_AIRCR_ENDIANESS_Pos)               /*!< SCB AIRCR: ENDIANESS Mask */
-
-#define SCB_AIRCR_PRIGROUP_Pos              8                                             /*!< SCB AIRCR: PRIGROUP Position */
-#define SCB_AIRCR_PRIGROUP_Msk             (7UL << SCB_AIRCR_PRIGROUP_Pos)                /*!< SCB AIRCR: PRIGROUP Mask */
-
-#define SCB_AIRCR_SYSRESETREQ_Pos           2                                             /*!< SCB AIRCR: SYSRESETREQ Position */
-#define SCB_AIRCR_SYSRESETREQ_Msk          (1UL << SCB_AIRCR_SYSRESETREQ_Pos)             /*!< SCB AIRCR: SYSRESETREQ Mask */
-
-#define SCB_AIRCR_VECTCLRACTIVE_Pos         1                                             /*!< SCB AIRCR: VECTCLRACTIVE Position */
-#define SCB_AIRCR_VECTCLRACTIVE_Msk        (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos)           /*!< SCB AIRCR: VECTCLRACTIVE Mask */
-
-#define SCB_AIRCR_VECTRESET_Pos             0                                             /*!< SCB AIRCR: VECTRESET Position */
-#define SCB_AIRCR_VECTRESET_Msk            (1UL << SCB_AIRCR_VECTRESET_Pos)               /*!< SCB AIRCR: VECTRESET Mask */
-
-/* SCB System Control Register Definitions */
-#define SCB_SCR_SEVONPEND_Pos               4                                             /*!< SCB SCR: SEVONPEND Position */
-#define SCB_SCR_SEVONPEND_Msk              (1UL << SCB_SCR_SEVONPEND_Pos)                 /*!< SCB SCR: SEVONPEND Mask */
-
-#define SCB_SCR_SLEEPDEEP_Pos               2                                             /*!< SCB SCR: SLEEPDEEP Position */
-#define SCB_SCR_SLEEPDEEP_Msk              (1UL << SCB_SCR_SLEEPDEEP_Pos)                 /*!< SCB SCR: SLEEPDEEP Mask */
-
-#define SCB_SCR_SLEEPONEXIT_Pos             1                                             /*!< SCB SCR: SLEEPONEXIT Position */
-#define SCB_SCR_SLEEPONEXIT_Msk            (1UL << SCB_SCR_SLEEPONEXIT_Pos)               /*!< SCB SCR: SLEEPONEXIT Mask */
-
-/* SCB Configuration Control Register Definitions */
-#define SCB_CCR_STKALIGN_Pos                9                                             /*!< SCB CCR: STKALIGN Position */
-#define SCB_CCR_STKALIGN_Msk               (1UL << SCB_CCR_STKALIGN_Pos)                  /*!< SCB CCR: STKALIGN Mask */
-
-#define SCB_CCR_BFHFNMIGN_Pos               8                                             /*!< SCB CCR: BFHFNMIGN Position */
-#define SCB_CCR_BFHFNMIGN_Msk              (1UL << SCB_CCR_BFHFNMIGN_Pos)                 /*!< SCB CCR: BFHFNMIGN Mask */
-
-#define SCB_CCR_DIV_0_TRP_Pos               4                                             /*!< SCB CCR: DIV_0_TRP Position */
-#define SCB_CCR_DIV_0_TRP_Msk              (1UL << SCB_CCR_DIV_0_TRP_Pos)                 /*!< SCB CCR: DIV_0_TRP Mask */
-
-#define SCB_CCR_UNALIGN_TRP_Pos             3                                             /*!< SCB CCR: UNALIGN_TRP Position */
-#define SCB_CCR_UNALIGN_TRP_Msk            (1UL << SCB_CCR_UNALIGN_TRP_Pos)               /*!< SCB CCR: UNALIGN_TRP Mask */
-
-#define SCB_CCR_USERSETMPEND_Pos            1                                             /*!< SCB CCR: USERSETMPEND Position */
-#define SCB_CCR_USERSETMPEND_Msk           (1UL << SCB_CCR_USERSETMPEND_Pos)              /*!< SCB CCR: USERSETMPEND Mask */
-
-#define SCB_CCR_NONBASETHRDENA_Pos          0                                             /*!< SCB CCR: NONBASETHRDENA Position */
-#define SCB_CCR_NONBASETHRDENA_Msk         (1UL << SCB_CCR_NONBASETHRDENA_Pos)            /*!< SCB CCR: NONBASETHRDENA Mask */
-
-/* SCB System Handler Control and State Register Definitions */
-#define SCB_SHCSR_USGFAULTENA_Pos          18                                             /*!< SCB SHCSR: USGFAULTENA Position */
-#define SCB_SHCSR_USGFAULTENA_Msk          (1UL << SCB_SHCSR_USGFAULTENA_Pos)             /*!< SCB SHCSR: USGFAULTENA Mask */
-
-#define SCB_SHCSR_BUSFAULTENA_Pos          17                                             /*!< SCB SHCSR: BUSFAULTENA Position */
-#define SCB_SHCSR_BUSFAULTENA_Msk          (1UL << SCB_SHCSR_BUSFAULTENA_Pos)             /*!< SCB SHCSR: BUSFAULTENA Mask */
-
-#define SCB_SHCSR_MEMFAULTENA_Pos          16                                             /*!< SCB SHCSR: MEMFAULTENA Position */
-#define SCB_SHCSR_MEMFAULTENA_Msk          (1UL << SCB_SHCSR_MEMFAULTENA_Pos)             /*!< SCB SHCSR: MEMFAULTENA Mask */
-
-#define SCB_SHCSR_SVCALLPENDED_Pos         15                                             /*!< SCB SHCSR: SVCALLPENDED Position */
-#define SCB_SHCSR_SVCALLPENDED_Msk         (1UL << SCB_SHCSR_SVCALLPENDED_Pos)            /*!< SCB SHCSR: SVCALLPENDED Mask */
-
-#define SCB_SHCSR_BUSFAULTPENDED_Pos       14                                             /*!< SCB SHCSR: BUSFAULTPENDED Position */
-#define SCB_SHCSR_BUSFAULTPENDED_Msk       (1UL << SCB_SHCSR_BUSFAULTPENDED_Pos)          /*!< SCB SHCSR: BUSFAULTPENDED Mask */
-
-#define SCB_SHCSR_MEMFAULTPENDED_Pos       13                                             /*!< SCB SHCSR: MEMFAULTPENDED Position */
-#define SCB_SHCSR_MEMFAULTPENDED_Msk       (1UL << SCB_SHCSR_MEMFAULTPENDED_Pos)          /*!< SCB SHCSR: MEMFAULTPENDED Mask */
-
-#define SCB_SHCSR_USGFAULTPENDED_Pos       12                                             /*!< SCB SHCSR: USGFAULTPENDED Position */
-#define SCB_SHCSR_USGFAULTPENDED_Msk       (1UL << SCB_SHCSR_USGFAULTPENDED_Pos)          /*!< SCB SHCSR: USGFAULTPENDED Mask */
-
-#define SCB_SHCSR_SYSTICKACT_Pos           11                                             /*!< SCB SHCSR: SYSTICKACT Position */
-#define SCB_SHCSR_SYSTICKACT_Msk           (1UL << SCB_SHCSR_SYSTICKACT_Pos)              /*!< SCB SHCSR: SYSTICKACT Mask */
-
-#define SCB_SHCSR_PENDSVACT_Pos            10                                             /*!< SCB SHCSR: PENDSVACT Position */
-#define SCB_SHCSR_PENDSVACT_Msk            (1UL << SCB_SHCSR_PENDSVACT_Pos)               /*!< SCB SHCSR: PENDSVACT Mask */
-
-#define SCB_SHCSR_MONITORACT_Pos            8                                             /*!< SCB SHCSR: MONITORACT Position */
-#define SCB_SHCSR_MONITORACT_Msk           (1UL << SCB_SHCSR_MONITORACT_Pos)              /*!< SCB SHCSR: MONITORACT Mask */
-
-#define SCB_SHCSR_SVCALLACT_Pos             7                                             /*!< SCB SHCSR: SVCALLACT Position */
-#define SCB_SHCSR_SVCALLACT_Msk            (1UL << SCB_SHCSR_SVCALLACT_Pos)               /*!< SCB SHCSR: SVCALLACT Mask */
-
-#define SCB_SHCSR_USGFAULTACT_Pos           3                                             /*!< SCB SHCSR: USGFAULTACT Position */
-#define SCB_SHCSR_USGFAULTACT_Msk          (1UL << SCB_SHCSR_USGFAULTACT_Pos)             /*!< SCB SHCSR: USGFAULTACT Mask */
-
-#define SCB_SHCSR_BUSFAULTACT_Pos           1                                             /*!< SCB SHCSR: BUSFAULTACT Position */
-#define SCB_SHCSR_BUSFAULTACT_Msk          (1UL << SCB_SHCSR_BUSFAULTACT_Pos)             /*!< SCB SHCSR: BUSFAULTACT Mask */
-
-#define SCB_SHCSR_MEMFAULTACT_Pos           0                                             /*!< SCB SHCSR: MEMFAULTACT Position */
-#define SCB_SHCSR_MEMFAULTACT_Msk          (1UL << SCB_SHCSR_MEMFAULTACT_Pos)             /*!< SCB SHCSR: MEMFAULTACT Mask */
-
-/* SCB Configurable Fault Status Registers Definitions */
-#define SCB_CFSR_USGFAULTSR_Pos            16                                             /*!< SCB CFSR: Usage Fault Status Register Position */
-#define SCB_CFSR_USGFAULTSR_Msk            (0xFFFFUL << SCB_CFSR_USGFAULTSR_Pos)          /*!< SCB CFSR: Usage Fault Status Register Mask */
-
-#define SCB_CFSR_BUSFAULTSR_Pos             8                                             /*!< SCB CFSR: Bus Fault Status Register Position */
-#define SCB_CFSR_BUSFAULTSR_Msk            (0xFFUL << SCB_CFSR_BUSFAULTSR_Pos)            /*!< SCB CFSR: Bus Fault Status Register Mask */
-
-#define SCB_CFSR_MEMFAULTSR_Pos             0                                             /*!< SCB CFSR: Memory Manage Fault Status Register Position */
-#define SCB_CFSR_MEMFAULTSR_Msk            (0xFFUL << SCB_CFSR_MEMFAULTSR_Pos)            /*!< SCB CFSR: Memory Manage Fault Status Register Mask */
-
-/* SCB Hard Fault Status Registers Definitions */
-#define SCB_HFSR_DEBUGEVT_Pos              31                                             /*!< SCB HFSR: DEBUGEVT Position */
-#define SCB_HFSR_DEBUGEVT_Msk              (1UL << SCB_HFSR_DEBUGEVT_Pos)                 /*!< SCB HFSR: DEBUGEVT Mask */
-
-#define SCB_HFSR_FORCED_Pos                30                                             /*!< SCB HFSR: FORCED Position */
-#define SCB_HFSR_FORCED_Msk                (1UL << SCB_HFSR_FORCED_Pos)                   /*!< SCB HFSR: FORCED Mask */
-
-#define SCB_HFSR_VECTTBL_Pos                1                                             /*!< SCB HFSR: VECTTBL Position */
-#define SCB_HFSR_VECTTBL_Msk               (1UL << SCB_HFSR_VECTTBL_Pos)                  /*!< SCB HFSR: VECTTBL Mask */
-
-/* SCB Debug Fault Status Register Definitions */
-#define SCB_DFSR_EXTERNAL_Pos               4                                             /*!< SCB DFSR: EXTERNAL Position */
-#define SCB_DFSR_EXTERNAL_Msk              (1UL << SCB_DFSR_EXTERNAL_Pos)                 /*!< SCB DFSR: EXTERNAL Mask */
-
-#define SCB_DFSR_VCATCH_Pos                 3                                             /*!< SCB DFSR: VCATCH Position */
-#define SCB_DFSR_VCATCH_Msk                (1UL << SCB_DFSR_VCATCH_Pos)                   /*!< SCB DFSR: VCATCH Mask */
-
-#define SCB_DFSR_DWTTRAP_Pos                2                                             /*!< SCB DFSR: DWTTRAP Position */
-#define SCB_DFSR_DWTTRAP_Msk               (1UL << SCB_DFSR_DWTTRAP_Pos)                  /*!< SCB DFSR: DWTTRAP Mask */
-
-#define SCB_DFSR_BKPT_Pos                   1                                             /*!< SCB DFSR: BKPT Position */
-#define SCB_DFSR_BKPT_Msk                  (1UL << SCB_DFSR_BKPT_Pos)                     /*!< SCB DFSR: BKPT Mask */
-
-#define SCB_DFSR_HALTED_Pos                 0                                             /*!< SCB DFSR: HALTED Position */
-#define SCB_DFSR_HALTED_Msk                (1UL << SCB_DFSR_HALTED_Pos)                   /*!< SCB DFSR: HALTED Mask */
-
-/*@} end of group CMSIS_SCB */
-
-
-/** \ingroup  CMSIS_core_register
-    \defgroup CMSIS_SCnSCB System Controls not in SCB (SCnSCB)
-    \brief      Type definitions for the System Control and ID Register not in the SCB
-  @{
- */
-
-/** \brief  Structure type to access the System Control and ID Register not in the SCB.
- */
-typedef struct
-{
-       uint32_t RESERVED0[1];
-  __I  uint32_t ICTR;                    /*!< Offset: 0x004 (R/ )  Interrupt Controller Type Register      */
-#if ((defined __CM3_REV) && (__CM3_REV >= 0x200))
-  __IO uint32_t ACTLR;                   /*!< Offset: 0x008 (R/W)  Auxiliary Control Register      */
-#else
-       uint32_t RESERVED1[1];
-#endif
-} SCnSCB_Type;
-
-/* Interrupt Controller Type Register Definitions */
-#define SCnSCB_ICTR_INTLINESNUM_Pos         0                                          /*!< ICTR: INTLINESNUM Position */
-#define SCnSCB_ICTR_INTLINESNUM_Msk        (0xFUL << SCnSCB_ICTR_INTLINESNUM_Pos)      /*!< ICTR: INTLINESNUM Mask */
-
-/* Auxiliary Control Register Definitions */
-
-#define SCnSCB_ACTLR_DISFOLD_Pos            2                                          /*!< ACTLR: DISFOLD Position */
-#define SCnSCB_ACTLR_DISFOLD_Msk           (1UL << SCnSCB_ACTLR_DISFOLD_Pos)           /*!< ACTLR: DISFOLD Mask */
-
-#define SCnSCB_ACTLR_DISDEFWBUF_Pos         1                                          /*!< ACTLR: DISDEFWBUF Position */
-#define SCnSCB_ACTLR_DISDEFWBUF_Msk        (1UL << SCnSCB_ACTLR_DISDEFWBUF_Pos)        /*!< ACTLR: DISDEFWBUF Mask */
-
-#define SCnSCB_ACTLR_DISMCYCINT_Pos         0                                          /*!< ACTLR: DISMCYCINT Position */
-#define SCnSCB_ACTLR_DISMCYCINT_Msk        (1UL << SCnSCB_ACTLR_DISMCYCINT_Pos)        /*!< ACTLR: DISMCYCINT Mask */
-
-/*@} end of group CMSIS_SCnotSCB */
-
-
-/** \ingroup  CMSIS_core_register
-    \defgroup CMSIS_SysTick     System Tick Timer (SysTick)
-    \brief      Type definitions for the System Timer Registers.
-  @{
- */
-
-/** \brief  Structure type to access the System Timer (SysTick).
- */
-typedef struct
-{
-  __IO uint32_t CTRL;                    /*!< Offset: 0x000 (R/W)  SysTick Control and Status Register */
-  __IO uint32_t LOAD;                    /*!< Offset: 0x004 (R/W)  SysTick Reload Value Register       */
-  __IO uint32_t VAL;                     /*!< Offset: 0x008 (R/W)  SysTick Current Value Register      */
-  __I  uint32_t CALIB;                   /*!< Offset: 0x00C (R/ )  SysTick Calibration Register        */
-} SysTick_Type;
-
-/* SysTick Control / Status Register Definitions */
-#define SysTick_CTRL_COUNTFLAG_Pos         16                                             /*!< SysTick CTRL: COUNTFLAG Position */
-#define SysTick_CTRL_COUNTFLAG_Msk         (1UL << SysTick_CTRL_COUNTFLAG_Pos)            /*!< SysTick CTRL: COUNTFLAG Mask */
-
-#define SysTick_CTRL_CLKSOURCE_Pos          2                                             /*!< SysTick CTRL: CLKSOURCE Position */
-#define SysTick_CTRL_CLKSOURCE_Msk         (1UL << SysTick_CTRL_CLKSOURCE_Pos)            /*!< SysTick CTRL: CLKSOURCE Mask */
-
-#define SysTick_CTRL_TICKINT_Pos            1                                             /*!< SysTick CTRL: TICKINT Position */
-#define SysTick_CTRL_TICKINT_Msk           (1UL << SysTick_CTRL_TICKINT_Pos)              /*!< SysTick CTRL: TICKINT Mask */
-
-#define SysTick_CTRL_ENABLE_Pos             0                                             /*!< SysTick CTRL: ENABLE Position */
-#define SysTick_CTRL_ENABLE_Msk            (1UL << SysTick_CTRL_ENABLE_Pos)               /*!< SysTick CTRL: ENABLE Mask */
-
-/* SysTick Reload Register Definitions */
-#define SysTick_LOAD_RELOAD_Pos             0                                             /*!< SysTick LOAD: RELOAD Position */
-#define SysTick_LOAD_RELOAD_Msk            (0xFFFFFFUL << SysTick_LOAD_RELOAD_Pos)        /*!< SysTick LOAD: RELOAD Mask */
-
-/* SysTick Current Register Definitions */
-#define SysTick_VAL_CURRENT_Pos             0                                             /*!< SysTick VAL: CURRENT Position */
-#define SysTick_VAL_CURRENT_Msk            (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos)        /*!< SysTick VAL: CURRENT Mask */
-
-/* SysTick Calibration Register Definitions */
-#define SysTick_CALIB_NOREF_Pos            31                                             /*!< SysTick CALIB: NOREF Position */
-#define SysTick_CALIB_NOREF_Msk            (1UL << SysTick_CALIB_NOREF_Pos)               /*!< SysTick CALIB: NOREF Mask */
-
-#define SysTick_CALIB_SKEW_Pos             30                                             /*!< SysTick CALIB: SKEW Position */
-#define SysTick_CALIB_SKEW_Msk             (1UL << SysTick_CALIB_SKEW_Pos)                /*!< SysTick CALIB: SKEW Mask */
-
-#define SysTick_CALIB_TENMS_Pos             0                                             /*!< SysTick CALIB: TENMS Position */
-#define SysTick_CALIB_TENMS_Msk            (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos)        /*!< SysTick CALIB: TENMS Mask */
-
-/*@} end of group CMSIS_SysTick */
-
-
-/** \ingroup  CMSIS_core_register
-    \defgroup CMSIS_ITM     Instrumentation Trace Macrocell (ITM)
-    \brief      Type definitions for the Instrumentation Trace Macrocell (ITM)
-  @{
- */
-
-/** \brief  Structure type to access the Instrumentation Trace Macrocell Register (ITM).
- */
-typedef struct
-{
-  __O  union
-  {
-    __O  uint8_t    u8;                  /*!< Offset: 0x000 ( /W)  ITM Stimulus Port 8-bit                   */
-    __O  uint16_t   u16;                 /*!< Offset: 0x000 ( /W)  ITM Stimulus Port 16-bit                  */
-    __O  uint32_t   u32;                 /*!< Offset: 0x000 ( /W)  ITM Stimulus Port 32-bit                  */
-  }  PORT [32];                          /*!< Offset: 0x000 ( /W)  ITM Stimulus Port Registers               */
-       uint32_t RESERVED0[864];
-  __IO uint32_t TER;                     /*!< Offset: 0xE00 (R/W)  ITM Trace Enable Register                 */
-       uint32_t RESERVED1[15];
-  __IO uint32_t TPR;                     /*!< Offset: 0xE40 (R/W)  ITM Trace Privilege Register              */
-       uint32_t RESERVED2[15];
-  __IO uint32_t TCR;                     /*!< Offset: 0xE80 (R/W)  ITM Trace Control Register                */
-       uint32_t RESERVED3[29];
-  __O  uint32_t IWR;                     /*!< Offset: 0xEF8 ( /W)  ITM Integration Write Register            */
-  __I  uint32_t IRR;                     /*!< Offset: 0xEFC (R/ )  ITM Integration Read Register             */
-  __IO uint32_t IMCR;                    /*!< Offset: 0xF00 (R/W)  ITM Integration Mode Control Register     */
-       uint32_t RESERVED4[43];
-  __O  uint32_t LAR;                     /*!< Offset: 0xFB0 ( /W)  ITM Lock Access Register                  */
-  __I  uint32_t LSR;                     /*!< Offset: 0xFB4 (R/ )  ITM Lock Status Register                  */
-       uint32_t RESERVED5[6];
-  __I  uint32_t PID4;                    /*!< Offset: 0xFD0 (R/ )  ITM Peripheral Identification Register #4 */
-  __I  uint32_t PID5;                    /*!< Offset: 0xFD4 (R/ )  ITM Peripheral Identification Register #5 */
-  __I  uint32_t PID6;                    /*!< Offset: 0xFD8 (R/ )  ITM Peripheral Identification Register #6 */
-  __I  uint32_t PID7;                    /*!< Offset: 0xFDC (R/ )  ITM Peripheral Identification Register #7 */
-  __I  uint32_t PID0;                    /*!< Offset: 0xFE0 (R/ )  ITM Peripheral Identification Register #0 */
-  __I  uint32_t PID1;                    /*!< Offset: 0xFE4 (R/ )  ITM Peripheral Identification Register #1 */
-  __I  uint32_t PID2;                    /*!< Offset: 0xFE8 (R/ )  ITM Peripheral Identification Register #2 */
-  __I  uint32_t PID3;                    /*!< Offset: 0xFEC (R/ )  ITM Peripheral Identification Register #3 */
-  __I  uint32_t CID0;                    /*!< Offset: 0xFF0 (R/ )  ITM Component  Identification Register #0 */
-  __I  uint32_t CID1;                    /*!< Offset: 0xFF4 (R/ )  ITM Component  Identification Register #1 */
-  __I  uint32_t CID2;                    /*!< Offset: 0xFF8 (R/ )  ITM Component  Identification Register #2 */
-  __I  uint32_t CID3;                    /*!< Offset: 0xFFC (R/ )  ITM Component  Identification Register #3 */
-} ITM_Type;
-
-/* ITM Trace Privilege Register Definitions */
-#define ITM_TPR_PRIVMASK_Pos                0                                             /*!< ITM TPR: PRIVMASK Position */
-#define ITM_TPR_PRIVMASK_Msk               (0xFUL << ITM_TPR_PRIVMASK_Pos)                /*!< ITM TPR: PRIVMASK Mask */
-
-/* ITM Trace Control Register Definitions */
-#define ITM_TCR_BUSY_Pos                   23                                             /*!< ITM TCR: BUSY Position */
-#define ITM_TCR_BUSY_Msk                   (1UL << ITM_TCR_BUSY_Pos)                      /*!< ITM TCR: BUSY Mask */
-
-#define ITM_TCR_TraceBusID_Pos             16                                             /*!< ITM TCR: ATBID Position */
-#define ITM_TCR_TraceBusID_Msk             (0x7FUL << ITM_TCR_TraceBusID_Pos)             /*!< ITM TCR: ATBID Mask */
-
-#define ITM_TCR_GTSFREQ_Pos                10                                             /*!< ITM TCR: Global timestamp frequency Position */
-#define ITM_TCR_GTSFREQ_Msk                (3UL << ITM_TCR_GTSFREQ_Pos)                   /*!< ITM TCR: Global timestamp frequency Mask */
-
-#define ITM_TCR_TSPrescale_Pos              8                                             /*!< ITM TCR: TSPrescale Position */
-#define ITM_TCR_TSPrescale_Msk             (3UL << ITM_TCR_TSPrescale_Pos)                /*!< ITM TCR: TSPrescale Mask */
-
-#define ITM_TCR_SWOENA_Pos                  4                                             /*!< ITM TCR: SWOENA Position */
-#define ITM_TCR_SWOENA_Msk                 (1UL << ITM_TCR_SWOENA_Pos)                    /*!< ITM TCR: SWOENA Mask */
-
-#define ITM_TCR_DWTENA_Pos                  3                                             /*!< ITM TCR: DWTENA Position */
-#define ITM_TCR_DWTENA_Msk                 (1UL << ITM_TCR_DWTENA_Pos)                    /*!< ITM TCR: DWTENA Mask */
-
-#define ITM_TCR_SYNCENA_Pos                 2                                             /*!< ITM TCR: SYNCENA Position */
-#define ITM_TCR_SYNCENA_Msk                (1UL << ITM_TCR_SYNCENA_Pos)                   /*!< ITM TCR: SYNCENA Mask */
-
-#define ITM_TCR_TSENA_Pos                   1                                             /*!< ITM TCR: TSENA Position */
-#define ITM_TCR_TSENA_Msk                  (1UL << ITM_TCR_TSENA_Pos)                     /*!< ITM TCR: TSENA Mask */
-
-#define ITM_TCR_ITMENA_Pos                  0                                             /*!< ITM TCR: ITM Enable bit Position */
-#define ITM_TCR_ITMENA_Msk                 (1UL << ITM_TCR_ITMENA_Pos)                    /*!< ITM TCR: ITM Enable bit Mask */
-
-/* ITM Integration Write Register Definitions */
-#define ITM_IWR_ATVALIDM_Pos                0                                             /*!< ITM IWR: ATVALIDM Position */
-#define ITM_IWR_ATVALIDM_Msk               (1UL << ITM_IWR_ATVALIDM_Pos)                  /*!< ITM IWR: ATVALIDM Mask */
-
-/* ITM Integration Read Register Definitions */
-#define ITM_IRR_ATREADYM_Pos                0                                             /*!< ITM IRR: ATREADYM Position */
-#define ITM_IRR_ATREADYM_Msk               (1UL << ITM_IRR_ATREADYM_Pos)                  /*!< ITM IRR: ATREADYM Mask */
-
-/* ITM Integration Mode Control Register Definitions */
-#define ITM_IMCR_INTEGRATION_Pos            0                                             /*!< ITM IMCR: INTEGRATION Position */
-#define ITM_IMCR_INTEGRATION_Msk           (1UL << ITM_IMCR_INTEGRATION_Pos)              /*!< ITM IMCR: INTEGRATION Mask */
-
-/* ITM Lock Status Register Definitions */
-#define ITM_LSR_ByteAcc_Pos                 2                                             /*!< ITM LSR: ByteAcc Position */
-#define ITM_LSR_ByteAcc_Msk                (1UL << ITM_LSR_ByteAcc_Pos)                   /*!< ITM LSR: ByteAcc Mask */
-
-#define ITM_LSR_Access_Pos                  1                                             /*!< ITM LSR: Access Position */
-#define ITM_LSR_Access_Msk                 (1UL << ITM_LSR_Access_Pos)                    /*!< ITM LSR: Access Mask */
-
-#define ITM_LSR_Present_Pos                 0                                             /*!< ITM LSR: Present Position */
-#define ITM_LSR_Present_Msk                (1UL << ITM_LSR_Present_Pos)                   /*!< ITM LSR: Present Mask */
-
-/*@}*/ /* end of group CMSIS_ITM */
-
-
-/** \ingroup  CMSIS_core_register
-    \defgroup CMSIS_DWT     Data Watchpoint and Trace (DWT)
-    \brief      Type definitions for the Data Watchpoint and Trace (DWT)
-  @{
- */
-
-/** \brief  Structure type to access the Data Watchpoint and Trace Register (DWT).
- */
-typedef struct
-{
-  __IO uint32_t CTRL;                    /*!< Offset: 0x000 (R/W)  Control Register                          */
-  __IO uint32_t CYCCNT;                  /*!< Offset: 0x004 (R/W)  Cycle Count Register                      */
-  __IO uint32_t CPICNT;                  /*!< Offset: 0x008 (R/W)  CPI Count Register                        */
-  __IO uint32_t EXCCNT;                  /*!< Offset: 0x00C (R/W)  Exception Overhead Count Register         */
-  __IO uint32_t SLEEPCNT;                /*!< Offset: 0x010 (R/W)  Sleep Count Register                      */
-  __IO uint32_t LSUCNT;                  /*!< Offset: 0x014 (R/W)  LSU Count Register                        */
-  __IO uint32_t FOLDCNT;                 /*!< Offset: 0x018 (R/W)  Folded-instruction Count Register         */
-  __I  uint32_t PCSR;                    /*!< Offset: 0x01C (R/ )  Program Counter Sample Register           */
-  __IO uint32_t COMP0;                   /*!< Offset: 0x020 (R/W)  Comparator Register 0                     */
-  __IO uint32_t MASK0;                   /*!< Offset: 0x024 (R/W)  Mask Register 0                           */
-  __IO uint32_t FUNCTION0;               /*!< Offset: 0x028 (R/W)  Function Register 0                       */
-       uint32_t RESERVED0[1];
-  __IO uint32_t COMP1;                   /*!< Offset: 0x030 (R/W)  Comparator Register 1                     */
-  __IO uint32_t MASK1;                   /*!< Offset: 0x034 (R/W)  Mask Register 1                           */
-  __IO uint32_t FUNCTION1;               /*!< Offset: 0x038 (R/W)  Function Register 1                       */
-       uint32_t RESERVED1[1];
-  __IO uint32_t COMP2;                   /*!< Offset: 0x040 (R/W)  Comparator Register 2                     */
-  __IO uint32_t MASK2;                   /*!< Offset: 0x044 (R/W)  Mask Register 2                           */
-  __IO uint32_t FUNCTION2;               /*!< Offset: 0x048 (R/W)  Function Register 2                       */
-       uint32_t RESERVED2[1];
-  __IO uint32_t COMP3;                   /*!< Offset: 0x050 (R/W)  Comparator Register 3                     */
-  __IO uint32_t MASK3;                   /*!< Offset: 0x054 (R/W)  Mask Register 3                           */
-  __IO uint32_t FUNCTION3;               /*!< Offset: 0x058 (R/W)  Function Register 3                       */
-} DWT_Type;
-
-/* DWT Control Register Definitions */
-#define DWT_CTRL_NUMCOMP_Pos               28                                          /*!< DWT CTRL: NUMCOMP Position */
-#define DWT_CTRL_NUMCOMP_Msk               (0xFUL << DWT_CTRL_NUMCOMP_Pos)             /*!< DWT CTRL: NUMCOMP Mask */
-
-#define DWT_CTRL_NOTRCPKT_Pos              27                                          /*!< DWT CTRL: NOTRCPKT Position */
-#define DWT_CTRL_NOTRCPKT_Msk              (0x1UL << DWT_CTRL_NOTRCPKT_Pos)            /*!< DWT CTRL: NOTRCPKT Mask */
-
-#define DWT_CTRL_NOEXTTRIG_Pos             26                                          /*!< DWT CTRL: NOEXTTRIG Position */
-#define DWT_CTRL_NOEXTTRIG_Msk             (0x1UL << DWT_CTRL_NOEXTTRIG_Pos)           /*!< DWT CTRL: NOEXTTRIG Mask */
-
-#define DWT_CTRL_NOCYCCNT_Pos              25                                          /*!< DWT CTRL: NOCYCCNT Position */
-#define DWT_CTRL_NOCYCCNT_Msk              (0x1UL << DWT_CTRL_NOCYCCNT_Pos)            /*!< DWT CTRL: NOCYCCNT Mask */
-
-#define DWT_CTRL_NOPRFCNT_Pos              24                                          /*!< DWT CTRL: NOPRFCNT Position */
-#define DWT_CTRL_NOPRFCNT_Msk              (0x1UL << DWT_CTRL_NOPRFCNT_Pos)            /*!< DWT CTRL: NOPRFCNT Mask */
-
-#define DWT_CTRL_CYCEVTENA_Pos             22                                          /*!< DWT CTRL: CYCEVTENA Position */
-#define DWT_CTRL_CYCEVTENA_Msk             (0x1UL << DWT_CTRL_CYCEVTENA_Pos)           /*!< DWT CTRL: CYCEVTENA Mask */
-
-#define DWT_CTRL_FOLDEVTENA_Pos            21                                          /*!< DWT CTRL: FOLDEVTENA Position */
-#define DWT_CTRL_FOLDEVTENA_Msk            (0x1UL << DWT_CTRL_FOLDEVTENA_Pos)          /*!< DWT CTRL: FOLDEVTENA Mask */
-
-#define DWT_CTRL_LSUEVTENA_Pos             20                                          /*!< DWT CTRL: LSUEVTENA Position */
-#define DWT_CTRL_LSUEVTENA_Msk             (0x1UL << DWT_CTRL_LSUEVTENA_Pos)           /*!< DWT CTRL: LSUEVTENA Mask */
-
-#define DWT_CTRL_SLEEPEVTENA_Pos           19                                          /*!< DWT CTRL: SLEEPEVTENA Position */
-#define DWT_CTRL_SLEEPEVTENA_Msk           (0x1UL << DWT_CTRL_SLEEPEVTENA_Pos)         /*!< DWT CTRL: SLEEPEVTENA Mask */
-
-#define DWT_CTRL_EXCEVTENA_Pos             18                                          /*!< DWT CTRL: EXCEVTENA Position */
-#define DWT_CTRL_EXCEVTENA_Msk             (0x1UL << DWT_CTRL_EXCEVTENA_Pos)           /*!< DWT CTRL: EXCEVTENA Mask */
-
-#define DWT_CTRL_CPIEVTENA_Pos             17                                          /*!< DWT CTRL: CPIEVTENA Position */
-#define DWT_CTRL_CPIEVTENA_Msk             (0x1UL << DWT_CTRL_CPIEVTENA_Pos)           /*!< DWT CTRL: CPIEVTENA Mask */
-
-#define DWT_CTRL_EXCTRCENA_Pos             16                                          /*!< DWT CTRL: EXCTRCENA Position */
-#define DWT_CTRL_EXCTRCENA_Msk             (0x1UL << DWT_CTRL_EXCTRCENA_Pos)           /*!< DWT CTRL: EXCTRCENA Mask */
-
-#define DWT_CTRL_PCSAMPLENA_Pos            12                                          /*!< DWT CTRL: PCSAMPLENA Position */
-#define DWT_CTRL_PCSAMPLENA_Msk            (0x1UL << DWT_CTRL_PCSAMPLENA_Pos)          /*!< DWT CTRL: PCSAMPLENA Mask */
-
-#define DWT_CTRL_SYNCTAP_Pos               10                                          /*!< DWT CTRL: SYNCTAP Position */
-#define DWT_CTRL_SYNCTAP_Msk               (0x3UL << DWT_CTRL_SYNCTAP_Pos)             /*!< DWT CTRL: SYNCTAP Mask */
-
-#define DWT_CTRL_CYCTAP_Pos                 9                                          /*!< DWT CTRL: CYCTAP Position */
-#define DWT_CTRL_CYCTAP_Msk                (0x1UL << DWT_CTRL_CYCTAP_Pos)              /*!< DWT CTRL: CYCTAP Mask */
-
-#define DWT_CTRL_POSTINIT_Pos               5                                          /*!< DWT CTRL: POSTINIT Position */
-#define DWT_CTRL_POSTINIT_Msk              (0xFUL << DWT_CTRL_POSTINIT_Pos)            /*!< DWT CTRL: POSTINIT Mask */
-
-#define DWT_CTRL_POSTPRESET_Pos             1                                          /*!< DWT CTRL: POSTPRESET Position */
-#define DWT_CTRL_POSTPRESET_Msk            (0xFUL << DWT_CTRL_POSTPRESET_Pos)          /*!< DWT CTRL: POSTPRESET Mask */
-
-#define DWT_CTRL_CYCCNTENA_Pos              0                                          /*!< DWT CTRL: CYCCNTENA Position */
-#define DWT_CTRL_CYCCNTENA_Msk             (0x1UL << DWT_CTRL_CYCCNTENA_Pos)           /*!< DWT CTRL: CYCCNTENA Mask */
-
-/* DWT CPI Count Register Definitions */
-#define DWT_CPICNT_CPICNT_Pos               0                                          /*!< DWT CPICNT: CPICNT Position */
-#define DWT_CPICNT_CPICNT_Msk              (0xFFUL << DWT_CPICNT_CPICNT_Pos)           /*!< DWT CPICNT: CPICNT Mask */
-
-/* DWT Exception Overhead Count Register Definitions */
-#define DWT_EXCCNT_EXCCNT_Pos               0                                          /*!< DWT EXCCNT: EXCCNT Position */
-#define DWT_EXCCNT_EXCCNT_Msk              (0xFFUL << DWT_EXCCNT_EXCCNT_Pos)           /*!< DWT EXCCNT: EXCCNT Mask */
-
-/* DWT Sleep Count Register Definitions */
-#define DWT_SLEEPCNT_SLEEPCNT_Pos           0                                          /*!< DWT SLEEPCNT: SLEEPCNT Position */
-#define DWT_SLEEPCNT_SLEEPCNT_Msk          (0xFFUL << DWT_SLEEPCNT_SLEEPCNT_Pos)       /*!< DWT SLEEPCNT: SLEEPCNT Mask */
-
-/* DWT LSU Count Register Definitions */
-#define DWT_LSUCNT_LSUCNT_Pos               0                                          /*!< DWT LSUCNT: LSUCNT Position */
-#define DWT_LSUCNT_LSUCNT_Msk              (0xFFUL << DWT_LSUCNT_LSUCNT_Pos)           /*!< DWT LSUCNT: LSUCNT Mask */
-
-/* DWT Folded-instruction Count Register Definitions */
-#define DWT_FOLDCNT_FOLDCNT_Pos             0                                          /*!< DWT FOLDCNT: FOLDCNT Position */
-#define DWT_FOLDCNT_FOLDCNT_Msk            (0xFFUL << DWT_FOLDCNT_FOLDCNT_Pos)         /*!< DWT FOLDCNT: FOLDCNT Mask */
-
-/* DWT Comparator Mask Register Definitions */
-#define DWT_MASK_MASK_Pos                   0                                          /*!< DWT MASK: MASK Position */
-#define DWT_MASK_MASK_Msk                  (0x1FUL << DWT_MASK_MASK_Pos)               /*!< DWT MASK: MASK Mask */
-
-/* DWT Comparator Function Register Definitions */
-#define DWT_FUNCTION_MATCHED_Pos           24                                          /*!< DWT FUNCTION: MATCHED Position */
-#define DWT_FUNCTION_MATCHED_Msk           (0x1UL << DWT_FUNCTION_MATCHED_Pos)         /*!< DWT FUNCTION: MATCHED Mask */
-
-#define DWT_FUNCTION_DATAVADDR1_Pos        16                                          /*!< DWT FUNCTION: DATAVADDR1 Position */
-#define DWT_FUNCTION_DATAVADDR1_Msk        (0xFUL << DWT_FUNCTION_DATAVADDR1_Pos)      /*!< DWT FUNCTION: DATAVADDR1 Mask */
-
-#define DWT_FUNCTION_DATAVADDR0_Pos        12                                          /*!< DWT FUNCTION: DATAVADDR0 Position */
-#define DWT_FUNCTION_DATAVADDR0_Msk        (0xFUL << DWT_FUNCTION_DATAVADDR0_Pos)      /*!< DWT FUNCTION: DATAVADDR0 Mask */
-
-#define DWT_FUNCTION_DATAVSIZE_Pos         10                                          /*!< DWT FUNCTION: DATAVSIZE Position */
-#define DWT_FUNCTION_DATAVSIZE_Msk         (0x3UL << DWT_FUNCTION_DATAVSIZE_Pos)       /*!< DWT FUNCTION: DATAVSIZE Mask */
-
-#define DWT_FUNCTION_LNK1ENA_Pos            9                                          /*!< DWT FUNCTION: LNK1ENA Position */
-#define DWT_FUNCTION_LNK1ENA_Msk           (0x1UL << DWT_FUNCTION_LNK1ENA_Pos)         /*!< DWT FUNCTION: LNK1ENA Mask */
-
-#define DWT_FUNCTION_DATAVMATCH_Pos         8                                          /*!< DWT FUNCTION: DATAVMATCH Position */
-#define DWT_FUNCTION_DATAVMATCH_Msk        (0x1UL << DWT_FUNCTION_DATAVMATCH_Pos)      /*!< DWT FUNCTION: DATAVMATCH Mask */
-
-#define DWT_FUNCTION_CYCMATCH_Pos           7                                          /*!< DWT FUNCTION: CYCMATCH Position */
-#define DWT_FUNCTION_CYCMATCH_Msk          (0x1UL << DWT_FUNCTION_CYCMATCH_Pos)        /*!< DWT FUNCTION: CYCMATCH Mask */
-
-#define DWT_FUNCTION_EMITRANGE_Pos          5                                          /*!< DWT FUNCTION: EMITRANGE Position */
-#define DWT_FUNCTION_EMITRANGE_Msk         (0x1UL << DWT_FUNCTION_EMITRANGE_Pos)       /*!< DWT FUNCTION: EMITRANGE Mask */
-
-#define DWT_FUNCTION_FUNCTION_Pos           0                                          /*!< DWT FUNCTION: FUNCTION Position */
-#define DWT_FUNCTION_FUNCTION_Msk          (0xFUL << DWT_FUNCTION_FUNCTION_Pos)        /*!< DWT FUNCTION: FUNCTION Mask */
-
-/*@}*/ /* end of group CMSIS_DWT */
-
-
-/** \ingroup  CMSIS_core_register
-    \defgroup CMSIS_TPI     Trace Port Interface (TPI)
-    \brief      Type definitions for the Trace Port Interface (TPI)
-  @{
- */
-
-/** \brief  Structure type to access the Trace Port Interface Register (TPI).
- */
-typedef struct
-{
-  __IO uint32_t SSPSR;                   /*!< Offset: 0x000 (R/ )  Supported Parallel Port Size Register     */
-  __IO uint32_t CSPSR;                   /*!< Offset: 0x004 (R/W)  Current Parallel Port Size Register */
-       uint32_t RESERVED0[2];
-  __IO uint32_t ACPR;                    /*!< Offset: 0x010 (R/W)  Asynchronous Clock Prescaler Register */
-       uint32_t RESERVED1[55];
-  __IO uint32_t SPPR;                    /*!< Offset: 0x0F0 (R/W)  Selected Pin Protocol Register */
-       uint32_t RESERVED2[131];
-  __I  uint32_t FFSR;                    /*!< Offset: 0x300 (R/ )  Formatter and Flush Status Register */
-  __IO uint32_t FFCR;                    /*!< Offset: 0x304 (R/W)  Formatter and Flush Control Register */
-  __I  uint32_t FSCR;                    /*!< Offset: 0x308 (R/ )  Formatter Synchronization Counter Register */
-       uint32_t RESERVED3[759];
-  __I  uint32_t TRIGGER;                 /*!< Offset: 0xEE8 (R/ )  TRIGGER */
-  __I  uint32_t FIFO0;                   /*!< Offset: 0xEEC (R/ )  Integration ETM Data */
-  __I  uint32_t ITATBCTR2;               /*!< Offset: 0xEF0 (R/ )  ITATBCTR2 */
-       uint32_t RESERVED4[1];
-  __I  uint32_t ITATBCTR0;               /*!< Offset: 0xEF8 (R/ )  ITATBCTR0 */
-  __I  uint32_t FIFO1;                   /*!< Offset: 0xEFC (R/ )  Integration ITM Data */
-  __IO uint32_t ITCTRL;                  /*!< Offset: 0xF00 (R/W)  Integration Mode Control */
-       uint32_t RESERVED5[39];
-  __IO uint32_t CLAIMSET;                /*!< Offset: 0xFA0 (R/W)  Claim tag set */
-  __IO uint32_t CLAIMCLR;                /*!< Offset: 0xFA4 (R/W)  Claim tag clear */
-       uint32_t RESERVED7[8];
-  __I  uint32_t DEVID;                   /*!< Offset: 0xFC8 (R/ )  TPIU_DEVID */
-  __I  uint32_t DEVTYPE;                 /*!< Offset: 0xFCC (R/ )  TPIU_DEVTYPE */
-} TPI_Type;
-
-/* TPI Asynchronous Clock Prescaler Register Definitions */
-#define TPI_ACPR_PRESCALER_Pos              0                                          /*!< TPI ACPR: PRESCALER Position */
-#define TPI_ACPR_PRESCALER_Msk             (0x1FFFUL << TPI_ACPR_PRESCALER_Pos)        /*!< TPI ACPR: PRESCALER Mask */
-
-/* TPI Selected Pin Protocol Register Definitions */
-#define TPI_SPPR_TXMODE_Pos                 0                                          /*!< TPI SPPR: TXMODE Position */
-#define TPI_SPPR_TXMODE_Msk                (0x3UL << TPI_SPPR_TXMODE_Pos)              /*!< TPI SPPR: TXMODE Mask */
-
-/* TPI Formatter and Flush Status Register Definitions */
-#define TPI_FFSR_FtNonStop_Pos              3                                          /*!< TPI FFSR: FtNonStop Position */
-#define TPI_FFSR_FtNonStop_Msk             (0x1UL << TPI_FFSR_FtNonStop_Pos)           /*!< TPI FFSR: FtNonStop Mask */
-
-#define TPI_FFSR_TCPresent_Pos              2                                          /*!< TPI FFSR: TCPresent Position */
-#define TPI_FFSR_TCPresent_Msk             (0x1UL << TPI_FFSR_TCPresent_Pos)           /*!< TPI FFSR: TCPresent Mask */
-
-#define TPI_FFSR_FtStopped_Pos              1                                          /*!< TPI FFSR: FtStopped Position */
-#define TPI_FFSR_FtStopped_Msk             (0x1UL << TPI_FFSR_FtStopped_Pos)           /*!< TPI FFSR: FtStopped Mask */
-
-#define TPI_FFSR_FlInProg_Pos               0                                          /*!< TPI FFSR: FlInProg Position */
-#define TPI_FFSR_FlInProg_Msk              (0x1UL << TPI_FFSR_FlInProg_Pos)            /*!< TPI FFSR: FlInProg Mask */
-
-/* TPI Formatter and Flush Control Register Definitions */
-#define TPI_FFCR_TrigIn_Pos                 8                                          /*!< TPI FFCR: TrigIn Position */
-#define TPI_FFCR_TrigIn_Msk                (0x1UL << TPI_FFCR_TrigIn_Pos)              /*!< TPI FFCR: TrigIn Mask */
-
-#define TPI_FFCR_EnFCont_Pos                1                                          /*!< TPI FFCR: EnFCont Position */
-#define TPI_FFCR_EnFCont_Msk               (0x1UL << TPI_FFCR_EnFCont_Pos)             /*!< TPI FFCR: EnFCont Mask */
-
-/* TPI TRIGGER Register Definitions */
-#define TPI_TRIGGER_TRIGGER_Pos             0                                          /*!< TPI TRIGGER: TRIGGER Position */
-#define TPI_TRIGGER_TRIGGER_Msk            (0x1UL << TPI_TRIGGER_TRIGGER_Pos)          /*!< TPI TRIGGER: TRIGGER Mask */
-
-/* TPI Integration ETM Data Register Definitions (FIFO0) */
-#define TPI_FIFO0_ITM_ATVALID_Pos          29                                          /*!< TPI FIFO0: ITM_ATVALID Position */
-#define TPI_FIFO0_ITM_ATVALID_Msk          (0x3UL << TPI_FIFO0_ITM_ATVALID_Pos)        /*!< TPI FIFO0: ITM_ATVALID Mask */
-
-#define TPI_FIFO0_ITM_bytecount_Pos        27                                          /*!< TPI FIFO0: ITM_bytecount Position */
-#define TPI_FIFO0_ITM_bytecount_Msk        (0x3UL << TPI_FIFO0_ITM_bytecount_Pos)      /*!< TPI FIFO0: ITM_bytecount Mask */
-
-#define TPI_FIFO0_ETM_ATVALID_Pos          26                                          /*!< TPI FIFO0: ETM_ATVALID Position */
-#define TPI_FIFO0_ETM_ATVALID_Msk          (0x3UL << TPI_FIFO0_ETM_ATVALID_Pos)        /*!< TPI FIFO0: ETM_ATVALID Mask */
-
-#define TPI_FIFO0_ETM_bytecount_Pos        24                                          /*!< TPI FIFO0: ETM_bytecount Position */
-#define TPI_FIFO0_ETM_bytecount_Msk        (0x3UL << TPI_FIFO0_ETM_bytecount_Pos)      /*!< TPI FIFO0: ETM_bytecount Mask */
-
-#define TPI_FIFO0_ETM2_Pos                 16                                          /*!< TPI FIFO0: ETM2 Position */
-#define TPI_FIFO0_ETM2_Msk                 (0xFFUL << TPI_FIFO0_ETM2_Pos)              /*!< TPI FIFO0: ETM2 Mask */
-
-#define TPI_FIFO0_ETM1_Pos                  8                                          /*!< TPI FIFO0: ETM1 Position */
-#define TPI_FIFO0_ETM1_Msk                 (0xFFUL << TPI_FIFO0_ETM1_Pos)              /*!< TPI FIFO0: ETM1 Mask */
-
-#define TPI_FIFO0_ETM0_Pos                  0                                          /*!< TPI FIFO0: ETM0 Position */
-#define TPI_FIFO0_ETM0_Msk                 (0xFFUL << TPI_FIFO0_ETM0_Pos)              /*!< TPI FIFO0: ETM0 Mask */
-
-/* TPI ITATBCTR2 Register Definitions */
-#define TPI_ITATBCTR2_ATREADY_Pos           0                                          /*!< TPI ITATBCTR2: ATREADY Position */
-#define TPI_ITATBCTR2_ATREADY_Msk          (0x1UL << TPI_ITATBCTR2_ATREADY_Pos)        /*!< TPI ITATBCTR2: ATREADY Mask */
-
-/* TPI Integration ITM Data Register Definitions (FIFO1) */
-#define TPI_FIFO1_ITM_ATVALID_Pos          29                                          /*!< TPI FIFO1: ITM_ATVALID Position */
-#define TPI_FIFO1_ITM_ATVALID_Msk          (0x3UL << TPI_FIFO1_ITM_ATVALID_Pos)        /*!< TPI FIFO1: ITM_ATVALID Mask */
-
-#define TPI_FIFO1_ITM_bytecount_Pos        27                                          /*!< TPI FIFO1: ITM_bytecount Position */
-#define TPI_FIFO1_ITM_bytecount_Msk        (0x3UL << TPI_FIFO1_ITM_bytecount_Pos)      /*!< TPI FIFO1: ITM_bytecount Mask */
-
-#define TPI_FIFO1_ETM_ATVALID_Pos          26                                          /*!< TPI FIFO1: ETM_ATVALID Position */
-#define TPI_FIFO1_ETM_ATVALID_Msk          (0x3UL << TPI_FIFO1_ETM_ATVALID_Pos)        /*!< TPI FIFO1: ETM_ATVALID Mask */
-
-#define TPI_FIFO1_ETM_bytecount_Pos        24                                          /*!< TPI FIFO1: ETM_bytecount Position */
-#define TPI_FIFO1_ETM_bytecount_Msk        (0x3UL << TPI_FIFO1_ETM_bytecount_Pos)      /*!< TPI FIFO1: ETM_bytecount Mask */
-
-#define TPI_FIFO1_ITM2_Pos                 16                                          /*!< TPI FIFO1: ITM2 Position */
-#define TPI_FIFO1_ITM2_Msk                 (0xFFUL << TPI_FIFO1_ITM2_Pos)              /*!< TPI FIFO1: ITM2 Mask */
-
-#define TPI_FIFO1_ITM1_Pos                  8                                          /*!< TPI FIFO1: ITM1 Position */
-#define TPI_FIFO1_ITM1_Msk                 (0xFFUL << TPI_FIFO1_ITM1_Pos)              /*!< TPI FIFO1: ITM1 Mask */
-
-#define TPI_FIFO1_ITM0_Pos                  0                                          /*!< TPI FIFO1: ITM0 Position */
-#define TPI_FIFO1_ITM0_Msk                 (0xFFUL << TPI_FIFO1_ITM0_Pos)              /*!< TPI FIFO1: ITM0 Mask */
-
-/* TPI ITATBCTR0 Register Definitions */
-#define TPI_ITATBCTR0_ATREADY_Pos           0                                          /*!< TPI ITATBCTR0: ATREADY Position */
-#define TPI_ITATBCTR0_ATREADY_Msk          (0x1UL << TPI_ITATBCTR0_ATREADY_Pos)        /*!< TPI ITATBCTR0: ATREADY Mask */
-
-/* TPI Integration Mode Control Register Definitions */
-#define TPI_ITCTRL_Mode_Pos                 0                                          /*!< TPI ITCTRL: Mode Position */
-#define TPI_ITCTRL_Mode_Msk                (0x1UL << TPI_ITCTRL_Mode_Pos)              /*!< TPI ITCTRL: Mode Mask */
-
-/* TPI DEVID Register Definitions */
-#define TPI_DEVID_NRZVALID_Pos             11                                          /*!< TPI DEVID: NRZVALID Position */
-#define TPI_DEVID_NRZVALID_Msk             (0x1UL << TPI_DEVID_NRZVALID_Pos)           /*!< TPI DEVID: NRZVALID Mask */
-
-#define TPI_DEVID_MANCVALID_Pos            10                                          /*!< TPI DEVID: MANCVALID Position */
-#define TPI_DEVID_MANCVALID_Msk            (0x1UL << TPI_DEVID_MANCVALID_Pos)          /*!< TPI DEVID: MANCVALID Mask */
-
-#define TPI_DEVID_PTINVALID_Pos             9                                          /*!< TPI DEVID: PTINVALID Position */
-#define TPI_DEVID_PTINVALID_Msk            (0x1UL << TPI_DEVID_PTINVALID_Pos)          /*!< TPI DEVID: PTINVALID Mask */
-
-#define TPI_DEVID_MinBufSz_Pos              6                                          /*!< TPI DEVID: MinBufSz Position */
-#define TPI_DEVID_MinBufSz_Msk             (0x7UL << TPI_DEVID_MinBufSz_Pos)           /*!< TPI DEVID: MinBufSz Mask */
-
-#define TPI_DEVID_AsynClkIn_Pos             5                                          /*!< TPI DEVID: AsynClkIn Position */
-#define TPI_DEVID_AsynClkIn_Msk            (0x1UL << TPI_DEVID_AsynClkIn_Pos)          /*!< TPI DEVID: AsynClkIn Mask */
-
-#define TPI_DEVID_NrTraceInput_Pos          0                                          /*!< TPI DEVID: NrTraceInput Position */
-#define TPI_DEVID_NrTraceInput_Msk         (0x1FUL << TPI_DEVID_NrTraceInput_Pos)      /*!< TPI DEVID: NrTraceInput Mask */
-
-/* TPI DEVTYPE Register Definitions */
-#define TPI_DEVTYPE_SubType_Pos             0                                          /*!< TPI DEVTYPE: SubType Position */
-#define TPI_DEVTYPE_SubType_Msk            (0xFUL << TPI_DEVTYPE_SubType_Pos)          /*!< TPI DEVTYPE: SubType Mask */
-
-#define TPI_DEVTYPE_MajorType_Pos           4                                          /*!< TPI DEVTYPE: MajorType Position */
-#define TPI_DEVTYPE_MajorType_Msk          (0xFUL << TPI_DEVTYPE_MajorType_Pos)        /*!< TPI DEVTYPE: MajorType Mask */
-
-/*@}*/ /* end of group CMSIS_TPI */
-
-
-#if (__MPU_PRESENT == 1)
-/** \ingroup  CMSIS_core_register
-    \defgroup CMSIS_MPU     Memory Protection Unit (MPU)
-    \brief      Type definitions for the Memory Protection Unit (MPU)
-  @{
- */
-
-/** \brief  Structure type to access the Memory Protection Unit (MPU).
- */
-typedef struct
-{
-  __I  uint32_t TYPE;                    /*!< Offset: 0x000 (R/ )  MPU Type Register                              */
-  __IO uint32_t CTRL;                    /*!< Offset: 0x004 (R/W)  MPU Control Register                           */
-  __IO uint32_t RNR;                     /*!< Offset: 0x008 (R/W)  MPU Region RNRber Register                     */
-  __IO uint32_t RBAR;                    /*!< Offset: 0x00C (R/W)  MPU Region Base Address Register               */
-  __IO uint32_t RASR;                    /*!< Offset: 0x010 (R/W)  MPU Region Attribute and Size Register         */
-  __IO uint32_t RBAR_A1;                 /*!< Offset: 0x014 (R/W)  MPU Alias 1 Region Base Address Register       */
-  __IO uint32_t RASR_A1;                 /*!< Offset: 0x018 (R/W)  MPU Alias 1 Region Attribute and Size Register */
-  __IO uint32_t RBAR_A2;                 /*!< Offset: 0x01C (R/W)  MPU Alias 2 Region Base Address Register       */
-  __IO uint32_t RASR_A2;                 /*!< Offset: 0x020 (R/W)  MPU Alias 2 Region Attribute and Size Register */
-  __IO uint32_t RBAR_A3;                 /*!< Offset: 0x024 (R/W)  MPU Alias 3 Region Base Address Register       */
-  __IO uint32_t RASR_A3;                 /*!< Offset: 0x028 (R/W)  MPU Alias 3 Region Attribute and Size Register */
-} MPU_Type;
-
-/* MPU Type Register */
-#define MPU_TYPE_IREGION_Pos               16                                             /*!< MPU TYPE: IREGION Position */
-#define MPU_TYPE_IREGION_Msk               (0xFFUL << MPU_TYPE_IREGION_Pos)               /*!< MPU TYPE: IREGION Mask */
-
-#define MPU_TYPE_DREGION_Pos                8                                             /*!< MPU TYPE: DREGION Position */
-#define MPU_TYPE_DREGION_Msk               (0xFFUL << MPU_TYPE_DREGION_Pos)               /*!< MPU TYPE: DREGION Mask */
-
-#define MPU_TYPE_SEPARATE_Pos               0                                             /*!< MPU TYPE: SEPARATE Position */
-#define MPU_TYPE_SEPARATE_Msk              (1UL << MPU_TYPE_SEPARATE_Pos)                 /*!< MPU TYPE: SEPARATE Mask */
-
-/* MPU Control Register */
-#define MPU_CTRL_PRIVDEFENA_Pos             2                                             /*!< MPU CTRL: PRIVDEFENA Position */
-#define MPU_CTRL_PRIVDEFENA_Msk            (1UL << MPU_CTRL_PRIVDEFENA_Pos)               /*!< MPU CTRL: PRIVDEFENA Mask */
-
-#define MPU_CTRL_HFNMIENA_Pos               1                                             /*!< MPU CTRL: HFNMIENA Position */
-#define MPU_CTRL_HFNMIENA_Msk              (1UL << MPU_CTRL_HFNMIENA_Pos)                 /*!< MPU CTRL: HFNMIENA Mask */
-
-#define MPU_CTRL_ENABLE_Pos                 0                                             /*!< MPU CTRL: ENABLE Position */
-#define MPU_CTRL_ENABLE_Msk                (1UL << MPU_CTRL_ENABLE_Pos)                   /*!< MPU CTRL: ENABLE Mask */
-
-/* MPU Region Number Register */
-#define MPU_RNR_REGION_Pos                  0                                             /*!< MPU RNR: REGION Position */
-#define MPU_RNR_REGION_Msk                 (0xFFUL << MPU_RNR_REGION_Pos)                 /*!< MPU RNR: REGION Mask */
-
-/* MPU Region Base Address Register */
-#define MPU_RBAR_ADDR_Pos                   5                                             /*!< MPU RBAR: ADDR Position */
-#define MPU_RBAR_ADDR_Msk                  (0x7FFFFFFUL << MPU_RBAR_ADDR_Pos)             /*!< MPU RBAR: ADDR Mask */
-
-#define MPU_RBAR_VALID_Pos                  4                                             /*!< MPU RBAR: VALID Position */
-#define MPU_RBAR_VALID_Msk                 (1UL << MPU_RBAR_VALID_Pos)                    /*!< MPU RBAR: VALID Mask */
-
-#define MPU_RBAR_REGION_Pos                 0                                             /*!< MPU RBAR: REGION Position */
-#define MPU_RBAR_REGION_Msk                (0xFUL << MPU_RBAR_REGION_Pos)                 /*!< MPU RBAR: REGION Mask */
-
-/* MPU Region Attribute and Size Register */
-#define MPU_RASR_ATTRS_Pos                 16                                             /*!< MPU RASR: MPU Region Attribute field Position */
-#define MPU_RASR_ATTRS_Msk                 (0xFFFFUL << MPU_RASR_ATTRS_Pos)               /*!< MPU RASR: MPU Region Attribute field Mask */
-
-#define MPU_RASR_XN_Pos                    28                                             /*!< MPU RASR: ATTRS.XN Position */
-#define MPU_RASR_XN_Msk                    (1UL << MPU_RASR_XN_Pos)                       /*!< MPU RASR: ATTRS.XN Mask */
-
-#define MPU_RASR_AP_Pos                    24                                             /*!< MPU RASR: ATTRS.AP Position */
-#define MPU_RASR_AP_Msk                    (0x7UL << MPU_RASR_AP_Pos)                     /*!< MPU RASR: ATTRS.AP Mask */
-
-#define MPU_RASR_TEX_Pos                   19                                             /*!< MPU RASR: ATTRS.TEX Position */
-#define MPU_RASR_TEX_Msk                   (0x7UL << MPU_RASR_TEX_Pos)                    /*!< MPU RASR: ATTRS.TEX Mask */
-
-#define MPU_RASR_S_Pos                     18                                             /*!< MPU RASR: ATTRS.S Position */
-#define MPU_RASR_S_Msk                     (1UL << MPU_RASR_S_Pos)                        /*!< MPU RASR: ATTRS.S Mask */
-
-#define MPU_RASR_C_Pos                     17                                             /*!< MPU RASR: ATTRS.C Position */
-#define MPU_RASR_C_Msk                     (1UL << MPU_RASR_C_Pos)                        /*!< MPU RASR: ATTRS.C Mask */
-
-#define MPU_RASR_B_Pos                     16                                             /*!< MPU RASR: ATTRS.B Position */
-#define MPU_RASR_B_Msk                     (1UL << MPU_RASR_B_Pos)                        /*!< MPU RASR: ATTRS.B Mask */
-
-#define MPU_RASR_SRD_Pos                    8                                             /*!< MPU RASR: Sub-Region Disable Position */
-#define MPU_RASR_SRD_Msk                   (0xFFUL << MPU_RASR_SRD_Pos)                   /*!< MPU RASR: Sub-Region Disable Mask */
-
-#define MPU_RASR_SIZE_Pos                   1                                             /*!< MPU RASR: Region Size Field Position */
-#define MPU_RASR_SIZE_Msk                  (0x1FUL << MPU_RASR_SIZE_Pos)                  /*!< MPU RASR: Region Size Field Mask */
-
-#define MPU_RASR_ENABLE_Pos                 0                                             /*!< MPU RASR: Region enable bit Position */
-#define MPU_RASR_ENABLE_Msk                (1UL << MPU_RASR_ENABLE_Pos)                   /*!< MPU RASR: Region enable bit Disable Mask */
-
-/*@} end of group CMSIS_MPU */
-#endif
-
-
-/** \ingroup  CMSIS_core_register
-    \defgroup CMSIS_CoreDebug       Core Debug Registers (CoreDebug)
-    \brief      Type definitions for the Core Debug Registers
-  @{
- */
-
-/** \brief  Structure type to access the Core Debug Register (CoreDebug).
- */
-typedef struct
-{
-  __IO uint32_t DHCSR;                   /*!< Offset: 0x000 (R/W)  Debug Halting Control and Status Register    */
-  __O  uint32_t DCRSR;                   /*!< Offset: 0x004 ( /W)  Debug Core Register Selector Register        */
-  __IO uint32_t DCRDR;                   /*!< Offset: 0x008 (R/W)  Debug Core Register Data Register            */
-  __IO uint32_t DEMCR;                   /*!< Offset: 0x00C (R/W)  Debug Exception and Monitor Control Register */
-} CoreDebug_Type;
-
-/* Debug Halting Control and Status Register */
-#define CoreDebug_DHCSR_DBGKEY_Pos         16                                             /*!< CoreDebug DHCSR: DBGKEY Position */
-#define CoreDebug_DHCSR_DBGKEY_Msk         (0xFFFFUL << CoreDebug_DHCSR_DBGKEY_Pos)       /*!< CoreDebug DHCSR: DBGKEY Mask */
-
-#define CoreDebug_DHCSR_S_RESET_ST_Pos     25                                             /*!< CoreDebug DHCSR: S_RESET_ST Position */
-#define CoreDebug_DHCSR_S_RESET_ST_Msk     (1UL << CoreDebug_DHCSR_S_RESET_ST_Pos)        /*!< CoreDebug DHCSR: S_RESET_ST Mask */
-
-#define CoreDebug_DHCSR_S_RETIRE_ST_Pos    24                                             /*!< CoreDebug DHCSR: S_RETIRE_ST Position */
-#define CoreDebug_DHCSR_S_RETIRE_ST_Msk    (1UL << CoreDebug_DHCSR_S_RETIRE_ST_Pos)       /*!< CoreDebug DHCSR: S_RETIRE_ST Mask */
-
-#define CoreDebug_DHCSR_S_LOCKUP_Pos       19                                             /*!< CoreDebug DHCSR: S_LOCKUP Position */
-#define CoreDebug_DHCSR_S_LOCKUP_Msk       (1UL << CoreDebug_DHCSR_S_LOCKUP_Pos)          /*!< CoreDebug DHCSR: S_LOCKUP Mask */
-
-#define CoreDebug_DHCSR_S_SLEEP_Pos        18                                             /*!< CoreDebug DHCSR: S_SLEEP Position */
-#define CoreDebug_DHCSR_S_SLEEP_Msk        (1UL << CoreDebug_DHCSR_S_SLEEP_Pos)           /*!< CoreDebug DHCSR: S_SLEEP Mask */
-
-#define CoreDebug_DHCSR_S_HALT_Pos         17                                             /*!< CoreDebug DHCSR: S_HALT Position */
-#define CoreDebug_DHCSR_S_HALT_Msk         (1UL << CoreDebug_DHCSR_S_HALT_Pos)            /*!< CoreDebug DHCSR: S_HALT Mask */
-
-#define CoreDebug_DHCSR_S_REGRDY_Pos       16                                             /*!< CoreDebug DHCSR: S_REGRDY Position */
-#define CoreDebug_DHCSR_S_REGRDY_Msk       (1UL << CoreDebug_DHCSR_S_REGRDY_Pos)          /*!< CoreDebug DHCSR: S_REGRDY Mask */
-
-#define CoreDebug_DHCSR_C_SNAPSTALL_Pos     5                                             /*!< CoreDebug DHCSR: C_SNAPSTALL Position */
-#define CoreDebug_DHCSR_C_SNAPSTALL_Msk    (1UL << CoreDebug_DHCSR_C_SNAPSTALL_Pos)       /*!< CoreDebug DHCSR: C_SNAPSTALL Mask */
-
-#define CoreDebug_DHCSR_C_MASKINTS_Pos      3                                             /*!< CoreDebug DHCSR: C_MASKINTS Position */
-#define CoreDebug_DHCSR_C_MASKINTS_Msk     (1UL << CoreDebug_DHCSR_C_MASKINTS_Pos)        /*!< CoreDebug DHCSR: C_MASKINTS Mask */
-
-#define CoreDebug_DHCSR_C_STEP_Pos          2                                             /*!< CoreDebug DHCSR: C_STEP Position */
-#define CoreDebug_DHCSR_C_STEP_Msk         (1UL << CoreDebug_DHCSR_C_STEP_Pos)            /*!< CoreDebug DHCSR: C_STEP Mask */
-
-#define CoreDebug_DHCSR_C_HALT_Pos          1                                             /*!< CoreDebug DHCSR: C_HALT Position */
-#define CoreDebug_DHCSR_C_HALT_Msk         (1UL << CoreDebug_DHCSR_C_HALT_Pos)            /*!< CoreDebug DHCSR: C_HALT Mask */
-
-#define CoreDebug_DHCSR_C_DEBUGEN_Pos       0                                             /*!< CoreDebug DHCSR: C_DEBUGEN Position */
-#define CoreDebug_DHCSR_C_DEBUGEN_Msk      (1UL << CoreDebug_DHCSR_C_DEBUGEN_Pos)         /*!< CoreDebug DHCSR: C_DEBUGEN Mask */
-
-/* Debug Core Register Selector Register */
-#define CoreDebug_DCRSR_REGWnR_Pos         16                                             /*!< CoreDebug DCRSR: REGWnR Position */
-#define CoreDebug_DCRSR_REGWnR_Msk         (1UL << CoreDebug_DCRSR_REGWnR_Pos)            /*!< CoreDebug DCRSR: REGWnR Mask */
-
-#define CoreDebug_DCRSR_REGSEL_Pos          0                                             /*!< CoreDebug DCRSR: REGSEL Position */
-#define CoreDebug_DCRSR_REGSEL_Msk         (0x1FUL << CoreDebug_DCRSR_REGSEL_Pos)         /*!< CoreDebug DCRSR: REGSEL Mask */
-
-/* Debug Exception and Monitor Control Register */
-#define CoreDebug_DEMCR_TRCENA_Pos         24                                             /*!< CoreDebug DEMCR: TRCENA Position */
-#define CoreDebug_DEMCR_TRCENA_Msk         (1UL << CoreDebug_DEMCR_TRCENA_Pos)            /*!< CoreDebug DEMCR: TRCENA Mask */
-
-#define CoreDebug_DEMCR_MON_REQ_Pos        19                                             /*!< CoreDebug DEMCR: MON_REQ Position */
-#define CoreDebug_DEMCR_MON_REQ_Msk        (1UL << CoreDebug_DEMCR_MON_REQ_Pos)           /*!< CoreDebug DEMCR: MON_REQ Mask */
-
-#define CoreDebug_DEMCR_MON_STEP_Pos       18                                             /*!< CoreDebug DEMCR: MON_STEP Position */
-#define CoreDebug_DEMCR_MON_STEP_Msk       (1UL << CoreDebug_DEMCR_MON_STEP_Pos)          /*!< CoreDebug DEMCR: MON_STEP Mask */
-
-#define CoreDebug_DEMCR_MON_PEND_Pos       17                                             /*!< CoreDebug DEMCR: MON_PEND Position */
-#define CoreDebug_DEMCR_MON_PEND_Msk       (1UL << CoreDebug_DEMCR_MON_PEND_Pos)          /*!< CoreDebug DEMCR: MON_PEND Mask */
-
-#define CoreDebug_DEMCR_MON_EN_Pos         16                                             /*!< CoreDebug DEMCR: MON_EN Position */
-#define CoreDebug_DEMCR_MON_EN_Msk         (1UL << CoreDebug_DEMCR_MON_EN_Pos)            /*!< CoreDebug DEMCR: MON_EN Mask */
-
-#define CoreDebug_DEMCR_VC_HARDERR_Pos     10                                             /*!< CoreDebug DEMCR: VC_HARDERR Position */
-#define CoreDebug_DEMCR_VC_HARDERR_Msk     (1UL << CoreDebug_DEMCR_VC_HARDERR_Pos)        /*!< CoreDebug DEMCR: VC_HARDERR Mask */
-
-#define CoreDebug_DEMCR_VC_INTERR_Pos       9                                             /*!< CoreDebug DEMCR: VC_INTERR Position */
-#define CoreDebug_DEMCR_VC_INTERR_Msk      (1UL << CoreDebug_DEMCR_VC_INTERR_Pos)         /*!< CoreDebug DEMCR: VC_INTERR Mask */
-
-#define CoreDebug_DEMCR_VC_BUSERR_Pos       8                                             /*!< CoreDebug DEMCR: VC_BUSERR Position */
-#define CoreDebug_DEMCR_VC_BUSERR_Msk      (1UL << CoreDebug_DEMCR_VC_BUSERR_Pos)         /*!< CoreDebug DEMCR: VC_BUSERR Mask */
-
-#define CoreDebug_DEMCR_VC_STATERR_Pos      7                                             /*!< CoreDebug DEMCR: VC_STATERR Position */
-#define CoreDebug_DEMCR_VC_STATERR_Msk     (1UL << CoreDebug_DEMCR_VC_STATERR_Pos)        /*!< CoreDebug DEMCR: VC_STATERR Mask */
-
-#define CoreDebug_DEMCR_VC_CHKERR_Pos       6                                             /*!< CoreDebug DEMCR: VC_CHKERR Position */
-#define CoreDebug_DEMCR_VC_CHKERR_Msk      (1UL << CoreDebug_DEMCR_VC_CHKERR_Pos)         /*!< CoreDebug DEMCR: VC_CHKERR Mask */
-
-#define CoreDebug_DEMCR_VC_NOCPERR_Pos      5                                             /*!< CoreDebug DEMCR: VC_NOCPERR Position */
-#define CoreDebug_DEMCR_VC_NOCPERR_Msk     (1UL << CoreDebug_DEMCR_VC_NOCPERR_Pos)        /*!< CoreDebug DEMCR: VC_NOCPERR Mask */
-
-#define CoreDebug_DEMCR_VC_MMERR_Pos        4                                             /*!< CoreDebug DEMCR: VC_MMERR Position */
-#define CoreDebug_DEMCR_VC_MMERR_Msk       (1UL << CoreDebug_DEMCR_VC_MMERR_Pos)          /*!< CoreDebug DEMCR: VC_MMERR Mask */
-
-#define CoreDebug_DEMCR_VC_CORERESET_Pos    0                                             /*!< CoreDebug DEMCR: VC_CORERESET Position */
-#define CoreDebug_DEMCR_VC_CORERESET_Msk   (1UL << CoreDebug_DEMCR_VC_CORERESET_Pos)      /*!< CoreDebug DEMCR: VC_CORERESET Mask */
-
-/*@} end of group CMSIS_CoreDebug */
-
-
-/** \ingroup    CMSIS_core_register
-    \defgroup   CMSIS_core_base     Core Definitions
-    \brief      Definitions for base addresses, unions, and structures.
-  @{
- */
-
-/* Memory mapping of Cortex-M3 Hardware */
-#define SCS_BASE            (0xE000E000UL)                            /*!< System Control Space Base Address  */
-#define ITM_BASE            (0xE0000000UL)                            /*!< ITM Base Address                   */
-#define DWT_BASE            (0xE0001000UL)                            /*!< DWT Base Address                   */
-#define TPI_BASE            (0xE0040000UL)                            /*!< TPI Base Address                   */
-#define CoreDebug_BASE      (0xE000EDF0UL)                            /*!< Core Debug Base Address            */
-#define SysTick_BASE        (SCS_BASE +  0x0010UL)                    /*!< SysTick Base Address               */
-#define NVIC_BASE           (SCS_BASE +  0x0100UL)                    /*!< NVIC Base Address                  */
-#define SCB_BASE            (SCS_BASE +  0x0D00UL)                    /*!< System Control Block Base Address  */
-
-#define SCnSCB              ((SCnSCB_Type    *)     SCS_BASE      )   /*!< System control Register not in SCB */
-#define SCB                 ((SCB_Type       *)     SCB_BASE      )   /*!< SCB configuration struct           */
-#define SysTick             ((SysTick_Type   *)     SysTick_BASE  )   /*!< SysTick configuration struct       */
-#define NVIC                ((NVIC_Type      *)     NVIC_BASE     )   /*!< NVIC configuration struct          */
-#define ITM                 ((ITM_Type       *)     ITM_BASE      )   /*!< ITM configuration struct           */
-#define DWT                 ((DWT_Type       *)     DWT_BASE      )   /*!< DWT configuration struct           */
-#define TPI                 ((TPI_Type       *)     TPI_BASE      )   /*!< TPI configuration struct           */
-#define CoreDebug           ((CoreDebug_Type *)     CoreDebug_BASE)   /*!< Core Debug configuration struct    */
-
-#if (__MPU_PRESENT == 1)
-  #define MPU_BASE          (SCS_BASE +  0x0D90UL)                    /*!< Memory Protection Unit             */
-  #define MPU               ((MPU_Type       *)     MPU_BASE      )   /*!< Memory Protection Unit             */
-#endif
-
-/*@} */
-
-
-
-/*******************************************************************************
- *                Hardware Abstraction Layer
-  Core Function Interface contains:
-  - Core NVIC Functions
-  - Core SysTick Functions
-  - Core Debug Functions
-  - Core Register Access Functions
- ******************************************************************************/
-/** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference
-*/
-
-
-
-/* ##########################   NVIC functions  #################################### */
-/** \ingroup  CMSIS_Core_FunctionInterface
-    \defgroup CMSIS_Core_NVICFunctions NVIC Functions
-    \brief      Functions that manage interrupts and exceptions via the NVIC.
-    @{
- */
-
-/** \brief  Set Priority Grouping
-
-  The function sets the priority grouping field using the required unlock sequence.
-  The parameter PriorityGroup is assigned to the field SCB->AIRCR [10:8] PRIGROUP field.
-  Only values from 0..7 are used.
-  In case of a conflict between priority grouping and available
-  priority bits (__NVIC_PRIO_BITS), the smallest possible priority group is set.
-
-    \param [in]      PriorityGroup  Priority grouping field.
- */
-__STATIC_INLINE void NVIC_SetPriorityGrouping(uint32_t PriorityGroup)
-{
-  uint32_t reg_value;
-  uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07);               /* only values 0..7 are used          */
-
-  reg_value  =  SCB->AIRCR;                                                   /* read old register configuration    */
-  reg_value &= ~(SCB_AIRCR_VECTKEY_Msk | SCB_AIRCR_PRIGROUP_Msk);             /* clear bits to change               */
-  reg_value  =  (reg_value                                 |
-                ((uint32_t)0x5FA << SCB_AIRCR_VECTKEY_Pos) |
-                (PriorityGroupTmp << 8));                                     /* Insert write key and priorty group */
-  SCB->AIRCR =  reg_value;
-}
-
-
-/** \brief  Get Priority Grouping
-
-  The function reads the priority grouping field from the NVIC Interrupt Controller.
-
-    \return                Priority grouping field (SCB->AIRCR [10:8] PRIGROUP field).
- */
-__STATIC_INLINE uint32_t NVIC_GetPriorityGrouping(void)
-{
-  return ((SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) >> SCB_AIRCR_PRIGROUP_Pos);   /* read priority grouping field */
-}
-
-
-/** \brief  Enable External Interrupt
-
-    The function enables a device-specific interrupt in the NVIC interrupt controller.
-
-    \param [in]      IRQn  External interrupt number. Value cannot be negative.
- */
-__STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn)
-{
-  NVIC->ISER[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* enable interrupt */
-}
-
-
-/** \brief  Disable External Interrupt
-
-    The function disables a device-specific interrupt in the NVIC interrupt controller.
-
-    \param [in]      IRQn  External interrupt number. Value cannot be negative.
- */
-__STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn)
-{
-  NVIC->ICER[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* disable interrupt */
-}
-
-
-/** \brief  Get Pending Interrupt
-
-    The function reads the pending register in the NVIC and returns the pending bit
-    for the specified interrupt.
-
-    \param [in]      IRQn  Interrupt number.
-
-    \return             0  Interrupt status is not pending.
-    \return             1  Interrupt sta

<TRUNCATED>


[30/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/bootutil/design.txt
----------------------------------------------------------------------
diff --git a/libs/bootutil/design.txt b/libs/bootutil/design.txt
deleted file mode 100644
index a39759b..0000000
--- a/libs/bootutil/design.txt
+++ /dev/null
@@ -1,413 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you 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.
-#
-
-****** BOOTUTIL
-
-*** SUMMARY
-
-The bootutil library performs most of the functions of a boot loader.  In
-particular, the piece that is missing is the final step of actually jumping to
-the main image.  This last step should instead be implemented in an
-architecture-specific project.  Boot loader functionality is separated in this
-manner for the following two reasons:
-
-1. By keeping architecture-dependent code separate, the bootutil library can be
-   reused among several boot loaders.
-
-2. By excluding the last boot step from the library, the rest of the code can
-   be tested in a sim environment.
-
-There is a boot loader project specific to the olimex_stm32-e407 devboard
-called "boot."  This project provides an example of how the bootutil library
-should be used.
-
-*** LIMITATIONS
-
-The boot loader currently only supports images with the following
-characteristics:
-    * Built to run from flash.
-    * Build to run from a fixed location (i.e., position-independent).
-
-These limitations will likely be addressed soon.
-
-
-*** IMAGE FORMAT
-
-The following definitions describe the image header format.
-
-#define IMAGE_MAGIC                 0x96f3b83c
-
-struct image_version {
-    uint8_t iv_major;
-    uint8_t iv_minor;
-    uint16_t iv_revision;
-    uint32_t iv_build_num;
-};
-
-/** Image header.  All fields are in little endian byte order. */
-struct image_header {
-    uint32_t ih_magic;
-    uint32_t ih_crc32; /* Covers remainder of header and all of image body. */
-    uint32_t ih_hdr_size;
-    uint32_t ih_img_size; /* Does not include header. */
-    uint32_t ih_flags;
-    struct image_version ih_ver;
-};
-
-At this time, no flags have been defined.
-
-The ih_hdr_size field indicates the length of the header, and therefore the
-offset of the image itself.  This field provides for backwards compatibility in
-case of changes to the format of the image header.
-
-When security is added, security data will likely go in a footer at the end of
-the image.
-
-
-*** FLASH AREAS
-
-Bootutil uses the same concept of "flash areas" as the nffs file system.
-Briefly, an area is a region of disk with the following properties:
-    (1) An area can be fully erased without affecting any other areas.
-    (2) A write to one area does not restrict writes to other areas.
-
-The areas used for image data must not be used for anything else.  In
-particular, these areas must be kept separate from the nffs file system.
-
-
-*** IMAGE SLOTS
-
-A portion of the flash memory is partitioned into two image slots: a primary
-slot and a secondary slot.  The boot loader will only run an image from the
-primary slot, so images must be built such that they can run from that fixed
-location in flash.  If the boot loader needs to run the image resident in the
-secondary slot, it must swap the two images in flash prior to booting.
-
-In addition to the two image slots, the boot loader requires a scratch area to
-allow for reliable image swapping.
-
-All areas used by image data (including the scratch area) must be the same
-size.
-
-
-*** BOOT VECTOR
-
-Bootutil determines which image it should boot into by reading the contents of
-the boot vector.  The boot vector comprises the following files in the flash
-file system:
-
-#define BOOT_PATH_MAIN      "/boot/main"
-#define BOOT_PATH_TEST      "/boot/test"
-
-Each file, if present, must contain a 64-bit image version.  This version is
-simply a "binary dump" of an image_version struct.  The test file is used to
-indicate that an image is being "tested out," and should only be booted once.
-The main file indicates the "last known good" image which should be booted
-repeatedly.
-
-The boot loader uses the following procedure to determine which image to boot:
-
-1) If the test file is present and contains a valid image version:
-    * Delete the test file.
-    * Boot into the specified image.
-
-2) Else if the main file is present and contains a valid image version:
-    * Boot into the specified image.
-
-3) Else:
-    * Just boot into whichever image is in the primary slot.  If there is no
-      image in the primary slot, boot into the image in the secondary slot.
-
-If a vector file contains a version which doesn't correspond to an image
-actually present in flash, the boot loader deletes the file and procedes as
-though the file was not present.
-
-
-*** BOOT STATUS
-
-The boot status file allows the boot loader to recover in case it was reset
-while in the middle of an image swap operation.  Image swapping is discussed
-later in this document; the structure of the boot status file is presented
-here.  To ensure recovery is always possible, bootutil updates the status file
-at each step throughout the image swap process.  The boot status is contained
-in the following file:
-
-#define BOOT_PATH_STATUS    "/boot/status"
-
-The contents of the boot status file are defined below.
-
-struct boot_status {
-    uint32_t bs_img1_length;
-    uint32_t bs_img2_length;
-    /* Followed by sequence of boot status entries; file size indicates number
-     * of entries.
-     */
-};
-
-struct boot_status_entry {
-    uint8_t bse_image_num;
-    uint8_t bse_part_num;
-};
-
-#define BOOT_IMAGE_NUM_NONE     0xff
-
-There is a separate boot status entry for each flash area used by the boot
-loader (i.e., each area in the two slots, plus one for the scratch area).  The
-entries are placed in the file in the same order as their corresponding areas
-in flash.  Each entry indicates which image part is resident in the
-corresponding flash area.  If a flash area does not contain any image data, its
-corresponding entry will have a bse_image_num value of BOOT_IMAGE_NUM_NONE.
-
-Consider the following example:
-
-Five flash areas are dedicated to image data, as follows:
-
-    Area 0: slot 0, 0/1
-    Area 1: slot 0, 1/1
-    Area 2: slot 1, 0/1
-    Area 3: slot 1, 1/1
-    Area 4: scratch
-
-The following array of boot status entries is read from the status file:
-
-    [0] = {
-        .bse_image_num = 0,
-        .bse_part_num = 0,
-    },
-    [1] = { 
-        .bse_image_num = 0,
-        .bse_part_num = 1,
-    },
-    [2] = { 
-        .bse_image_num = 1,
-        .bse_part_num = 0,
-    },
-    [3] = { 
-        .bse_image_num = 1,
-        .bse_part_num = 1,
-    },
-    [4] = { 
-        .bse_image_num = 0xff,
-        .bse_part_num = 0xff,
-    },
-
-This status file indicates the following image placement:
-
-    Area 0: image 0, part 0
-    Area 1: image 0, part 1
-    Area 2: image 1, part 0
-    Area 3: image 1, part 1
-    Scratch area: empty
-
-Images don't have an instrinsic image number.  When a swap operation is
-started, the image initially in the primary slot is labelled image 0, and the
-image in the secondary slot is labelled image 1.  All swap operations end with
-image 1 in the primary slot, and image 0 in the secondary slot.
-
-The boot status header containing the image sizes is necessary so that bootutil
-can determine how many flash areas each image occupies.  Without this
-information, bootutil would need to swap the full contents of the image slots,
-including useless data after the end of each image.
-
-The status file is always deleted upon successful boot.
-
-
-*** IMAGE SWAPPING
-
-If the boot vector indicates that the image in the secondary slot should be
-run, the boot loader needs to copy it to the primary slot.  The image currently
-in the primary slot also needs to be retained in flash so that it can be used
-later.  Furthermore, both images need to be recoverable if the boot loader
-resets in the middle of the process.  The two images are swapped according to
-the following procedure:
-
-    1. Determine how many flash areas are required to hold the desired image.
-    2. For each required area in the primary slot ("destination area"):
-        a. Identify the flash area in the secondary slot which contains the
-           required image data ("source area").
-        b. Erase scratch area.
-        c. Copy destination area to scratch area.
-        d. Write updated boot status to the file system.
-        e. Erase destination area.
-        f. Copy source area to destination area.
-        g. Write updated boot status to the file system.
-        h. Erase source area.
-        i. Copy scratch area to source area.
-        j. Write updated boot status to the file system.
-    3. Determine how many flash areas are required to hold image 1.
-    4. For each required area in the secondary slot ("destination area"):
-        a. If the destination area already contains the required image data,
-           advance to the next image part.
-        b. Else, identify the flash area in the primary slot which contains the
-           required image data ("source area").
-        c. Repeat steps b through j from step 2.
-
-This procedure ensures that the contents of the boot status file are always
-accurate, so the boot loader can recover after an unexpected reset.
-
-Step 4 is necessary in case the two images do not occupy the same number of
-flash areas.
-
-
-*** RESET RECOVERY
-
-If the boot loader resets in the middle of a swap operation, the two images may
-be discontiguous in flash.  Bootutil recovers from this condition by using the
-boot status file to determine how the image parts are placed in flash.
-
-If the boot status file indicates that the images are not contiguous, bootutil
-completes the swap operation that was in progress when the system was reset.
-In other words, it applies the procedure defined in the previous section,
-moving image 1 into slot 0 and image 0 into slot 1.  If the boot status file
-indicates that an image part is present in the scratch area, this part is
-copied into the correct location by starting at step e or step h in the
-area-swap procedure, depending on whether the part belongs to image 0 or image
-1.
-
-After the swap operation has been completed, the boot loader proceeds as though
-it had just been started.
-
-
-*** API
-
-The API consists of a single function:
-
-/**
- * Prepares the booting process.  Based on the information provided in the
- * request object, this function moves images around in flash as appropriate,
- * and tells you what address to boot from.
- *
- * @param req                   Contains information about the flash layout.
- * @param rsp                   On success, indicates how booting should occur.
- *
- * @return                      0 on success; nonzero on failure.
- */
-int boot_go(const struct boot_req *req, struct boot_rsp *rsp)
-
-The request and response structures are defined as follows:
-
-/** A request object instructing the boot loader how to proceed. */
-struct boot_req {
-    /**
-     * Array of area descriptors indicating the layout of internal flash; must
-     * be terminated with a 0-length element.
-     */
-    struct nffs_area_desc *br_area_descs;
-
-    /**
-     * Array of indices of elements in the br_area_descs array; indicates which
-     * areas hold image data.
-     */
-    uint8_t *br_image_areas;
-
-    /**
-     * Array of indices of elements in the br_area_descs array; indicates which
-     * areas represent the beginning of an image slot.  This should be a subset
-     * of the br_image_areas array.
-     */
-    uint8_t *br_slot_areas;
-
-    /**
-     * The number of image areas (i.e., the size of the br_image_areas array).
-     */
-    uint8_t br_num_image_areas;
-
-    /** The index of the area to use as the image scratch area. */
-    uint8_t br_scratch_area_idx;
-};
-
-/**
- * A response object provided by the boot loader code; indicates where to jump
- * to execute the main image.
- */
-struct boot_rsp {
-    /** A pointer to the header of the image to be executed. */
-    const struct image_header *br_hdr;
-
-    /**
-     * The flash offset of the image to execute.  Indicates the position of
-     * the image header.
-     */
-    uint32_t br_image_addr;
-};
-
-
-*** EXAMPLE USAGE
-
-In this example, each image slot consists of three flash areas.
-
-/** Internal flash layout. */
-static struct nffs_area_desc boot_area_descs[] = {
-    [0] =  { 0x08000000, 16 * 1024 },
-    [1] =  { 0x08004000, 16 * 1024 },
-    [2] =  { 0x08008000, 16 * 1024 },
-    [3] =  { 0x0800c000, 16 * 1024 },
-    [4] =  { 0x08010000, 64 * 1024 },
-    [5] =  { 0x08020000, 128 * 1024 }, /* Image data; 0,0. */
-    [6] =  { 0x08040000, 128 * 1024 }, /* Image data; 0,1. */
-    [7] =  { 0x08060000, 128 * 1024 }, /* Image data; 0,2. */
-    [8] =  { 0x08080000, 128 * 1024 }, /* Image data; 1,0. */
-    [9] =  { 0x080a0000, 128 * 1024 }, /* Image data; 1,1. */
-    [10] = { 0x080c0000, 128 * 1024 }, /* Image data; 1,2. */
-    [11] = { 0x080e0000, 128 * 1024 }, /* Image scratch area. */
-    { 0, 0 },
-};
-
-/** Contains indices of the areas which can contain image data. */
-static uint8_t boot_img_areas[] = {
-    5, 6, 7, 8, 9, 10, 11,
-};
-
-/** Areas representing the beginning of image slots. */
-static uint8_t boot_slot_areas[] = {
-    5, 8,
-};
-
-#define BOOT_NUM_IMG_AREAS \
-    ((int)(sizeof boot_img_areas / sizeof boot_img_areas[0]))
-
-/** The scratch area to use during an image swap operation. */
-#define BOOT_AREA_IDX_SCRATCH 11
-
-int
-main(void)
-{
-    struct boot_rsp rsp;
-    int rc;
-
-    const struct boot_req req = {
-        .br_area_descs = boot_area_descs,
-        .br_image_areas = boot_img_areas,
-        .br_slot_areas = boot_slot_areas,
-        .br_num_image_areas = BOOT_NUM_IMG_AREAS,
-        .br_scratch_area_idx = BOOT_AREA_IDX_SCRATCH,
-    };
-
-    rc = boot_go(&req, &rsp);
-    assert(rc == 0);
-
-    /* Perform jump to address indicated by the response object. */
-
-    return 0;
-}
-
-
-*** DEPENDENCIES
-    * nffs (for the boot vector and boot status files).
-    * os (for os_malloc() and os_free()).

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/bootutil/include/bootutil/bootutil_misc.h
----------------------------------------------------------------------
diff --git a/libs/bootutil/include/bootutil/bootutil_misc.h b/libs/bootutil/include/bootutil/bootutil_misc.h
deleted file mode 100644
index 2e3049d..0000000
--- a/libs/bootutil/include/bootutil/bootutil_misc.h
+++ /dev/null
@@ -1,28 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 __BOOTUTIL_MISC_H_
-#define __BOOTUTIL_MISC_H_
-
-int boot_vect_read_test(int *slot);
-int boot_vect_read_main(int *slot);
-int boot_vect_write_test(int slot);
-int boot_vect_write_main(void);
-
-#endif /*  __BOOTUTIL_MISC_H_ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/bootutil/include/bootutil/bootutil_test.h
----------------------------------------------------------------------
diff --git a/libs/bootutil/include/bootutil/bootutil_test.h b/libs/bootutil/include/bootutil/bootutil_test.h
deleted file mode 100644
index 55c8a67..0000000
--- a/libs/bootutil/include/bootutil/bootutil_test.h
+++ /dev/null
@@ -1,25 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 H_BOOTUTIL_TEST_
-#define H_BOOTUTIL_TEST_
-
-int boot_test_all(void);
-
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/bootutil/include/bootutil/image.h
----------------------------------------------------------------------
diff --git a/libs/bootutil/include/bootutil/image.h b/libs/bootutil/include/bootutil/image.h
deleted file mode 100644
index 0974d5b..0000000
--- a/libs/bootutil/include/bootutil/image.h
+++ /dev/null
@@ -1,89 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 H_IMAGE_
-#define H_IMAGE_
-
-#include <inttypes.h>
-
-#define IMAGE_MAGIC                 0x96f3b83c
-#define IMAGE_MAGIC_NONE            0xffffffff
-
-/*
- * Image header flags.
- */
-#define IMAGE_F_PIC                   0x00000001
-#define IMAGE_F_SHA256                0x00000002	/* Image contains hash TLV */
-#define IMAGE_F_PKCS15_RSA2048_SHA256 0x00000004 /* PKCS15 w/RSA and SHA */
-#define IMAGE_F_ECDSA224_SHA256       0x00000008  /* ECDSA256 over SHA256 */
-#define IMAGE_F_NON_BOOTABLE          0x00000010
-#define IMAGE_HEADER_SIZE           32
-
-/*
- * Image trailer TLV types.
- */
-#define IMAGE_TLV_SHA256            1	/* SHA256 of image hdr and body */
-#define IMAGE_TLV_RSA2048           2	/* RSA2048 of hash output */
-#define IMAGE_TLV_ECDSA224          3   /* ECDSA of hash output */
-
-struct image_version {
-    uint8_t iv_major;
-    uint8_t iv_minor;
-    uint16_t iv_revision;
-    uint32_t iv_build_num;
-};
-
-#define IMAGE_SIZE(hdr)                                                 \
-    ((hdr)->ih_tlv_size + (hdr)->ih_hdr_size + (hdr)->ih_img_size)
-
-/** Image header.  All fields are in little endian byte order. */
-struct image_header {
-    uint32_t ih_magic;
-    uint16_t ih_tlv_size; /* Trailing TLVs */
-    uint8_t  ih_key_id;
-    uint8_t  _pad1;
-    uint16_t ih_hdr_size;
-    uint16_t _pad2;
-    uint32_t ih_img_size; /* Does not include header. */
-    uint32_t ih_flags;
-    struct image_version ih_ver;
-    uint32_t _pad3;
-};
-
-/** Image trailer TLV format. All fields in little endian. */
-struct image_tlv {
-    uint8_t  it_type;
-    uint8_t  _pad;
-    uint16_t it_len;
-};
-
-struct boot_image_location {
-    uint8_t bil_flash_id;
-    uint32_t bil_address;
-};
-
-
-_Static_assert(sizeof(struct image_header) == IMAGE_HEADER_SIZE,
-               "struct image_header not required size");
-
-int bootutil_img_validate(struct image_header *hdr, uint8_t flash_id,
-                        uint32_t addr, uint8_t *tmp_buf, uint32_t tmp_buf_sz,
-                        uint8_t *seed, int seed_len, uint8_t *out_hash);
-
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/bootutil/include/bootutil/loader.h
----------------------------------------------------------------------
diff --git a/libs/bootutil/include/bootutil/loader.h b/libs/bootutil/include/bootutil/loader.h
deleted file mode 100644
index 75e0d01..0000000
--- a/libs/bootutil/include/bootutil/loader.h
+++ /dev/null
@@ -1,84 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 H_LOADER_
-#define H_LOADER_
-
-#include <inttypes.h>
-struct image_header;
-
-/** A request object instructing the boot loader how to proceed. */
-struct boot_req {
-    /**
-     * Array of area descriptors indicating the layout of flash(es); must
-     * be terminated with a 0-length element.
-     */
-    struct flash_area *br_area_descs;
-
-    /**
-     * Array of indices of elements in the br_area_descs array; indicates which
-     * areas represent the beginning of an image slot.  These are indices
-     * to br_area_descs array.
-     */
-    uint8_t *br_slot_areas;
-
-    /**
-     * The number of image areas (i.e., the size of the br_image_areas array).
-     */
-    uint8_t br_num_image_areas;
-
-    /** The area to use as the image scratch area, index is
-	index to br_area_descs array, of the  */
-    uint8_t br_scratch_area_idx;
-
-    /** Size of the image slot */
-    uint32_t br_img_sz;
-};
-
-/**
- * A response object provided by the boot loader code; indicates where to jump
- * to execute the main image.
- */
-struct boot_rsp {
-    /** A pointer to the header of the image to be executed. */
-    const struct image_header *br_hdr;
-
-    /**
-     * The flash offset of the image to execute.  Indicates the position of
-     * the image header.
-     */
-    uint8_t br_flash_id;
-    uint32_t br_image_addr;
-};
-
-/* you must have pre-allocated all the entries within this structure */
-int
-boot_build_request(struct boot_req *preq, int area_descriptor_max);
-
-int
-boot_go(const struct boot_req *req, struct boot_rsp *rsp);
-
-
-#define SPLIT_GO_OK                 (0)
-#define SPLIT_GO_NON_MATCHING       (-1)
-#define SPLIT_GO_ERR                (-2)
-int
-split_go(int loader_slot, int split_slot, void **entry);
-
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/bootutil/include/bootutil/sign_key.h
----------------------------------------------------------------------
diff --git a/libs/bootutil/include/bootutil/sign_key.h b/libs/bootutil/include/bootutil/sign_key.h
deleted file mode 100644
index 5ccda90..0000000
--- a/libs/bootutil/include/bootutil/sign_key.h
+++ /dev/null
@@ -1,33 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 __BOOTUTIL_SIGN_KEY_H_
-#define __BOOTUTIL_SIGN_KEY_H_
-
-#include <stdint.h>
-
-struct bootutil_key {
-    const uint8_t *key;
-    const unsigned int *len;
-};
-
-extern const struct bootutil_key bootutil_keys[];
-extern const int bootutil_key_cnt;
-
-#endif /* __BOOTUTIL_SIGN_KEY_H_ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/bootutil/pkg.yml
----------------------------------------------------------------------
diff --git a/libs/bootutil/pkg.yml b/libs/bootutil/pkg.yml
deleted file mode 100644
index 390610a..0000000
--- a/libs/bootutil/pkg.yml
+++ /dev/null
@@ -1,41 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you 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.
-#
-
-pkg.name: libs/bootutil
-pkg.description: The bootutil library performs most of the functions of a boot loader.
-pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
-pkg.homepage: "http://mynewt.apache.org/"
-pkg.keywords:
-    - boot
-    - bootloader
-
-pkg.deps: 
-    - hw/hal
-    - crypto/mbedtls
-    - libs/os 
-
-pkg.syscfg_defs:
-    BOOTUTIL_SIGN_RSA:
-        description: 'TBD'
-        value: '0'
-    BOOTUTIL_SIGN_EC:
-        description: 'TBD'
-        value: '0'
-pkg.cflags.IMAGE_KEYS_RSA: -DIMAGE_SIGNATURES_RSA
-pkg.cflags.IMAGE_KEYS_EC: -DIMAGE_SIGNATURES_EC

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/bootutil/signed_images.md
----------------------------------------------------------------------
diff --git a/libs/bootutil/signed_images.md b/libs/bootutil/signed_images.md
deleted file mode 100644
index 39792ea..0000000
--- a/libs/bootutil/signed_images.md
+++ /dev/null
@@ -1,91 +0,0 @@
-<!--
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you 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.
-#
--->
-
-## Image signing
-
-This signs the image by computing hash over the image, and then
-signing that hash. Signature is computed by newt tool when it's
-creating the image. This signature is placed in the image trailer.
-
-The public key of this keypair must be included in the bootloader,
-as it verifies it before allowing the image to run.
-
-This facility allows you to use multiple signing keys. This would
-be useful when you want to prevent production units from booting
-development images, but want development units to be able to boot
-both production images and development images.
-
-## Creating signing keys
-First you need a keypair to use for signing. You can create
-one with openssl command line tool.
-
-openssl genrsa -out image_sign.pem 2048
-
-This created a file which contains both the private and public key,
-and will be used when signing images.
-
-Then you need to extract the public key from this to include it
-in the bootloader. Bootloader need to keep key parsing minimal,
-so it expects simple key format.
-
-openssl rsa -in image_sign.pem -pubout -out image_sign_pub.der -outform DER -RSAPublicKey_out
-
-Now the public key is in file called image_sign_pub.der.
-
-## Creating a key package
-
-xxd -i image_sign_pub.der image_sign_pub.c.import
-
-Then you need to create a package containing this key, or keys.
-In the pkg.yml for this package, you advertise feature IMAGE_KEYS_RSA or
-IMAGE_KEYS_EC.
-Once this is done, bootloader will expect keys to be filled in
-'bootutil_keys', and the number of keys to be in 'bootutil_key_cnt'.
-
-## Sample pkg.yml
-This gets bootutil to turn on image signature validation.
-
-    pkg.name: libs/mykeys
-    pkg.deps:
-        - libs/bootutil
-    pkg.features.bootloader:
-        - IMAGE_KEYS_RSA
-
-## Sample source file
-This exports the keys.
-
-    #include <bootutil/sign_key.h>
-
-    #include "image_sign_pub.c.import"
-
-    const struct bootutil_key bootutil_keys[] = {
-        [0] = {
-            .key = image_sign_pub_der,
-            .len = &image_sign_pub_der_len,
-        }
-    };
-
-    const int bootutil_key_cnt = sizeof(bootutil_keys) / sizeof(bootutil_keys[0]);
-
-## Building bootloader
-
-After you've created the key package, you must include it in the build
-for bootloader. So modify the pkg.yml for apps/boot to include it.

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/bootutil/src/bootutil_misc.c
----------------------------------------------------------------------
diff --git a/libs/bootutil/src/bootutil_misc.c b/libs/bootutil/src/bootutil_misc.c
deleted file mode 100644
index f64d2a4..0000000
--- a/libs/bootutil/src/bootutil_misc.c
+++ /dev/null
@@ -1,319 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include <assert.h>
-#include <string.h>
-#include <inttypes.h>
-
-#include "syscfg/syscfg.h"
-#include "hal/hal_bsp.h"
-#include "hal/hal_flash.h"
-#include "hal/flash_map.h"
-#include "os/os.h"
-#include "bootutil/image.h"
-#include "bootutil/loader.h"
-#include "bootutil/bootutil_misc.h"
-#include "bootutil_priv.h"
-
-/*
- * Read the image trailer from a given slot.
- */
-static int
-boot_vect_read_img_trailer(int slot, struct boot_img_trailer *bit)
-{
-    int rc;
-    const struct flash_area *fap;
-    uint32_t off;
-
-    rc = flash_area_open(slot, &fap);
-    if (rc) {
-        return rc;
-    }
-    off = fap->fa_size - sizeof(struct boot_img_trailer);
-    rc = flash_area_read(fap, off, bit, sizeof(*bit));
-    flash_area_close(fap);
-
-    return rc;
-}
-
-/**
- * Retrieves from the slot number of the test image (i.e.,
- * the image that has not been proven stable, and which will only run once).
- *
- * @param slot              On success, the slot number of image to boot.
- *
- * @return                  0 on success; nonzero on failure.
- */
-int
-boot_vect_read_test(int *slot)
-{
-    struct boot_img_trailer bit;
-    int i;
-    int rc;
-
-    for (i = FLASH_AREA_IMAGE_0; i <= FLASH_AREA_IMAGE_1; i++) {
-        if (i == bsp_imgr_current_slot()) {
-            continue;
-        }
-        rc = boot_vect_read_img_trailer(i, &bit);
-        if (rc) {
-            continue;
-        }
-        if (bit.bit_copy_start == BOOT_IMG_MAGIC) {
-            *slot = i;
-            return 0;
-        }
-    }
-    return -1;
-}
-
-/**
- * Retrieves from the slot number of the main image. If this is
- * different from test image slot, next restart will revert to main.
- *
- * @param out_ver           On success, the main version gets written here.
- *
- * @return                  0 on success; nonzero on failure.
- */
-int
-boot_vect_read_main(int *slot)
-{
-    int rc;
-    struct boot_img_trailer bit;
-
-    rc = boot_vect_read_img_trailer(FLASH_AREA_IMAGE_0, &bit);
-    assert(rc == 0);
-
-    if (bit.bit_copy_start != BOOT_IMG_MAGIC || bit.bit_img_ok != 0xff) {
-        /*
-         * If there never was copy that took place, or if the current
-         * image has been marked good, we'll keep booting it.
-         */
-        *slot = FLASH_AREA_IMAGE_0;
-    } else {
-        *slot = FLASH_AREA_IMAGE_1;
-    }
-    return 0;
-}
-
-/**
- * Write the test image version number from the boot vector.
- *
- * @return                  0 on success; nonzero on failure.
- */
-int
-boot_vect_write_test(int slot)
-{
-    const struct flash_area *fap;
-    uint32_t off;
-    uint32_t magic;
-    int rc;
-
-    rc = flash_area_open(slot, &fap);
-    if (rc) {
-        return rc;
-    }
-
-    off = fap->fa_size - sizeof(struct boot_img_trailer);
-    magic = BOOT_IMG_MAGIC;
-
-    rc = flash_area_write(fap, off, &magic, sizeof(magic));
-    flash_area_close(fap);
-
-    return rc;
-}
-
-/**
- * Deletes the main image version number from the boot vector.
- * This must be called by the app to confirm that it is ok to keep booting
- * to this image.
- *
- * @return                  0 on success; nonzero on failure.
- */
-int
-boot_vect_write_main(void)
-{
-    const struct flash_area *fap;
-    uint32_t off;
-    int rc;
-    uint8_t val;
-
-    /*
-     * Write to slot 0.
-     */
-    rc = flash_area_open(FLASH_AREA_IMAGE_0, &fap);
-    if (rc) {
-        return rc;
-    }
-
-    off = fap->fa_size - sizeof(struct boot_img_trailer);
-    off += (sizeof(uint32_t) + sizeof(uint8_t));
-    rc = flash_area_read(fap, off, &val, sizeof(val));
-    if (!rc && val == 0xff) {
-        val = 0;
-        rc = flash_area_write(fap, off, &val, sizeof(val));
-    }
-    return rc;
-}
-
-/**
- * Reads the header of image present in flash.  Header corresponding to
- * empty image slot is filled with 0xff bytes.
- *
- * @param out_headers           Points to an array of image headers.  Each
- *                                  element is filled with the header of the
- *                                  corresponding image in flash.
- * @param addresses             An array containing the flash addresses of each
- *                                  image slot.
- * @param num_addresses         The number of headers to read.  This should
- *                                  also be equal to the lengths of the
- *                                  out_headers and addresses arrays.
- */
-int
-boot_read_image_header(struct boot_image_location *loc,
-                       struct image_header *out_hdr)
-{
-    int rc;
-
-    rc = hal_flash_read(loc->bil_flash_id, loc->bil_address, out_hdr,
-                        sizeof *out_hdr);
-    if (rc != 0) {
-        rc = BOOT_EFLASH;
-    } else if (out_hdr->ih_magic != IMAGE_MAGIC) {
-        rc = BOOT_EBADIMAGE;
-    }
-
-    if (rc) {
-        memset(out_hdr, 0xff, sizeof(*out_hdr));
-    }
-    return rc;
-}
-
-/*
- * How far has the copy progressed?
- */
-static void
-boot_read_status_bytes(struct boot_status *bs, uint8_t flash_id, uint32_t off)
-{
-    uint8_t status;
-
-    assert(bs->elem_sz);
-    off -= bs->elem_sz * 2;
-    while (1) {
-        hal_flash_read(flash_id, off, &status, sizeof(status));
-        if (status == 0xff) {
-            break;
-        }
-        off -= bs->elem_sz;
-        if (bs->state == 2) {
-            bs->idx++;
-            bs->state = 0;
-        } else {
-            bs->state++;
-        }
-    }
-}
-
-/**
- * Reads the boot status from the flash.  The boot status contains
- * the current state of an interrupted image copy operation.  If the boot
- * status is not present, or it indicates that previous copy finished,
- * there is no operation in progress.
- */
-int
-boot_read_status(struct boot_status *bs)
-{
-    struct boot_img_trailer bit;
-    uint8_t flash_id;
-    uint32_t off;
-
-    /*
-     * Check if boot_img_trailer is in scratch, or at the end of slot0.
-     */
-    boot_slot_magic(0, &bit);
-    if (bit.bit_copy_start == BOOT_IMG_MAGIC && bit.bit_copy_done == 0xff) {
-        boot_magic_loc(0, &flash_id, &off);
-        boot_read_status_bytes(bs, flash_id, off);
-        return 1;
-    }
-    boot_scratch_magic(&bit);
-    if (bit.bit_copy_start == BOOT_IMG_MAGIC && bit.bit_copy_done == 0xff) {
-        boot_scratch_loc(&flash_id, &off);
-        boot_read_status_bytes(bs, flash_id, off);
-        return 1;
-    }
-    return 0;
-}
-
-
-/**
- * Writes the supplied boot status to the flash file system.  The boot status
- * contains the current state of an in-progress image copy operation.
- *
- * @param bs                    The boot status to write.
- *
- * @return                      0 on success; nonzero on failure.
- */
-int
-boot_write_status(struct boot_status *bs)
-{
-    uint32_t off;
-    uint8_t flash_id;
-    uint8_t val;
-
-    if (bs->idx == 0) {
-        /*
-         * Write to scratch
-         */
-        boot_scratch_loc(&flash_id, &off);
-    } else {
-        /*
-         * Write to slot 0;
-         */
-        boot_magic_loc(0, &flash_id, &off);
-    }
-    off -= ((3 * bs->elem_sz) * bs->idx + bs->elem_sz * (bs->state + 1));
-
-    val = bs->state;
-    hal_flash_write(flash_id, off, &val, sizeof(val));
-
-    return 0;
-}
-
-/**
- * Finalizes the copy-in-progress status on the flash.  The boot status
- * contains the current state of an in-progress image copy operation.  By
- * clearing this, it is implied that there is no copy operation in
- * progress.
- */
-void
-boot_clear_status(void)
-{
-    uint32_t off;
-    uint8_t val = 0;
-    uint8_t flash_id;
-
-    /*
-     * Write to slot 0; boot_img_trailer is the 8 bytes within image slot.
-     * Here we say that copy operation was finished.
-     */
-    boot_magic_loc(0, &flash_id, &off);
-    off += sizeof(uint32_t);
-    hal_flash_write(flash_id, off, &val, sizeof(val));
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/bootutil/src/bootutil_priv.h
----------------------------------------------------------------------
diff --git a/libs/bootutil/src/bootutil_priv.h b/libs/bootutil/src/bootutil_priv.h
deleted file mode 100644
index e5b231c..0000000
--- a/libs/bootutil/src/bootutil_priv.h
+++ /dev/null
@@ -1,75 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 H_BOOTUTIL_PRIV_
-#define H_BOOTUTIL_PRIV_
-
-#include "bootutil/image.h"
-
-#define BOOT_EFLASH     1
-#define BOOT_EFILE      2
-#define BOOT_EBADIMAGE  3
-#define BOOT_EBADVECT   4
-#define BOOT_EBADSTATUS 5
-#define BOOT_ENOMEM     6
-#define BOOT_EBADARGS   7
-
-#define BOOT_TMPBUF_SZ  256
-
-
-
-/*
- * Maintain state of copy progress.
- */
-struct boot_status {
-    uint32_t idx;       /* Which area we're operating on */
-    uint8_t elem_sz;    /* Size of the status element to write in bytes */
-    uint8_t state;      /* Which part of the swapping process are we at */
-};
-
-/*
- * End-of-image slot data structure.
- */
-#define BOOT_IMG_MAGIC  0x12344321
-struct boot_img_trailer {
-    uint32_t bit_copy_start;
-    uint8_t  bit_copy_done;
-    uint8_t  bit_img_ok;
-    uint16_t _pad;
-};
-
-int bootutil_verify_sig(uint8_t *hash, uint32_t hlen, uint8_t *sig, int slen,
-    uint8_t key_id);
-
-int boot_read_image_header(struct boot_image_location *loc,
-  struct image_header *out_hdr);
-int boot_write_status(struct boot_status *bs);
-int boot_read_status(struct boot_status *bs);
-void boot_clear_status(void);
-
-void boot_magic_loc(int slot_num, uint8_t *flash_id, uint32_t *off);
-void boot_scratch_loc(uint8_t *flash_id, uint32_t *off);
-void boot_slot_magic(int slot_num, struct boot_img_trailer *bit);
-void boot_scratch_magic(struct boot_img_trailer *bit);
-
-struct boot_req;
-void boot_req_set(struct boot_req *req);
-
-#endif
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/bootutil/src/image_ec.c
----------------------------------------------------------------------
diff --git a/libs/bootutil/src/image_ec.c b/libs/bootutil/src/image_ec.c
deleted file mode 100644
index f3adfcf..0000000
--- a/libs/bootutil/src/image_ec.c
+++ /dev/null
@@ -1,121 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include "syscfg/syscfg.h"
-
-#if MYNEWT_VAL(BOOTUTIL_SIGN_EC)
-#include "bootutil/sign_key.h"
-
-#include "mbedtls/sha256.h"
-#include "mbedtls/ecdsa.h"
-#include "mbedtls/oid.h"
-#include "mbedtls/asn1.h"
-
-#include "bootutil_priv.h"
-
-/*
- * Declaring these like this adds NULL termination.
- */
-static const uint8_t ec_pubkey_oid[] = MBEDTLS_OID_EC_ALG_UNRESTRICTED;
-static const uint8_t ec_secp224r1_oid[] = MBEDTLS_OID_EC_GRP_SECP224R1;
-
-/*
- * Parse the public key used for signing. Simple RSA format.
- */
-static int
-bootutil_parse_eckey(mbedtls_ecdsa_context *ctx, uint8_t **p, uint8_t *end)
-{
-    size_t len;
-    mbedtls_asn1_buf alg;
-    mbedtls_asn1_buf param;
-
-    if (mbedtls_asn1_get_tag(p, end, &len,
-        MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) {
-        return -1;
-    }
-    end = *p + len;
-
-    if (mbedtls_asn1_get_alg(p, end, &alg, &param)) {
-        return -2;
-    }
-    if (alg.len != sizeof(ec_pubkey_oid) - 1 ||
-      memcmp(alg.p, ec_pubkey_oid, sizeof(ec_pubkey_oid) - 1)) {
-        return -3;
-    }
-    if (param.len != sizeof(ec_secp224r1_oid) - 1||
-      memcmp(param.p, ec_secp224r1_oid, sizeof(ec_secp224r1_oid) - 1)) {
-        return -4;
-    }
-
-    if (mbedtls_ecp_group_load_secp224r1(&ctx->grp)) {
-        return -5;
-    }
-
-    if (mbedtls_asn1_get_bitstring_null(p, end, &len)) {
-        return -6;
-    }
-    if (*p + len != end) {
-        return -7;
-    }
-
-    if (mbedtls_ecp_point_read_binary(&ctx->grp, &ctx->Q, *p, end - *p)) {
-        return -8;
-    }
-
-    if (mbedtls_ecp_check_pubkey(&ctx->grp, &ctx->Q)) {
-        return -9;
-    }
-    return 0;
-}
-
-static int
-bootutil_cmp_sig(mbedtls_ecdsa_context *ctx, uint8_t *hash, uint32_t hlen,
-  uint8_t *sig, int slen)
-{
-    return mbedtls_ecdsa_read_signature(ctx, hash, hlen, sig, slen);
-}
-
-int
-bootutil_verify_sig(uint8_t *hash, uint32_t hlen, uint8_t *sig, int slen,
-  uint8_t key_id)
-{
-    int rc;
-    uint8_t *cp;
-    uint8_t *end;
-    mbedtls_ecdsa_context ctx;
-
-    mbedtls_ecdsa_init(&ctx);
-
-    cp = (uint8_t *)bootutil_keys[key_id].key;
-    end = cp + *bootutil_keys[key_id].len;
-
-    rc = bootutil_parse_eckey(&ctx, &cp, end);
-    if (rc) {
-        return -1;
-    }
-
-    while (sig[slen - 1] == '\0') {
-        slen--;
-    }
-    rc = bootutil_cmp_sig(&ctx, hash, hlen, sig, slen);
-    mbedtls_ecdsa_free(&ctx);
-
-    return rc;
-}
-#endif /* MYNEWT_VAL(BOOTUTIL_SIGN_EC) */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/bootutil/src/image_rsa.c
----------------------------------------------------------------------
diff --git a/libs/bootutil/src/image_rsa.c b/libs/bootutil/src/image_rsa.c
deleted file mode 100644
index e556092..0000000
--- a/libs/bootutil/src/image_rsa.c
+++ /dev/null
@@ -1,144 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include "syscfg/syscfg.h"
-
-#if MYNEWT_VAL(BOOTUTIL_SIGN_RSA)
-#include "bootutil/sign_key.h"
-
-#include "mbedtls/rsa.h"
-#include "mbedtls/asn1.h"
-
-#include "bootutil_priv.h"
-
-static const uint8_t sha256_oid[] = {
-    0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
-    0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05,
-    0x00, 0x04, 0x20
-};
-
-/*
- * Parse the public key used for signing. Simple RSA format.
- */
-static int
-bootutil_parse_rsakey(mbedtls_rsa_context *ctx, uint8_t **p, uint8_t *end)
-{
-    int rc;
-    size_t len;
-
-    if ((rc = mbedtls_asn1_get_tag(p, end, &len,
-          MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
-        return -1;
-    }
-
-    if (*p + len != end) {
-        return -2;
-    }
-
-    if ((rc = mbedtls_asn1_get_mpi(p, end, &ctx->N)) != 0 ||
-      (rc = mbedtls_asn1_get_mpi(p, end, &ctx->E)) != 0) {
-        return -3;
-    }
-
-    if (*p != end) {
-        return -4;
-    }
-
-    if ((rc = mbedtls_rsa_check_pubkey(ctx)) != 0) {
-        return -5;
-    }
-
-    ctx->len = mbedtls_mpi_size(&ctx->N);
-
-    return 0;
-}
-
-/*
- * PKCS1.5 using RSA2048 computed over SHA256.
- */
-static int
-bootutil_cmp_rsasig(mbedtls_rsa_context *ctx, uint8_t *hash, uint32_t hlen,
-  uint8_t *sig)
-{
-    uint8_t buf[MBEDTLS_MPI_MAX_SIZE];
-    uint8_t *p;
-
-    if (ctx->len != 256) {
-        return -1;
-    }
-
-    if (mbedtls_rsa_public(ctx, sig, buf)) {
-        return -1;
-    }
-
-    p = buf;
-
-    if (*p++ != 0 || *p++ != MBEDTLS_RSA_SIGN) {
-        return -1;
-    }
-
-    while (*p != 0) {
-        if (p >= buf + ctx->len - 1 || *p != 0xFF) {
-            return -1;
-        }
-        p++;
-    }
-    p++;
-
-    if ((p - buf) + sizeof(sha256_oid) + hlen != ctx->len) {
-        return -1;
-    }
-
-    if (memcmp(p, sha256_oid, sizeof(sha256_oid))) {
-        return -1;
-    }
-    p += sizeof(sha256_oid);
-
-    if (memcmp(p, hash, hlen)) {
-        return -1;
-    }
-
-    return 0;
-}
-
-int
-bootutil_verify_sig(uint8_t *hash, uint32_t hlen, uint8_t *sig, int slen,
-  uint8_t key_id)
-{
-    mbedtls_rsa_context ctx;
-    int rc;
-    uint8_t *cp;
-    uint8_t *end;
-
-    mbedtls_rsa_init(&ctx, 0, 0);
-
-    cp = (uint8_t *)bootutil_keys[key_id].key;
-    end = cp + *bootutil_keys[key_id].len;
-
-    rc = bootutil_parse_rsakey(&ctx, &cp, end);
-    if (rc || slen != ctx.len) {
-        mbedtls_rsa_free(&ctx);
-        return rc;
-    }
-    rc = bootutil_cmp_rsasig(&ctx, hash, hlen, sig);
-    mbedtls_rsa_free(&ctx);
-
-    return rc;
-}
-#endif /* MYNEWT_VAL(BOOTUTIL_SIGN_RSA) */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/bootutil/src/image_validate.c
----------------------------------------------------------------------
diff --git a/libs/bootutil/src/image_validate.c b/libs/bootutil/src/image_validate.c
deleted file mode 100644
index 3793948..0000000
--- a/libs/bootutil/src/image_validate.c
+++ /dev/null
@@ -1,198 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include <assert.h>
-#include <stddef.h>
-#include <inttypes.h>
-#include <string.h>
-
-#include "syscfg/syscfg.h"
-#include "hal/hal_flash.h"
-#include "bootutil/image.h"
-#include "bootutil/sign_key.h"
-
-#include "mbedtls/sha256.h"
-#include "mbedtls/rsa.h"
-#include "mbedtls/ecdsa.h"
-#include "mbedtls/asn1.h"
-
-#include "bootutil_priv.h"
-
-/*
- * Compute SHA256 over the image.
- */
-static int
-bootutil_img_hash(struct image_header *hdr, uint8_t flash_id, uint32_t addr,
-  uint8_t *tmp_buf, uint32_t tmp_buf_sz, uint8_t *hash_result, uint8_t *seed, int seed_len)
-{
-    mbedtls_sha256_context sha256_ctx;
-    uint32_t blk_sz;
-    uint32_t size;
-    uint32_t off;
-    int rc;
-
-    mbedtls_sha256_init(&sha256_ctx);
-    mbedtls_sha256_starts(&sha256_ctx, 0);
-
-    /* in some cases (split image) the hash is seeded with data from
-     * the loader image */
-    if(seed && (seed_len > 0)) {
-        mbedtls_sha256_update(&sha256_ctx, seed, seed_len);
-    }
-
-    size = hdr->ih_img_size + hdr->ih_hdr_size;
-
-    /*
-     * Hash is computed over image header and image itself. No TLV is
-     * included ATM.
-     */
-    size = hdr->ih_img_size + hdr->ih_hdr_size;
-    for (off = 0; off < size; off += blk_sz) {
-        blk_sz = size - off;
-        if (blk_sz > tmp_buf_sz) {
-            blk_sz = tmp_buf_sz;
-        }
-        rc = hal_flash_read(flash_id, addr + off, tmp_buf, blk_sz);
-        if (rc) {
-            return rc;
-        }
-        mbedtls_sha256_update(&sha256_ctx, tmp_buf, blk_sz);
-    }
-    mbedtls_sha256_finish(&sha256_ctx, hash_result);
-
-    return 0;
-}
-
-/*
- * Verify the integrity of the image.
- * Return non-zero if image could not be validated/does not validate.
- */
-int
-bootutil_img_validate(struct image_header *hdr, uint8_t flash_id, uint32_t addr,
-  uint8_t *tmp_buf, uint32_t tmp_buf_sz, uint8_t *seed, int seed_len, uint8_t *out_hash)
-{
-    uint32_t off;
-    uint32_t size;
-    uint32_t sha_off = 0;
-#if MYNEWT_VAL(BOOTUTIL_SIGN_RSA) || MYNEWT_VAL(BOOTUTIL_SIGN_EC)
-    uint32_t sig_off = 0;
-    uint32_t sig_len = 0;
-#endif
-    struct image_tlv tlv;
-    uint8_t buf[256];
-    uint8_t hash[32];
-    int rc;
-
-#if MYNEWT_VAL(BOOTUTIL_SIGN_RSA)
-    if ((hdr->ih_flags & IMAGE_F_PKCS15_RSA2048_SHA256) == 0) {
-        return -1;
-    }
-#endif
-#if MYNEWT_VAL(BOOTUTIL_SIGN_EC)
-    if ((hdr->ih_flags & IMAGE_F_ECDSA224_SHA256) == 0) {
-        return -1;
-    }
-#endif
-    if ((hdr->ih_flags & IMAGE_F_SHA256) == 0) {
-        return -1;
-    }
-
-    rc = bootutil_img_hash(hdr, flash_id, addr, tmp_buf, tmp_buf_sz, hash, seed, seed_len);
-    if (rc) {
-        return rc;
-    }
-
-    if(out_hash) {
-        memcpy(out_hash, hash, 32);
-    }
-
-    /*
-     * After image there's TLVs.
-     */
-    off = hdr->ih_img_size + hdr->ih_hdr_size;
-    size = off + hdr->ih_tlv_size;
-
-    for (; off < size; off += sizeof(tlv) + tlv.it_len) {
-        rc = hal_flash_read(flash_id, addr + off, &tlv, sizeof(tlv));
-        if (rc) {
-            return rc;
-        }
-        if (tlv.it_type == IMAGE_TLV_SHA256) {
-            if (tlv.it_len != sizeof(hash)) {
-                return -1;
-            }
-            sha_off = addr + off + sizeof(tlv);
-        }
-#if MYNEWT_VAL(BOOTUTIL_SIGN_RSA)
-        if (tlv.it_type == IMAGE_TLV_RSA2048) {
-            if (tlv.it_len != 256) { /* 2048 bits */
-                return -1;
-            }
-            sig_off = addr + off + sizeof(tlv);
-            sig_len = tlv.it_len;
-        }
-#endif
-#if MYNEWT_VAL(BOOTUTIL_SIGN_EC)
-        if (tlv.it_type == IMAGE_TLV_ECDSA224) {
-            if (tlv.it_len < 64) { /* oids + 2 * 28 bytes */
-                return -1;
-            }
-            sig_off = addr + off + sizeof(tlv);
-            sig_len = tlv.it_len;
-        }
-#endif
-    }
-    if (hdr->ih_flags & IMAGE_F_SHA256) {
-        if (!sha_off) {
-            /*
-             * Header said there should be hash TLV, no TLV found.
-             */
-            return -1;
-        }
-        rc = hal_flash_read(flash_id, sha_off, buf, sizeof(hash));
-        if (rc) {
-            return rc;
-        }
-        if (memcmp(hash, buf, sizeof(hash))) {
-            return -1;
-        }
-    }
-#if MYNEWT_VAL(BOOTUTIL_SIGN_RSA) || MYNEWT_VAL(BOOTUTIL_SIGN_EC)
-    if (!sig_off) {
-        /*
-         * Header said there should be PKCS1.v5 signature, no TLV
-         * found.
-         */
-        return -1;
-    }
-    rc = hal_flash_read(flash_id, sig_off, buf, sig_len);
-    if (rc) {
-        return -1;
-    }
-
-    if (hdr->ih_key_id >= bootutil_key_cnt) {
-        return -1;
-    }
-    rc = bootutil_verify_sig(hash, sizeof(hash), buf, sig_len, hdr->ih_key_id);
-    if (rc) {
-        return -1;
-    }
-#endif
-    return 0;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/bootutil/src/loader.c
----------------------------------------------------------------------
diff --git a/libs/bootutil/src/loader.c b/libs/bootutil/src/loader.c
deleted file mode 100644
index e2d4cfa..0000000
--- a/libs/bootutil/src/loader.c
+++ /dev/null
@@ -1,652 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include <assert.h>
-#include <stddef.h>
-#include <inttypes.h>
-#include <stdlib.h>
-#include <string.h>
-#include <hal/flash_map.h>
-#include <hal/hal_flash.h>
-#include <os/os_malloc.h>
-#include "bootutil/loader.h"
-#include "bootutil/image.h"
-#include "bootutil/bootutil_misc.h"
-#include "bootutil_priv.h"
-
-/** Number of image slots in flash; currently limited to two. */
-#define BOOT_NUM_SLOTS              2
-
-/** The request object provided by the client. */
-static const struct boot_req *boot_req;
-
-/** Info about image slots. */
-static struct boot_img {
-    struct image_header hdr;
-    struct boot_image_location loc;
-    uint32_t area;
-} boot_img[BOOT_NUM_SLOTS];
-
-static struct boot_status boot_state;
-
-static int boot_erase_area(int area_idx, uint32_t sz);
-static uint32_t boot_copy_sz(int max_idx, int *cnt);
-
-
-int
-boot_build_request(struct boot_req *preq, int area_descriptor_max)
-{
-    int cnt;
-    int total;
-    int rc;
-    const struct flash_area *fap;
-    struct flash_area *descs = preq->br_area_descs;
-    uint8_t *img_starts = preq->br_slot_areas;
-
-    cnt = area_descriptor_max;
-    rc = flash_area_to_sectors(FLASH_AREA_IMAGE_0, &cnt, descs);
-    img_starts[0] = 0;
-    total = cnt;
-
-    flash_area_open(FLASH_AREA_IMAGE_0, &fap);
-    preq->br_img_sz = fap->fa_size;
-
-    cnt = area_descriptor_max - total;
-    if( cnt < 0) {
-        return -1;
-    }
-
-    rc = flash_area_to_sectors(FLASH_AREA_IMAGE_1, &cnt, &descs[total]);
-    if(rc != 0) {
-        return -2;
-    }
-    img_starts[1] = total;
-    total += cnt;
-
-    cnt = area_descriptor_max - total;
-    if( cnt < 0) {
-        return -3;
-    }
-
-    rc = flash_area_to_sectors(FLASH_AREA_IMAGE_SCRATCH, &cnt, &descs[total]);
-    if(rc != 0) {
-        return -4;
-    }
-
-    preq->br_scratch_area_idx = total;
-    total += cnt;
-    preq->br_num_image_areas = total;
-    return 0;
-}
-
-void
-boot_req_set(struct boot_req *req)
-{
-    boot_req = req;
-}
-
-/**
- * Calculates the flash offset of the specified image slot.
- *
- * @param slot_num              The number of the slot to calculate.
- * @param loc                   The flash location of the slot.
- *
- */
-static void
-boot_slot_addr(int slot_num, struct boot_image_location *loc)
-{
-    const struct flash_area *area_desc;
-    uint8_t area_idx;
-
-    area_idx = boot_req->br_slot_areas[slot_num];
-    area_desc = boot_req->br_area_descs + area_idx;
-    loc->bil_flash_id = area_desc->fa_flash_id;
-    loc->bil_address = area_desc->fa_off;
-}
-
-/*
- * Status about copy-in-progress is either in slot0 (target slot) or
- * in scratch area. It is in scratch area if the process is currently
- * moving the last sector within image.
- *
- * If the copy-in-progress status is within the image slot, it will
- * be at the end of the area.
- * If the sector containing the boot copy status is in scratch, it's
- * offset from beginning of scratch depends on how much of the image
- * fits inside the scratch area.
- *
- * We start copy from the end of image, so boot-copy-status is in
- * scratch when the first area is being moved. Otherwise it will be
- * in slot 0.
- */
-void
-boot_magic_loc(int slot_num, uint8_t *flash_id, uint32_t *off)
-{
-    struct boot_img *b;
-
-    b = &boot_img[slot_num];
-    *flash_id = b->loc.bil_flash_id;
-    *off = b->area + b->loc.bil_address - sizeof(struct boot_img_trailer);
-}
-
-void
-boot_scratch_loc(uint8_t *flash_id, uint32_t *off)
-{
-    struct flash_area *scratch;
-    int cnt;
-
-    scratch = &boot_req->br_area_descs[boot_req->br_scratch_area_idx];
-    *flash_id = scratch->fa_flash_id;
-
-    /*
-     * Calculate where the boot status would be, if it was copied to scratch.
-     */
-    *off = boot_copy_sz(boot_req->br_slot_areas[1], &cnt);
-    *off += (scratch->fa_off - sizeof(struct boot_img_trailer));
-}
-
-void
-boot_slot_magic(int slot_num, struct boot_img_trailer *bit)
-{
-    uint32_t off;
-    uint8_t flash_id;
-
-    boot_magic_loc(slot_num, &flash_id, &off);
-    memset(bit, 0xff, sizeof(*bit));
-    hal_flash_read(flash_id, off, bit, sizeof(*bit));
-}
-
-void
-boot_scratch_magic(struct boot_img_trailer *bit)
-{
-    uint32_t off;
-    uint8_t flash_id;
-
-    boot_scratch_loc(&flash_id, &off);
-    memset(bit, 0xff, sizeof(*bit));
-    hal_flash_read(flash_id, off, bit, sizeof(*bit));
-}
-
-/*
- * Gather info about image in a given slot.
- */
-void
-boot_image_info(void)
-{
-    int i;
-    struct boot_img *b;
-    struct flash_area *scratch;
-
-    for (i = 0; i < BOOT_NUM_SLOTS; i++) {
-        b = &boot_img[i];
-        boot_slot_addr(i, &b->loc);
-        boot_read_image_header(&b->loc, &b->hdr);
-        b->area = boot_req->br_img_sz;
-    }
-
-    /*
-     * Figure out what size to write update status update as.
-     * The size depends on what the minimum write size is for scratch
-     * area, active image slot. We need to use the bigger of those 2
-     * values.
-     */
-    boot_state.elem_sz = hal_flash_align(boot_img[0].loc.bil_flash_id);
-
-    scratch = &boot_req->br_area_descs[boot_req->br_scratch_area_idx];
-    i = hal_flash_align(scratch->fa_flash_id);
-    if (i > boot_state.elem_sz) {
-        boot_state.elem_sz = i;
-    }
-}
-
-static int
-boot_image_bootable(struct image_header *hdr) {
-    return ((hdr->ih_flags & IMAGE_F_NON_BOOTABLE) == 0);
-}
-
-/*
- * Validate image hash/signature in a slot.
- */
-static int
-boot_image_check(struct image_header *hdr, struct boot_image_location *loc)
-{
-    static void *tmpbuf;
-
-    if (!tmpbuf) {
-        tmpbuf = malloc(BOOT_TMPBUF_SZ);
-        if (!tmpbuf) {
-            return BOOT_ENOMEM;
-        }
-    }
-    if (bootutil_img_validate(hdr, loc->bil_flash_id, loc->bil_address,
-        tmpbuf, BOOT_TMPBUF_SZ, NULL, 0, NULL)) {
-        return BOOT_EBADIMAGE;
-    }
-    return 0;
-}
-
-
-static int
-split_image_check(struct image_header *app_hdr, struct boot_image_location *app_loc,
-                  struct image_header *loader_hdr, struct boot_image_location *loader_loc)
-{
-    static void *tmpbuf;
-    uint8_t loader_hash[32];
-
-    if (!tmpbuf) {
-        tmpbuf = malloc(BOOT_TMPBUF_SZ);
-        if (!tmpbuf) {
-            return BOOT_ENOMEM;
-        }
-    }
-    if (bootutil_img_validate(loader_hdr, loader_loc->bil_flash_id, loader_loc->bil_address,
-        tmpbuf, BOOT_TMPBUF_SZ, NULL, 0, loader_hash)) {
-        return BOOT_EBADIMAGE;
-    }
-
-    if (bootutil_img_validate(app_hdr, app_loc->bil_flash_id, app_loc->bil_address,
-        tmpbuf, BOOT_TMPBUF_SZ, loader_hash, 32, NULL)) {
-        return BOOT_EBADIMAGE;
-    }
-    return 0;
-}
-
-/**
- * Selects a slot number to boot from.
- *
- * @return                      The slot number to boot from on success;
- *                              -1 if an appropriate slot could not be
- *                              determined.
- */
-static int
-boot_select_image_slot(void)
-{
-    /*
-     * Check for swap magic. Check the integrity of the suggested image.
-     */
-    int rc;
-    int i;
-    struct boot_img *b;
-    struct boot_img_trailer bit;
-
-    boot_slot_magic(0, &bit);
-    if (bit.bit_copy_start == BOOT_IMG_MAGIC && bit.bit_copy_done != 0xff &&
-      bit.bit_img_ok == 0xff) {
-        /*
-         * Copied the image successfully, but image was not confirmed as good.
-         * We need to go back to another image.
-         */
-        boot_vect_write_test(FLASH_AREA_IMAGE_1);
-    }
-    for (i = 1; i < BOOT_NUM_SLOTS; i++) {
-        b = &boot_img[i];
-        boot_slot_magic(i, &bit);
-        if (bit.bit_copy_start == BOOT_IMG_MAGIC) {
-            if (b->hdr.ih_magic == IMAGE_MAGIC_NONE) {
-                continue;
-            }
-            if (!boot_image_bootable(&b->hdr)) {
-                continue;
-            }
-            rc = boot_image_check(&b->hdr, &b->loc);
-            if (rc) {
-                /*
-                 * Image fails integrity check. Erase it.
-                 */
-                boot_erase_area(boot_req->br_slot_areas[i], b->area);
-            } else {
-                return i;
-            }
-        }
-    }
-    return 0;
-}
-
-static int
-boot_status_sz(void)
-{
-    return sizeof(struct boot_img_trailer) + 32 * sizeof(uint32_t);
-}
-
-/*
- * How many sectors starting from sector[idx] can fit inside scratch.
- *
- */
-static uint32_t
-boot_copy_sz(int max_idx, int *cnt)
-{
-    int i;
-    uint32_t sz;
-    static uint32_t scratch_sz = 0;
-
-    if (!scratch_sz) {
-        for (i = boot_req->br_scratch_area_idx;
-             i < boot_req->br_num_image_areas;
-             i++) {
-            scratch_sz += boot_req->br_area_descs[i].fa_size;
-        }
-    }
-    sz = 0;
-    *cnt = 0;
-    for (i = max_idx - 1; i >= 0; i--) {
-        if (sz + boot_req->br_area_descs[i].fa_size > scratch_sz) {
-            break;
-        }
-        sz += boot_req->br_area_descs[i].fa_size;
-        *cnt = *cnt + 1;
-    }
-    return sz;
-}
-
-/**
- * Erase one area.  The destination area must
- * be erased prior to this function being called.
- *
- * @param area_idx            The index of the area.
- * @param sz                  The number of bytes to erase.
- *
- * @return                      0 on success; nonzero on failure.
- */
-static int
-boot_erase_area(int area_idx, uint32_t sz)
-{
-    const struct flash_area *area_desc;
-    int rc;
-
-    area_desc = boot_req->br_area_descs + area_idx;
-    rc = hal_flash_erase(area_desc->fa_flash_id, area_desc->fa_off, sz);
-    if (rc != 0) {
-        return BOOT_EFLASH;
-    }
-    return 0;
-}
-
-/**
- * Copies the contents of one area to another.  The destination area must
- * be erased prior to this function being called.
- *
- * @param from_area_idx       The index of the source area.
- * @param to_area_idx         The index of the destination area.
- * @param sz                  The number of bytes to move.
- *
- * @return                      0 on success; nonzero on failure.
- */
-static int
-boot_copy_area(int from_area_idx, int to_area_idx, uint32_t sz)
-{
-    const struct flash_area *from_area_desc;
-    const struct flash_area *to_area_desc;
-    uint32_t from_addr;
-    uint32_t to_addr;
-    uint32_t off;
-    int chunk_sz;
-    int rc;
-
-    static uint8_t buf[1024];
-
-    from_area_desc = boot_req->br_area_descs + from_area_idx;
-    to_area_desc = boot_req->br_area_descs + to_area_idx;
-
-    assert(to_area_desc->fa_size >= from_area_desc->fa_size);
-
-    off = 0;
-    while (off < sz) {
-        if (sz - off > sizeof buf) {
-            chunk_sz = sizeof buf;
-        } else {
-            chunk_sz = sz - off;
-        }
-
-        from_addr = from_area_desc->fa_off + off;
-        rc = hal_flash_read(from_area_desc->fa_flash_id, from_addr, buf,
-                            chunk_sz);
-        if (rc != 0) {
-            return rc;
-        }
-
-        to_addr = to_area_desc->fa_off + off;
-        rc = hal_flash_write(to_area_desc->fa_flash_id, to_addr, buf,
-                             chunk_sz);
-        if (rc != 0) {
-            return rc;
-        }
-
-        off += chunk_sz;
-    }
-
-    return 0;
-}
-
-/**
- * Swaps the contents of two flash areas belonging to images.
- *
- * @param area_idx            The index of first slot to exchange. This area
- *                                  must be part of the first image slot.
- * @param sz                  The number of bytes swap.
- *
- * @param end_area            Boolean telling whether this includes this
- *                                  area has last slots.
- *
- * @return                      0 on success; nonzero on failure.
- */
-static int
-boot_swap_areas(int idx, uint32_t sz, int end_area)
-{
-    int area_idx_1;
-    int area_idx_2;
-    int rc;
-
-    area_idx_1 = boot_req->br_slot_areas[0] + idx;
-    area_idx_2 = boot_req->br_slot_areas[1] + idx;
-    assert(area_idx_1 != area_idx_2);
-    assert(area_idx_1 != boot_req->br_scratch_area_idx);
-    assert(area_idx_2 != boot_req->br_scratch_area_idx);
-
-    if (boot_state.state == 0) {
-        rc = boot_erase_area(boot_req->br_scratch_area_idx, sz);
-        if (rc != 0) {
-            return rc;
-        }
-
-        rc = boot_copy_area(area_idx_2, boot_req->br_scratch_area_idx, sz);
-        if (rc != 0) {
-            return rc;
-        }
-
-        boot_state.state = 1;
-        (void)boot_write_status(&boot_state);
-    }
-    if (boot_state.state == 1) {
-        rc = boot_erase_area(area_idx_2, sz);
-        if (rc != 0) {
-            return rc;
-        }
-
-        rc = boot_copy_area(area_idx_1, area_idx_2,
-          end_area ? (sz - boot_status_sz()) : sz);
-        if (rc != 0) {
-            return rc;
-        }
-
-        boot_state.state = 2;
-        (void)boot_write_status(&boot_state);
-    }
-    if (boot_state.state == 2) {
-        rc = boot_erase_area(area_idx_1, sz);
-        if (rc != 0) {
-            return rc;
-        }
-
-        rc = boot_copy_area(boot_req->br_scratch_area_idx, area_idx_1, sz);
-        if (rc != 0) {
-            return rc;
-        }
-
-        boot_state.idx++;
-        boot_state.state = 0;
-        (void)boot_write_status(&boot_state);
-    }
-    return 0;
-}
-
-/**
- * Swaps the two images in flash.  If a prior copy operation was interrupted
- * by a system reset, this function completes that operation.
- *
- * @return                      0 on success; nonzero on failure.
- */
-static int
-boot_copy_image(void)
-{
-    uint32_t sz;
-    int i;
-    int end_area = 1;
-    int cnt;
-    int cur_idx;
-
-    for (i = boot_req->br_slot_areas[1], cur_idx = 0; i > 0; cur_idx++) {
-        sz = boot_copy_sz(i, &cnt);
-        i -= cnt;
-        if (cur_idx >= boot_state.idx) {
-            boot_swap_areas(i, sz, end_area);
-        }
-        end_area = 0;
-    }
-    boot_clear_status();
-
-    return 0;
-}
-
-/**
- * Prepares the booting process.  Based on the information provided in the
- * request object, this function moves images around in flash as appropriate,
- * and tells you what address to boot from.
- *
- * @param req                   Contains information about the flash layout.
- * @param rsp                   On success, indicates how booting should occur.
- *
- * @return                      0 on success; nonzero on failure.
- */
-int
-boot_go(const struct boot_req *req, struct boot_rsp *rsp)
-{
-    int slot;
-    int rc;
-
-    /* Set the global boot request object.  The remainder of the boot process
-     * will reference the global.
-     */
-    boot_req = req;
-
-    /* Attempt to read an image header from each slot. */
-    boot_image_info();
-
-    /* Read the boot status to determine if an image copy operation was
-     * interrupted (i.e., the system was reset before the boot loader could
-     * finish its task last time).
-     */
-    if (boot_read_status(&boot_state)) {
-        /* We are resuming an interrupted image copy. */
-        rc = boot_copy_image();
-        if (rc != 0) {
-            /* We failed to put the images back together; there is really no
-             * solution here.
-             */
-            return rc;
-        }
-    }
-
-    /*
-     * Check if we should initiate copy, or revert back to earlier image.
-     *
-     */
-    slot = boot_select_image_slot();
-    if (slot == -1) {
-        return BOOT_EBADIMAGE;
-    }
-
-    if (slot) {
-        boot_state.idx = 0;
-        boot_state.state = 0;
-        rc = boot_copy_image();
-        if (rc) {
-            return rc;
-        }
-    }
-
-    /* Always boot from the primary slot. */
-    rsp->br_flash_id = boot_img[0].loc.bil_flash_id;
-    rsp->br_image_addr = boot_img[0].loc.bil_address;
-    rsp->br_hdr = &boot_img[slot].hdr;
-
-    return 0;
-}
-
-#define SPLIT_AREA_DESC_MAX     (255)
-
-int
-split_go(int loader_slot, int split_slot, void **entry)
-{
-    int rc;
-    /** Areas representing the beginning of image slots. */
-    uint8_t img_starts[2];
-    struct flash_area *descs;
-    uint32_t entry_val;
-    struct boot_req req = {
-        .br_slot_areas = img_starts,
-    };
-
-    descs = calloc(SPLIT_AREA_DESC_MAX, sizeof(struct flash_area));
-    if (descs == NULL) {
-        return SPLIT_GO_ERR;
-    }
-
-    req.br_area_descs = descs;
-
-    rc = boot_build_request(&req, SPLIT_AREA_DESC_MAX);
-    if (rc != 0) {
-        rc = SPLIT_GO_ERR;
-        goto split_app_go_end;
-    }
-
-    boot_req = &req;
-
-    boot_image_info();
-
-    /* Don't check the bootable image flag because we could really
-      * call a bootable or non-bootable image.  Just validate that
-      * the image check passes which is distinct from the normal check */
-    rc = split_image_check(&boot_img[split_slot].hdr,
-                           &boot_img[split_slot].loc,
-                           &boot_img[loader_slot].hdr,
-                           &boot_img[loader_slot].loc);
-    if (rc != 0) {
-        rc = SPLIT_GO_NON_MATCHING;
-        goto split_app_go_end;
-    }
-
-    entry_val = (uint32_t) boot_img[split_slot].loc.bil_address +
-                         (uint32_t)  boot_img[split_slot].hdr.ih_hdr_size;
-    *entry = (void*) entry_val;
-    rc = SPLIT_GO_OK;
-
-split_app_go_end:
-    free(descs);
-    return rc;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/bootutil/test/pkg.yml
----------------------------------------------------------------------
diff --git a/libs/bootutil/test/pkg.yml b/libs/bootutil/test/pkg.yml
deleted file mode 100644
index 6f6718b..0000000
--- a/libs/bootutil/test/pkg.yml
+++ /dev/null
@@ -1,30 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you 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.
-#
-pkg.name: libs/bootutil/test
-pkg.type: unittest
-pkg.description: "Bootutil unit tests."
-pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
-pkg.homepage: "http://mynewt.apache.org/"
-pkg.keywords:
-
-pkg.deps: 
-    - libs/bootutil
-    - libs/testutil
-
-pkg.deps.SELFTEST:
-    - libs/console/stub


[05/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/mn_socket/src/arch/sim/native_itf.c
----------------------------------------------------------------------
diff --git a/sys/mn_socket/src/arch/sim/native_itf.c b/sys/mn_socket/src/arch/sim/native_itf.c
deleted file mode 100644
index 78607e7..0000000
--- a/sys/mn_socket/src/arch/sim/native_itf.c
+++ /dev/null
@@ -1,212 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-#include <ifaddrs.h>
-#include <net/if.h>
-#include <string.h>
-#include <errno.h>
-#include <limits.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
-
-#include "mn_socket/mn_socket.h"
-#include "native_sock_priv.h"
-
-static uint8_t
-itf_flags(int if_flags)
-{
-    uint8_t flags;
-
-    flags = 0;
-
-    if ((if_flags & (IFF_UP | IFF_RUNNING)) == (IFF_UP | IFF_RUNNING)) {
-        flags |= MN_ITF_F_UP;
-    }
-    if (if_flags & IFF_MULTICAST) {
-        flags |= MN_ITF_F_MULTICAST;
-    }
-    return flags;
-}
-
-int
-native_sock_itf_getnext(struct mn_itf *mi)
-{
-    int prev_idx, cur_idx;
-    struct ifaddrs *ifap;
-    struct ifaddrs *ifa;
-    int rc;
-
-    if (mi->mif_name[0] == '\0') {
-        prev_idx = 0;
-    } else {
-        prev_idx = mi->mif_idx;
-    }
-    mi->mif_idx = UCHAR_MAX;
-    rc = getifaddrs(&ifap);
-    if (rc < 0) {
-        rc = native_sock_err_to_mn_err(errno);
-        return rc;
-    }
-
-    rc = MN_ENOBUFS;
-    for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
-        cur_idx = if_nametoindex(ifa->ifa_name);
-        if (cur_idx <= prev_idx || cur_idx >= mi->mif_idx) {
-            continue;
-        }
-        strncpy(mi->mif_name, ifa->ifa_name, sizeof(mi->mif_name));
-        mi->mif_idx = cur_idx;
-        mi->mif_flags = itf_flags(ifa->ifa_flags);
-        rc = 0;
-    }
-    freeifaddrs(ifap);
-    return rc;
-}
-
-static int
-addrcmp(uint8_t fam1, void *addr1, uint8_t fam2, void *addr2, int alen)
-{
-    if (fam1 != fam2) {
-        return fam1 - fam2;
-    }
-    return memcmp(addr1, addr2, alen);
-}
-
-static int
-plen(void *addr, int alen)
-{
-    int i;
-    int j;
-    uint8_t b;
-
-    for (i = 0; i < alen; i++) {
-        b = ((uint8_t *)addr)[i];
-        if (b == 0xff) {
-            continue;
-        }
-        for (j = 0; j < 7; j++) {
-            if ((b & (0x80 >> j)) == 0) {
-                return i * 8 + j;
-            }
-        }
-    }
-    return alen * 8;
-}
-
-int
-native_sock_itf_addr(int idx, uint32_t *addr)
-{
-    struct ifaddrs *ifap;
-    struct ifaddrs *ifa;
-    struct sockaddr_in *sin;
-    int rc;
-
-    rc = getifaddrs(&ifap);
-    if (rc < 0) {
-        rc = native_sock_err_to_mn_err(errno);
-        return rc;
-    }
-
-    rc = MN_EADDRNOTAVAIL;
-    for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
-        if (if_nametoindex(ifa->ifa_name) != idx) {
-            continue;
-        }
-        if (ifa->ifa_addr->sa_family == AF_INET) {
-            sin = (struct sockaddr_in *)ifa->ifa_addr;
-            *addr = sin->sin_addr.s_addr;
-            rc = 0;
-            break;
-        }
-    }
-    freeifaddrs(ifap);
-    return rc;
-}
-
-int
-native_sock_itf_addr_getnext(struct mn_itf *mi, struct mn_itf_addr *mia)
-{
-    struct ifaddrs *ifap;
-    struct ifaddrs *ifa;
-    struct sockaddr_in *sin;
-    struct sockaddr_in6 *sin6;
-    int rc;
-    uint8_t prev_family;
-    uint8_t prev_addr[16];
-
-    rc = getifaddrs(&ifap);
-    if (rc < 0) {
-        rc = native_sock_err_to_mn_err(errno);
-        return rc;
-    }
-
-    prev_family = mia->mifa_family;
-    memcpy(prev_addr, &mia->mifa_addr, sizeof(mia->mifa_addr));
-    mia->mifa_family = UCHAR_MAX;
-    memset(&mia->mifa_addr, 0xff, sizeof(mia->mifa_addr));
-
-    rc = MN_ENOBUFS;
-
-    for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
-        if (if_nametoindex(ifa->ifa_name) != mi->mif_idx) {
-            continue;
-        }
-        if (ifa->ifa_addr->sa_family == AF_INET) {
-            sin = (struct sockaddr_in *)ifa->ifa_addr;
-            if (addrcmp(MN_AF_INET, &sin->sin_addr,
-                prev_family, prev_addr,
-                sizeof(struct in_addr)) <= 0) {
-                continue;
-            }
-            if (addrcmp(MN_AF_INET, &sin->sin_addr,
-                mia->mifa_family, &mia->mifa_addr,
-                sizeof(struct in_addr)) >= 0) {
-                continue;
-            }
-            mia->mifa_family = MN_AF_INET;
-            memcpy(&mia->mifa_addr, &sin->sin_addr, sizeof(struct in_addr));
-
-            sin = (struct sockaddr_in *)ifa->ifa_netmask;
-            mia->mifa_plen = plen(&sin->sin_addr, sizeof(struct in_addr));
-        } else if (ifa->ifa_addr->sa_family == AF_INET6) {
-            sin6 = (struct sockaddr_in6 *)ifa->ifa_addr;
-            if (addrcmp(MN_AF_INET6, &sin6->sin6_addr,
-                prev_family, prev_addr,
-                sizeof(struct in6_addr)) <= 0) {
-                continue;
-            }
-            if (addrcmp(MN_AF_INET6, &sin6->sin6_addr,
-                mia->mifa_family, &mia->mifa_addr,
-                sizeof(struct in6_addr)) >= 0) {
-                continue;
-            }
-            mia->mifa_family = MN_AF_INET6;
-            memcpy(&mia->mifa_addr, &sin6->sin6_addr, sizeof(struct in6_addr));
-
-            sin6 = (struct sockaddr_in6 *)ifa->ifa_netmask;
-            mia->mifa_plen = plen(&sin6->sin6_addr, sizeof(struct in6_addr));
-        } else {
-            continue;
-        }
-        rc = 0;
-    }
-    freeifaddrs(ifap);
-    return rc;
-}
-
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/mn_socket/src/arch/sim/native_sock.c
----------------------------------------------------------------------
diff --git a/sys/mn_socket/src/arch/sim/native_sock.c b/sys/mn_socket/src/arch/sim/native_sock.c
deleted file mode 100644
index 819120c..0000000
--- a/sys/mn_socket/src/arch/sim/native_sock.c
+++ /dev/null
@@ -1,753 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-#include <sys/socket.h>
-#include <unistd.h>
-#include <errno.h>
-#include <netinet/in.h>
-#include <string.h>
-#include <poll.h>
-#include <assert.h>
-#include <fcntl.h>
-#include <sys/ioctl.h>
-#include <stdio.h>
-
-#include <os/os.h>
-#include <os/os_mbuf.h>
-#include "mn_socket/mn_socket.h"
-#include "mn_socket/mn_socket_ops.h"
-
-#include "mn_socket/arch/sim/native_sock.h"
-#include "native_sock_priv.h"
-
-#define NATIVE_SOCK_MAX 8
-#define NATIVE_SOCK_MAX_UDP 2048
-#define NATIVE_SOCK_POLL_ITVL (OS_TICKS_PER_SEC / 5)
-#define SOCK_STACK_SZ   4096
-#define SOCK_PRIO       2
-
-static int native_sock_create(struct mn_socket **sp, uint8_t domain,
-  uint8_t type, uint8_t proto);
-static int native_sock_close(struct mn_socket *);
-static int native_sock_connect(struct mn_socket *, struct mn_sockaddr *);
-static int native_sock_bind(struct mn_socket *, struct mn_sockaddr *);
-static int native_sock_listen(struct mn_socket *, uint8_t qlen);
-static int native_sock_sendto(struct mn_socket *, struct os_mbuf *,
-  struct mn_sockaddr *);
-static int native_sock_recvfrom(struct mn_socket *, struct os_mbuf **,
-  struct mn_sockaddr *);
-static int native_sock_getsockopt(struct mn_socket *, uint8_t level,
-  uint8_t name, void *val);
-static int native_sock_setsockopt(struct mn_socket *, uint8_t level,
-  uint8_t name, void *val);
-
-static int native_sock_getsockname(struct mn_socket *, struct mn_sockaddr *);
-static int native_sock_getpeername(struct mn_socket *, struct mn_sockaddr *);
-
-static struct native_sock {
-    struct mn_socket ns_sock;
-    int ns_fd;
-    unsigned int ns_poll:1;
-    unsigned int ns_listen:1;
-    uint8_t ns_type;
-    uint8_t ns_pf;
-    struct os_sem ns_sem;
-    STAILQ_HEAD(, os_mbuf_pkthdr) ns_rx;
-    struct os_mbuf *ns_tx;
-} native_socks[NATIVE_SOCK_MAX];
-
-static struct native_sock_state {
-    struct pollfd poll_fds[NATIVE_SOCK_MAX];
-    int poll_fd_cnt;
-    struct os_mutex mtx;
-    struct os_task task;
-} native_sock_state;
-
-static const struct mn_socket_ops native_sock_ops = {
-    .mso_create = native_sock_create,
-    .mso_close = native_sock_close,
-
-    .mso_bind = native_sock_bind,
-    .mso_connect = native_sock_connect,
-    .mso_listen = native_sock_listen,
-
-    .mso_sendto = native_sock_sendto,
-    .mso_recvfrom = native_sock_recvfrom,
-
-    .mso_getsockopt = native_sock_getsockopt,
-    .mso_setsockopt = native_sock_setsockopt,
-
-    .mso_getsockname = native_sock_getsockname,
-    .mso_getpeername = native_sock_getpeername,
-
-    .mso_itf_getnext = native_sock_itf_getnext,
-    .mso_itf_addr_getnext = native_sock_itf_addr_getnext
-};
-
-static struct native_sock *
-native_get_sock(void)
-{
-    int i;
-    struct native_sock *ns;
-
-    for (i = 0; i < NATIVE_SOCK_MAX; i++) {
-        if (native_socks[i].ns_fd < 0) {
-            ns = &native_socks[i];
-            ns->ns_poll = 0;
-            ns->ns_listen = 0;
-            return ns;
-        }
-    }
-    return NULL;
-}
-
-static struct native_sock *
-native_find_sock(int fd)
-{
-    int i;
-
-    for (i = 0; i < NATIVE_SOCK_MAX; i++) {
-        if (native_socks[i].ns_fd == fd) {
-            return &native_socks[i];
-        }
-    }
-    return NULL;
-}
-
-static void
-native_sock_poll_rebuild(struct native_sock_state *nss)
-{
-    struct native_sock *ns;
-    int i;
-    int j;
-
-    os_mutex_pend(&nss->mtx, OS_WAIT_FOREVER);
-    for (i = 0, j = 0; i < NATIVE_SOCK_MAX; i++) {
-        ns = &native_socks[i];
-        if (ns->ns_fd < 0) {
-            continue;
-        }
-        if (!ns->ns_poll) {
-            continue;
-        }
-        nss->poll_fds[j].fd = ns->ns_fd;
-        nss->poll_fds[j].events = POLLIN;
-        nss->poll_fds[j].revents = 0;
-        j++;
-    }
-    nss->poll_fd_cnt = j;
-    os_mutex_release(&nss->mtx);
-}
-
-int
-native_sock_err_to_mn_err(int err)
-{
-    switch (err) {
-    case 0:
-        return 0;
-    case EAGAIN:
-    case EINPROGRESS:
-        return MN_EAGAIN;
-    case ENOTCONN:
-        return MN_ENOTCONN;
-    case ETIMEDOUT:
-        return MN_ETIMEDOUT;
-    case ENOMEM:
-        return MN_ENOBUFS;
-    case EADDRINUSE:
-        return MN_EADDRINUSE;
-    case EADDRNOTAVAIL:
-        return MN_EADDRNOTAVAIL;
-    default:
-        return MN_EINVAL;
-    }
-}
-
-static int
-native_sock_mn_addr_to_addr(struct mn_sockaddr *ms, struct sockaddr *sa,
-  int *sa_len)
-{
-    struct sockaddr_in *sin = (struct sockaddr_in *)sa;
-    struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa;
-    struct mn_sockaddr_in *msin = (struct mn_sockaddr_in *)ms;
-    struct mn_sockaddr_in6 *msin6 = (struct mn_sockaddr_in6 *)ms;
-
-    switch (ms->msa_family) {
-    case MN_AF_INET:
-        sin->sin_family = AF_INET;
-#ifndef MN_LINUX
-        sin->sin_len = sizeof(*sin);
-#endif
-        sin->sin_addr.s_addr = msin->msin_addr.s_addr;
-        sin->sin_port = msin->msin_port;
-        *sa_len = sizeof(*sin);
-        break;
-    case MN_AF_INET6:
-        sin6->sin6_family = AF_INET6;
-#ifndef MN_LINUX
-        sin6->sin6_len = sizeof(*sin6);
-#endif
-        sin6->sin6_port = msin6->msin6_port;
-        sin6->sin6_flowinfo = msin6->msin6_flowinfo;
-        memcpy(&sin6->sin6_addr, &msin6->msin6_addr, sizeof(msin6->msin6_addr));
-        sin6->sin6_scope_id = msin6->msin6_scope_id;
-        *sa_len = sizeof(*sin6);
-        break;
-    default:
-        return MN_EPROTONOSUPPORT;
-    }
-    return 0;
-}
-
-static int
-native_sock_addr_to_mn_addr(struct sockaddr *sa, struct mn_sockaddr *ms)
-{
-    struct mn_sockaddr_in *msin = (struct mn_sockaddr_in *)ms;
-    struct mn_sockaddr_in6 *msin6 = (struct mn_sockaddr_in6 *)ms;
-    struct sockaddr_in *sin = (struct sockaddr_in *)sa;
-    struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa;
-
-    switch (sa->sa_family) {
-    case AF_INET:
-        msin->msin_family = MN_AF_INET;
-        msin->msin_len = sizeof(*msin);
-        msin->msin_addr.s_addr = sin->sin_addr.s_addr;
-        msin->msin_port = sin->sin_port;
-        break;
-    case AF_INET6:
-        msin6->msin6_family = MN_AF_INET6;
-        msin6->msin6_len = sizeof(*msin6);
-        msin6->msin6_port = sin6->sin6_port;
-        msin6->msin6_flowinfo = sin6->sin6_flowinfo;
-        memcpy(&msin6->msin6_addr, &sin6->sin6_addr, sizeof(msin6->msin6_addr));
-        msin6->msin6_scope_id = sin6->sin6_scope_id;
-        break;
-    default:
-        return MN_EPROTONOSUPPORT;
-    }
-    return 0;
-}
-
-static int
-native_sock_create(struct mn_socket **sp, uint8_t domain,
-  uint8_t type, uint8_t proto)
-{
-    struct native_sock_state *nss = &native_sock_state;
-    struct native_sock *ns;
-    int idx;
-
-    switch (domain) {
-    case MN_PF_INET:
-        domain = PF_INET;
-        break;
-    case MN_PF_INET6:
-        domain = PF_INET6;
-        break;
-    default:
-        return MN_EPROTONOSUPPORT;
-    }
-
-    switch (type) {
-    case MN_SOCK_DGRAM:
-        type = SOCK_DGRAM;
-        break;
-    case MN_SOCK_STREAM:
-        type = SOCK_STREAM;
-        break;
-    case 0:
-        break;
-    default:
-        return MN_EPROTONOSUPPORT;
-    }
-
-    os_mutex_pend(&nss->mtx, OS_WAIT_FOREVER);
-    ns = native_get_sock();
-    if (!ns) {
-        os_mutex_release(&nss->mtx);
-        return MN_ENOBUFS;
-    }
-    os_sem_init(&ns->ns_sem, 0);
-    idx = socket(domain, type, proto);
-    ns->ns_fd = idx;
-    ns->ns_pf = domain;
-    ns->ns_type = type;
-    os_mutex_release(&nss->mtx);
-    if (idx < 0) {
-        return MN_ENOBUFS;
-    }
-    *sp = &ns->ns_sock;
-    return 0;
-}
-
-static int
-native_sock_close(struct mn_socket *s)
-{
-    struct native_sock_state *nss = &native_sock_state;
-    struct native_sock *ns = (struct native_sock *)s;
-    struct os_mbuf_pkthdr *m;
-
-    os_mutex_pend(&nss->mtx, OS_WAIT_FOREVER);
-    close(ns->ns_fd);
-    ns->ns_fd = -1;
-
-    /*
-     * When socket is closed, we must free all mbufs which might be
-     * queued in it.
-     */
-    while ((m = STAILQ_FIRST(&ns->ns_rx))) {
-        STAILQ_REMOVE_HEAD(&ns->ns_rx, omp_next);
-        os_mbuf_free_chain(OS_MBUF_PKTHDR_TO_MBUF(m));
-    }
-    native_sock_poll_rebuild(nss);
-    os_mutex_release(&nss->mtx);
-    return 0;
-}
-
-static int
-native_sock_connect(struct mn_socket *s, struct mn_sockaddr *addr)
-{
-    struct native_sock_state *nss = &native_sock_state;
-    struct native_sock *ns = (struct native_sock *)s;
-    struct sockaddr_storage ss;
-    struct sockaddr *sa = (struct sockaddr *)&ss;
-    int rc;
-    int sa_len;
-
-    rc = native_sock_mn_addr_to_addr(addr, sa, &sa_len);
-    if (rc) {
-        return rc;
-    }
-    os_mutex_pend(&nss->mtx, OS_WAIT_FOREVER);
-    if (connect(ns->ns_fd, sa, sa_len)) {
-        rc = errno;
-        os_mutex_release(&nss->mtx);
-        return native_sock_err_to_mn_err(rc);
-    }
-    ns->ns_poll = 1;
-    native_sock_poll_rebuild(nss);
-    os_mutex_release(&nss->mtx);
-    mn_socket_writable(s, 0);
-    return 0;
-}
-
-static int
-native_sock_bind(struct mn_socket *s, struct mn_sockaddr *addr)
-{
-    struct native_sock_state *nss = &native_sock_state;
-    struct native_sock *ns = (struct native_sock *)s;
-    struct sockaddr_storage ss;
-    struct sockaddr *sa = (struct sockaddr *)&ss;
-    int rc;
-    int sa_len;
-    int val = 1;
-
-    rc = native_sock_mn_addr_to_addr(addr, sa, &sa_len);
-    if (rc) {
-        return rc;
-    }
-
-    os_mutex_pend(&nss->mtx, OS_WAIT_FOREVER);
-    if (ns->ns_type == SOCK_STREAM) {
-        rc = setsockopt(ns->ns_fd, SOL_SOCKET, SO_REUSEADDR, &val,
-          sizeof(val));
-        if (rc) {
-            goto err;
-        }
-    }
-    rc = ioctl(ns->ns_fd, FIONBIO, (char *)&val);
-    if (rc) {
-        goto err;
-    }
-    if (bind(ns->ns_fd, sa, sa_len)) {
-        goto err;
-    }
-    if (ns->ns_type == SOCK_DGRAM) {
-        ns->ns_poll = 1;
-        native_sock_poll_rebuild(nss);
-    }
-    os_mutex_release(&nss->mtx);
-    return 0;
-err:
-    rc = errno;
-    os_mutex_release(&nss->mtx);
-    return native_sock_err_to_mn_err(rc);
-}
-
-static int
-native_sock_listen(struct mn_socket *s, uint8_t qlen)
-{
-    struct native_sock_state *nss = &native_sock_state;
-    struct native_sock *ns = (struct native_sock *)s;
-    int rc;
-
-    os_mutex_pend(&nss->mtx, OS_WAIT_FOREVER);
-    if (listen(ns->ns_fd, qlen)) {
-        rc = errno;
-        os_mutex_release(&nss->mtx);
-        return native_sock_err_to_mn_err(rc);
-    }
-    ns->ns_poll = 1;
-    ns->ns_listen = 1;
-    native_sock_poll_rebuild(nss);
-    os_mutex_release(&nss->mtx);
-    return 0;
-}
-
-/*
- * TX routine for stream sockets (TCP). The data to send is pointed
- * by ns_tx.
- * Keep sending mbufs until socket says that it can't take anymore.
- * then wait for send event notification before continuing.
- */
-static int
-native_sock_stream_tx(struct native_sock *ns, int notify)
-{
-    struct native_sock_state *nss = &native_sock_state;
-    struct os_mbuf *m;
-    struct os_mbuf *n;
-    int rc;
-
-    rc = 0;
-
-    os_mutex_pend(&nss->mtx, OS_TIMEOUT_NEVER);
-    while (ns->ns_tx && rc == 0) {
-        m = ns->ns_tx;
-        n = SLIST_NEXT(m, om_next);
-        rc = write(ns->ns_fd, m->om_data, m->om_len);
-        if (rc == m->om_len) {
-            ns->ns_tx = n;
-            os_mbuf_free(m);
-            rc = 0;
-        } else {
-            rc = errno;
-        }
-    }
-    os_mutex_release(&nss->mtx);
-    if (rc) {
-        if (rc == EAGAIN) {
-            rc = 0;
-        } else {
-            rc = native_sock_err_to_mn_err(rc);
-        }
-    }
-    if (notify) {
-        if (ns->ns_tx == NULL) {
-            mn_socket_writable(&ns->ns_sock, 0);
-        } else {
-            mn_socket_writable(&ns->ns_sock, rc);
-        }
-    }
-    return rc;
-}
-
-static int
-native_sock_sendto(struct mn_socket *s, struct os_mbuf *m,
-  struct mn_sockaddr *addr)
-{
-    struct native_sock *ns = (struct native_sock *)s;
-    struct sockaddr_storage ss;
-    struct sockaddr *sa = (struct sockaddr *)&ss;
-    uint8_t tmpbuf[NATIVE_SOCK_MAX_UDP];
-    struct os_mbuf *o;
-    int sa_len;
-    int off;
-    int rc;
-
-    if (ns->ns_type == SOCK_DGRAM) {
-        rc = native_sock_mn_addr_to_addr(addr, sa, &sa_len);
-        if (rc) {
-            return rc;
-        }
-        off = 0;
-        for (o = m; o; o = SLIST_NEXT(o, om_next)) {
-            if (off + o->om_len > sizeof(tmpbuf)) {
-                return MN_ENOBUFS;
-            }
-            os_mbuf_copydata(o, 0, o->om_len, &tmpbuf[off]);
-            off += o->om_len;
-        }
-        rc = sendto(ns->ns_fd, tmpbuf, off, 0, sa, sa_len);
-        if (rc != off) {
-            return native_sock_err_to_mn_err(errno);
-        }
-        os_mbuf_free_chain(m);
-        return 0;
-    } else {
-        if (ns->ns_tx) {
-            return MN_EAGAIN;
-        }
-        ns->ns_tx = m;
-
-        rc = native_sock_stream_tx(ns, 0);
-        return rc;
-    }
-}
-
-static int
-native_sock_recvfrom(struct mn_socket *s, struct os_mbuf **mp,
-  struct mn_sockaddr *addr)
-{
-    struct native_sock *ns = (struct native_sock *)s;
-    struct sockaddr_storage ss;
-    struct sockaddr *sa = (struct sockaddr *)&ss;
-    uint8_t tmpbuf[NATIVE_SOCK_MAX_UDP];
-    struct os_mbuf *m;
-    socklen_t slen;
-    int rc;
-
-    slen = sizeof(ss);
-    if (ns->ns_type == SOCK_DGRAM) {
-        rc = recvfrom(ns->ns_fd, tmpbuf, sizeof(tmpbuf), 0, sa, &slen);
-    } else {
-        rc = getpeername(ns->ns_fd, sa, &slen);
-        if (rc == 0) {
-            rc = read(ns->ns_fd, tmpbuf, sizeof(tmpbuf));
-        }
-    }
-    if (rc < 0) {
-        return native_sock_err_to_mn_err(errno);
-    }
-    if (ns->ns_type == SOCK_STREAM && rc == 0) {
-        mn_socket_readable(&ns->ns_sock, MN_ECONNABORTED);
-        ns->ns_poll = 0;
-        native_sock_poll_rebuild(&native_sock_state);
-        return MN_ECONNABORTED;
-    }
-
-    m = os_msys_get_pkthdr(rc, 0);
-    if (!m) {
-        return MN_ENOBUFS;
-    }
-    os_mbuf_copyinto(m, 0, tmpbuf, rc);
-    *mp = m;
-    if (addr) {
-        native_sock_addr_to_mn_addr(sa, addr);
-    }
-    return 0;
-}
-
-static int
-native_sock_getsockopt(struct mn_socket *s, uint8_t level, uint8_t name,
-  void *val)
-{
-    return MN_EPROTONOSUPPORT;
-}
-
-static int
-native_sock_setsockopt(struct mn_socket *s, uint8_t level, uint8_t name,
-  void *val)
-{
-    struct native_sock *ns = (struct native_sock *)s;
-    int rc;
-    uint32_t val32;
-    struct group_req greq;
-    struct sockaddr_in *sin;
-    struct sockaddr_in6 *sin6;
-    struct mn_mreq *mreq;
-
-    if (level == MN_SO_LEVEL) {
-        switch (name) {
-        case MN_MCAST_JOIN_GROUP:
-        case MN_MCAST_LEAVE_GROUP:
-            mreq = val;
-            memset(&greq, 0, sizeof(greq));
-            greq.gr_interface = mreq->mm_idx;
-            if (mreq->mm_family == MN_AF_INET) {
-                sin = (struct sockaddr_in *)&greq.gr_group;
-#ifndef MN_LINUX
-                sin->sin_len = sizeof(*sin);
-#endif
-                sin->sin_family = AF_INET;
-                memcpy(&sin->sin_addr, &mreq->mm_addr, sizeof(struct in_addr));
-                level = IPPROTO_IP;
-            } else {
-                sin6 = (struct sockaddr_in6 *)&greq.gr_group;
-#ifndef MN_LINUX
-                sin6->sin6_len = sizeof(*sin6);
-#endif
-                sin6->sin6_family = AF_INET6;
-                memcpy(&sin6->sin6_addr, &mreq->mm_addr,
-                  sizeof(struct in6_addr));
-                level = IPPROTO_IPV6;
-            }
-
-            if (name == MN_MCAST_JOIN_GROUP) {
-                name = MCAST_JOIN_GROUP;
-            } else {
-                name = MCAST_LEAVE_GROUP;
-            }
-            rc = setsockopt(ns->ns_fd, level, name, &greq, sizeof(greq));
-            if (rc) {
-                return native_sock_err_to_mn_err(errno);
-            }
-            return 0;
-        case MN_MCAST_IF:
-            if (ns->ns_pf == AF_INET) {
-                level = IPPROTO_IP;
-                name = IP_MULTICAST_IF;
-                rc = native_sock_itf_addr(*(int *)val, &val32);
-                if (rc) {
-                    return rc;
-                }
-            } else {
-                level = IPPROTO_IPV6;
-                name = IPV6_MULTICAST_IF;
-                val32 = *(uint32_t *)val;
-            }
-            rc = setsockopt(ns->ns_fd, level, name, &val32, sizeof(val32));
-            if (rc) {
-                return native_sock_err_to_mn_err(errno);
-            }
-            return 0;
-        }
-    }
-    return MN_EPROTONOSUPPORT;
-}
-
-static int
-native_sock_getsockname(struct mn_socket *s, struct mn_sockaddr *addr)
-{
-    struct native_sock *ns = (struct native_sock *)s;
-    struct sockaddr_storage ss;
-    struct sockaddr *sa = (struct sockaddr *)&ss;
-    socklen_t len;
-    int rc;
-
-    len = sizeof(struct sockaddr_storage);
-    rc = getsockname(ns->ns_fd, sa, &len);
-    if (rc) {
-        return native_sock_err_to_mn_err(errno);
-    }
-    rc = native_sock_addr_to_mn_addr(sa, addr);
-    if (rc) {
-        return rc;
-    }
-    return 0;
-}
-
-static int
-native_sock_getpeername(struct mn_socket *s, struct mn_sockaddr *addr)
-{
-    struct native_sock *ns = (struct native_sock *)s;
-    struct sockaddr_storage ss;
-    struct sockaddr *sa = (struct sockaddr *)&ss;
-    socklen_t len;
-    int rc;
-
-    len = sizeof(struct sockaddr_storage);
-    rc = getpeername(ns->ns_fd, sa, &len);
-    if (rc) {
-        return native_sock_err_to_mn_err(errno);
-    }
-    rc = native_sock_addr_to_mn_addr(sa, addr);
-    if (rc) {
-        return rc;
-    }
-    return 0;
-}
-
-/*
- * XXX should do this task with SIGIO as well.
- */
-static void
-socket_task(void *arg)
-{
-    struct native_sock_state *nss = arg;
-    struct native_sock *ns, *new_ns;
-    struct sockaddr_storage ss;
-    struct sockaddr *sa = (struct sockaddr *)&ss;
-    int i;
-    socklen_t slen;
-    int rc;
-
-    os_mutex_pend(&nss->mtx, OS_WAIT_FOREVER);
-    while (1) {
-        os_mutex_release(&nss->mtx);
-        os_time_delay(NATIVE_SOCK_POLL_ITVL);
-        os_mutex_pend(&nss->mtx, OS_WAIT_FOREVER);
-        if (nss->poll_fd_cnt) {
-            rc = poll(nss->poll_fds, nss->poll_fd_cnt, 0);
-        } else {
-            rc = 0;
-        }
-        if (rc == 0) {
-            continue;
-        }
-        for (i = 0; i < nss->poll_fd_cnt; i++) {
-            if (!nss->poll_fds[i].revents) {
-                continue;
-            }
-            nss->poll_fds[i].revents = 0;
-            ns = native_find_sock(nss->poll_fds[i].fd);
-            assert(ns);
-            if (ns->ns_listen) {
-                new_ns = native_get_sock();
-                if (!new_ns) {
-                    continue;
-                }
-                slen = sizeof(ss);
-                new_ns->ns_fd = accept(ns->ns_fd, sa, &slen);
-                if (new_ns->ns_fd < 0) {
-                    continue;
-                }
-                new_ns->ns_type = ns->ns_type;
-                new_ns->ns_sock.ms_ops = &native_sock_ops;
-                os_mutex_release(&nss->mtx);
-                if (mn_socket_newconn(&ns->ns_sock, &new_ns->ns_sock)) {
-                    /*
-                     * should close
-                     */
-                }
-                os_mutex_pend(&nss->mtx, OS_WAIT_FOREVER);
-                new_ns->ns_poll = 1;
-                native_sock_poll_rebuild(nss);
-            } else {
-                mn_socket_readable(&ns->ns_sock, 0);
-            }
-        }
-    }
-}
-
-int
-native_sock_init(void)
-{
-    struct native_sock_state *nss = &native_sock_state;
-    int i;
-    os_stack_t *sp;
-
-    for (i = 0; i < NATIVE_SOCK_MAX; i++) {
-        native_socks[i].ns_fd = -1;
-        STAILQ_INIT(&native_socks[i].ns_rx);
-    }
-    sp = malloc(sizeof(os_stack_t) * SOCK_STACK_SZ);
-    if (!sp) {
-        return -1;
-    }
-    os_mutex_init(&nss->mtx);
-    i = os_task_init(&nss->task, "socket", socket_task, &native_sock_state,
-      SOCK_PRIO, OS_WAIT_FOREVER, sp, SOCK_STACK_SZ);
-    if (i) {
-        return -1;
-    }
-    i = mn_socket_ops_reg(&native_sock_ops);
-    if (i) {
-        return -1;
-    }
-
-    return 0;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/mn_socket/src/arch/sim/native_sock_priv.h
----------------------------------------------------------------------
diff --git a/sys/mn_socket/src/arch/sim/native_sock_priv.h b/sys/mn_socket/src/arch/sim/native_sock_priv.h
deleted file mode 100644
index 108cbeb..0000000
--- a/sys/mn_socket/src/arch/sim/native_sock_priv.h
+++ /dev/null
@@ -1,32 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 __NATIVE_SOCK_PRIV_H_
-#define __NATIVE_SOCK_PRIV_H_
-
-struct mn_itf;
-struct mn_itf_addr;
-
-int native_sock_itf_getnext(struct mn_itf *);
-int native_sock_itf_addr_getnext(struct mn_itf *, struct mn_itf_addr *);
-int native_sock_itf_addr(int idx, uint32_t *addr);
-
-int native_sock_err_to_mn_err(int err);
-
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/mn_socket/src/mn_socket.c
----------------------------------------------------------------------
diff --git a/sys/mn_socket/src/mn_socket.c b/sys/mn_socket/src/mn_socket.c
deleted file mode 100644
index 1bf2b4c..0000000
--- a/sys/mn_socket/src/mn_socket.c
+++ /dev/null
@@ -1,138 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include <inttypes.h>
-#include <assert.h>
-
-#include <os/os.h>
-
-#include "mn_socket/mn_socket.h"
-#include "mn_socket/mn_socket_ops.h"
-
-/*
- * Currently there can be just one provider of sockets.
- */
-static const struct mn_socket_ops *mn_sock_tgt;
-
-/** All zeros. */
-const uint32_t nm_in6addr_any[4];
-
-int
-mn_socket_ops_reg(const struct mn_socket_ops *ops)
-{
-    if (mn_sock_tgt) {
-        /*
-         * XXXX for now.
-         */
-        return -1;
-    }
-    mn_sock_tgt = ops;
-    return 0;
-}
-
-int
-mn_socket(struct mn_socket **sp, uint8_t domain, uint8_t type, uint8_t proto)
-{
-    int rc;
-
-    *sp = NULL;
-    /*
-     * XXX Look up where socket should go.
-     */
-    if (!mn_sock_tgt) {
-        return MN_EINVAL;
-    }
-    rc = mn_sock_tgt->mso_create(sp, domain, type, proto);
-    if (*sp) {
-        (*sp)->ms_ops = mn_sock_tgt;
-    }
-    return rc;
-}
-
-int
-mn_bind(struct mn_socket *s, struct mn_sockaddr *addr)
-{
-    return s->ms_ops->mso_bind(s, addr);
-}
-
-int
-mn_connect(struct mn_socket *s, struct mn_sockaddr *addr)
-{
-    return s->ms_ops->mso_connect(s, addr);
-}
-
-int
-mn_listen(struct mn_socket *s, uint8_t qlen)
-{
-    return s->ms_ops->mso_listen(s, qlen);
-}
-
-int
-mn_recvfrom(struct mn_socket *s, struct os_mbuf **mp, struct mn_sockaddr *from)
-{
-    return s->ms_ops->mso_recvfrom(s, mp, from);
-}
-
-int
-mn_sendto(struct mn_socket *s, struct os_mbuf *m, struct mn_sockaddr *to)
-{
-    return s->ms_ops->mso_sendto(s, m, to);
-}
-
-int
-mn_getsockopt(struct mn_socket *s, uint8_t level, uint8_t name, void *val)
-{
-    return s->ms_ops->mso_getsockopt(s, level, name, val);
-}
-
-int
-mn_setsockopt(struct mn_socket *s, uint8_t level, uint8_t name, void *val)
-{
-    return s->ms_ops->mso_setsockopt(s, level, name, val);
-}
-
-int
-mn_getsockname(struct mn_socket *s, struct mn_sockaddr *addr)
-{
-    return s->ms_ops->mso_getsockname(s, addr);
-}
-
-int
-mn_getpeername(struct mn_socket *s, struct mn_sockaddr *addr)
-{
-    return s->ms_ops->mso_getpeername(s, addr);
-}
-
-int
-mn_close(struct mn_socket *s)
-{
-    return s->ms_ops->mso_close(s);
-}
-
-int
-mn_itf_getnext(struct mn_itf *mi)
-{
-    return mn_sock_tgt->mso_itf_getnext(mi);
-}
-
-int
-mn_itf_addr_getnext(struct mn_itf *mi, struct mn_itf_addr *mia)
-{
-    return mn_sock_tgt->mso_itf_addr_getnext(mi, mia);
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/mn_socket/src/mn_socket_aconv.c
----------------------------------------------------------------------
diff --git a/sys/mn_socket/src/mn_socket_aconv.c b/sys/mn_socket/src/mn_socket_aconv.c
deleted file mode 100644
index 7e48d65..0000000
--- a/sys/mn_socket/src/mn_socket_aconv.c
+++ /dev/null
@@ -1,98 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-#include <ctype.h>
-#include <stdio.h>
-#include <os/endian.h>
-#include "mn_socket/mn_socket.h"
-
-int
-mn_inet_pton(int af, const char *src, void *dst)
-{
-    const char *ch_src;
-    uint8_t *ch_tgt;
-    int val;
-    int cnt;
-
-    if (af == MN_PF_INET) {
-        cnt = 0;
-        ch_tgt = dst;
-        val = 0;
-        for (ch_src = src; *ch_src; ch_src++) {
-            if (cnt > 4) {
-                return 0;
-            }
-            if (isdigit(*ch_src)) {
-                val = val * 10 + *ch_src - '0';
-                if (val > 255) {
-                    return 0;
-                }
-                *ch_tgt = val;
-            } else if (*ch_src == '.') {
-                ++cnt;
-                val = 0;
-                ch_tgt++;
-            } else {
-                return 0;
-            }
-        }
-        return 1;
-    } else {
-        /*
-         * Add code here. XXX
-         */
-        return 0;
-    }
-}
-
-const char *
-mn_inet_ntop(int af, const void *src_v, void *dst, int len)
-{
-    const unsigned char *src = src_v;
-    const struct mn_in6_addr *a6;
-    int rc;
-    int i;
-
-    if (af == MN_PF_INET) {
-        rc = snprintf(dst, len, "%u.%u.%u.%u",
-          src[0], src[1], src[2], src[3]);
-        if (rc >= len) {
-            return NULL;
-        } else {
-            return dst;
-        }
-    } else {
-        a6 = src_v;
-        rc = 0;
-
-        for (i = 0; i < sizeof(*a6); i += 2) {
-            rc += snprintf(dst + rc, len - rc, "%x",
-              htons(*(uint16_t *)&a6->s_addr[i]));
-            if (rc >= len) {
-                return NULL;
-            }
-            if (i < sizeof(*a6) - 2) {
-                rc += snprintf(dst + rc, len - rc, ":");
-                if (rc >= len) {
-                    return NULL;
-                }
-            }
-        }
-        return dst;
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/mn_socket/test/pkg.yml
----------------------------------------------------------------------
diff --git a/sys/mn_socket/test/pkg.yml b/sys/mn_socket/test/pkg.yml
deleted file mode 100644
index b46d24c..0000000
--- a/sys/mn_socket/test/pkg.yml
+++ /dev/null
@@ -1,30 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you 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.
-#
-pkg.name: sys/mn_socket/test
-pkg.type: unittest
-pkg.description: "Mynewt socket unit tests."
-pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
-pkg.homepage: "http://mynewt.apache.org/"
-pkg.keywords:
-
-pkg.deps: 
-    - libs/testutil
-    - sys/mn_socket
-
-pkg.deps.SELFTEST:
-    - libs/console/stub

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/mn_socket/test/src/mn_sock_test.c
----------------------------------------------------------------------
diff --git a/sys/mn_socket/test/src/mn_sock_test.c b/sys/mn_socket/test/src/mn_sock_test.c
deleted file mode 100644
index 39acd2b..0000000
--- a/sys/mn_socket/test/src/mn_sock_test.c
+++ /dev/null
@@ -1,895 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include <stdio.h>
-#include <string.h>
-
-#include "syscfg/syscfg.h"
-#include "os/os.h"
-#include "testutil/testutil.h"
-
-#include "mn_socket/mn_socket.h"
-#include "mn_socket/arch/sim/native_sock.h"
-
-#define TEST_STACK_SIZE 4096
-#define TEST_PRIO 22
-static os_stack_t test_stack[OS_STACK_ALIGN(TEST_STACK_SIZE)];
-static struct os_task test_task;
-
-static struct os_sem test_sem;
-
-#define MB_CNT 10
-#define MB_SZ  512
-static uint8_t test_mbuf_area[MB_CNT * MB_SZ];
-static struct os_mempool test_mbuf_mpool;
-static struct os_mbuf_pool test_mbuf_pool;
-
-TEST_CASE(inet_pton_test)
-{
-    int rc;
-    uint8_t addr[8];
-    struct test_vec {
-        char *str;
-        uint8_t cmp[4];
-    };
-    struct test_vec ok_vec[] = {
-        { "1.1.1.1", { 1, 1, 1, 1 } },
-        { "1.2.3.4", { 1, 2, 3, 4 } },
-        { "010.001.255.255", { 10, 1, 255, 255 } },
-        { "001.002.005.006", { 1, 2, 5, 6 } }
-    };
-    struct test_vec invalid_vec[] = {
-        { "a.b.c.d" },
-        { "1a.b3.4.2" },
-        { "1.3.4.2a" },
-        { "1111.3.4.2" },
-        { "3.256.1.0" },
-    };
-    int i;
-
-    for (i = 0; i < sizeof(ok_vec) / sizeof(ok_vec[0]); i++) {
-        memset(addr, 0xa5, sizeof(addr));
-        rc = mn_inet_pton(MN_PF_INET, ok_vec[i].str, addr);
-        TEST_ASSERT(rc == 1);
-        TEST_ASSERT(!memcmp(ok_vec[i].cmp, addr, sizeof(uint32_t)));
-        TEST_ASSERT(addr[5] == 0xa5);
-    }
-    for (i = 0; i < sizeof(invalid_vec) / sizeof(invalid_vec[0]); i++) {
-        rc = mn_inet_pton(MN_PF_INET, invalid_vec[i].str, addr);
-        TEST_ASSERT(rc == 0);
-    }
-}
-
-TEST_CASE(inet_ntop_test)
-{
-    const char *rstr;
-    char addr[48];
-    struct test_vec {
-        char *str;
-        uint8_t cmp[4];
-    };
-    struct test_vec ok_vec[] = {
-        { "1.1.1.1", { 1, 1, 1, 1 } },
-        { "1.2.3.4", { 1, 2, 3, 4 } },
-        { "255.1.255.255", { 255, 1, 255, 255 } },
-        { "1.2.5.6", { 1, 2, 5, 6 } }
-    };
-    int i;
-
-    for (i = 0; i < sizeof(ok_vec) / sizeof(ok_vec[0]); i++) {
-        memset(addr, 0xa5, sizeof(addr));
-        rstr = mn_inet_ntop(MN_PF_INET, ok_vec[i].cmp, addr, sizeof(addr));
-        TEST_ASSERT(rstr);
-        TEST_ASSERT(!strcmp(ok_vec[i].str, addr));
-    }
-    rstr = mn_inet_ntop(MN_PF_INET, ok_vec[0].cmp, addr, 1);
-    TEST_ASSERT(rstr == NULL);
-
-    /* does not have space to null terminate */
-    rstr = mn_inet_ntop(MN_PF_INET, ok_vec[0].cmp, addr, 7);
-    TEST_ASSERT(rstr == NULL);
-}
-
-void
-sock_open_close(void)
-{
-    struct mn_socket *sock;
-    int rc;
-
-    rc = mn_socket(&sock, MN_PF_INET, MN_SOCK_DGRAM, 0);
-    TEST_ASSERT(sock);
-    TEST_ASSERT(rc == 0);
-    mn_close(sock);
-
-    rc = mn_socket(&sock, MN_PF_INET, MN_SOCK_STREAM, 0);
-    TEST_ASSERT(sock);
-    TEST_ASSERT(rc == 0);
-    mn_close(sock);
-
-    rc = mn_socket(&sock, MN_PF_INET6, MN_SOCK_DGRAM, 0);
-    TEST_ASSERT(sock);
-    TEST_ASSERT(rc == 0);
-    mn_close(sock);
-
-    rc = mn_socket(&sock, MN_PF_INET6, MN_SOCK_STREAM, 0);
-    TEST_ASSERT(sock);
-    TEST_ASSERT(rc == 0);
-    mn_close(sock);
-}
-
-void
-sock_listen(void)
-{
-    struct mn_socket *sock;
-    struct mn_sockaddr_in msin;
-    int rc;
-
-    rc = mn_socket(&sock, MN_PF_INET, MN_SOCK_STREAM, 0);
-    TEST_ASSERT(rc == 0);
-
-    msin.msin_family = MN_PF_INET;
-    msin.msin_len = sizeof(msin);
-    msin.msin_port = htons(12444);
-
-    mn_inet_pton(MN_PF_INET, "127.0.0.1", &msin.msin_addr);
-
-    rc = mn_bind(sock, (struct mn_sockaddr *)&msin);
-    TEST_ASSERT(rc == 0);
-
-    rc = mn_listen(sock, 2);
-    TEST_ASSERT(rc == 0);
-
-    mn_close(sock);
-}
-
-void
-stc_writable(void *cb_arg, int err)
-{
-    int *i;
-
-    TEST_ASSERT(err == 0);
-    i = (int *)cb_arg;
-    *i = *i + 1;
-}
-
-int
-stc_newconn(void *cb_arg, struct mn_socket *new)
-{
-    struct mn_socket **r_sock;
-
-    r_sock = cb_arg;
-    *r_sock = new;
-
-    os_sem_release(&test_sem);
-    return 0;
-}
-
-void
-sock_tcp_connect(void)
-{
-    struct mn_socket *listen_sock;
-    struct mn_socket *sock;
-    struct mn_sockaddr_in msin;
-    struct mn_sockaddr_in msin2;
-    int rc;
-    union mn_socket_cb listen_cbs = {
-        .listen.newconn = stc_newconn,
-    };
-    union mn_socket_cb sock_cbs = {
-        .socket.writable = stc_writable
-    };
-    int connected = 0;
-    struct mn_socket *new_sock = NULL;
-
-    rc = mn_socket(&listen_sock, MN_PF_INET, MN_SOCK_STREAM, 0);
-    TEST_ASSERT(rc == 0);
-
-    msin.msin_family = MN_PF_INET;
-    msin.msin_len = sizeof(msin);
-    msin.msin_port = htons(12445);
-
-    mn_inet_pton(MN_PF_INET, "127.0.0.1", &msin.msin_addr);
-
-    mn_socket_set_cbs(listen_sock, &new_sock, &listen_cbs);
-    rc = mn_bind(listen_sock, (struct mn_sockaddr *)&msin);
-    TEST_ASSERT(rc == 0);
-
-    rc = mn_listen(listen_sock, 2);
-    TEST_ASSERT(rc == 0);
-
-    rc = mn_socket(&sock, MN_PF_INET, MN_SOCK_STREAM, 0);
-    TEST_ASSERT(rc == 0);
-
-    mn_socket_set_cbs(sock, &connected, &sock_cbs);
-
-    rc = mn_connect(sock, (struct mn_sockaddr *)&msin);
-    TEST_ASSERT(rc == 0);
-
-    rc = os_sem_pend(&test_sem, OS_TICKS_PER_SEC);
-    TEST_ASSERT(rc == 0);
-    TEST_ASSERT(connected == 1);
-    TEST_ASSERT(new_sock != NULL);
-
-    /*
-     * Check endpoint data matches
-     */
-    rc = mn_getsockname(sock, (struct mn_sockaddr *)&msin);
-    TEST_ASSERT(rc == 0);
-    rc = mn_getpeername(new_sock, (struct mn_sockaddr *)&msin2);
-    TEST_ASSERT(rc == 0);
-    TEST_ASSERT(!memcmp(&msin, &msin2, sizeof(msin)));
-
-    rc = mn_getsockname(new_sock, (struct mn_sockaddr *)&msin);
-    TEST_ASSERT(rc == 0);
-    rc = mn_getpeername(sock, (struct mn_sockaddr *)&msin2);
-    TEST_ASSERT(rc == 0);
-    TEST_ASSERT(!memcmp(&msin, &msin2, sizeof(msin)));
-
-
-    if (new_sock) {
-        mn_close(new_sock);
-    }
-    mn_close(sock);
-    mn_close(listen_sock);
-}
-
-void
-sud_readable(void *cb_arg, int err)
-{
-    os_sem_release(&test_sem);
-}
-
-void
-sock_udp_data(void)
-{
-    struct mn_socket *sock1;
-    struct mn_socket *sock2;
-    struct mn_sockaddr_in msin;
-    struct mn_sockaddr_in msin2;
-    int rc;
-    union mn_socket_cb sock_cbs = {
-        .socket.readable = sud_readable
-    };
-    struct os_mbuf *m;
-    char data[] = "1234567890";
-
-    rc = mn_socket(&sock1, MN_PF_INET, MN_SOCK_DGRAM, 0);
-    TEST_ASSERT(rc == 0);
-    mn_socket_set_cbs(sock1, NULL, &sock_cbs);
-
-    rc = mn_socket(&sock2, MN_PF_INET, MN_SOCK_DGRAM, 0);
-    TEST_ASSERT(rc == 0);
-    mn_socket_set_cbs(sock2, NULL, &sock_cbs);
-
-    msin.msin_family = MN_PF_INET;
-    msin.msin_len = sizeof(msin);
-    msin.msin_port = htons(12445);
-
-    mn_inet_pton(MN_PF_INET, "127.0.0.1", &msin.msin_addr);
-
-    rc = mn_bind(sock1, (struct mn_sockaddr *)&msin);
-    TEST_ASSERT(rc == 0);
-
-    msin2.msin_family = MN_PF_INET;
-    msin2.msin_len = sizeof(msin2);
-    msin2.msin_port = 0;
-    msin2.msin_addr.s_addr = 0;
-    rc = mn_bind(sock2, (struct mn_sockaddr *)&msin2);
-    TEST_ASSERT(rc == 0);
-
-    m = os_msys_get(sizeof(data), 0);
-    TEST_ASSERT(m);
-    rc = os_mbuf_copyinto(m, 0, data, sizeof(data));
-    TEST_ASSERT(rc == 0);
-    rc = mn_sendto(sock2, (struct os_mbuf *)m, (struct mn_sockaddr *)&msin);
-    TEST_ASSERT(rc == 0);
-
-    /*
-     * Wait for the packet.
-     */
-    rc = os_sem_pend(&test_sem, OS_TICKS_PER_SEC);
-    TEST_ASSERT(rc == 0);
-
-    rc = mn_recvfrom(sock1, &m, (struct mn_sockaddr *)&msin2);
-    TEST_ASSERT(rc == 0);
-    TEST_ASSERT(m != NULL);
-    TEST_ASSERT(msin2.msin_family == MN_AF_INET);
-    TEST_ASSERT(msin2.msin_len == sizeof(msin2));
-    TEST_ASSERT(msin2.msin_port != 0);
-    TEST_ASSERT(msin2.msin_addr.s_addr != 0);
-
-    if (m) {
-        TEST_ASSERT(OS_MBUF_IS_PKTHDR(m));
-        TEST_ASSERT(OS_MBUF_PKTLEN(m) == sizeof(data));
-        TEST_ASSERT(m->om_len == sizeof(data));
-        TEST_ASSERT(!memcmp(m->om_data, data, sizeof(data)));
-    }
-
-    rc = mn_sendto(sock1, m, (struct mn_sockaddr *)&msin2);
-    TEST_ASSERT(rc == 0);
-
-    rc = os_sem_pend(&test_sem, OS_TICKS_PER_SEC);
-    TEST_ASSERT(rc == 0);
-
-    rc = mn_recvfrom(sock2, &m, (struct mn_sockaddr *)&msin2);
-    TEST_ASSERT(rc == 0);
-    TEST_ASSERT(m != NULL);
-    if (m) {
-        TEST_ASSERT(OS_MBUF_IS_PKTHDR(m));
-        TEST_ASSERT(OS_MBUF_PKTLEN(m) == sizeof(data));
-        TEST_ASSERT(m->om_len == sizeof(data));
-        TEST_ASSERT(!memcmp(m->om_data, data, sizeof(data)));
-        os_mbuf_free_chain(m);
-    }
-
-    mn_close(sock1);
-    mn_close(sock2);
-}
-
-void
-std_writable(void *cb_arg, int err)
-{
-    int *i;
-
-    TEST_ASSERT(err == 0);
-    i = (int *)cb_arg;
-    if (i) {
-        *i = *i + 1;
-    }
-}
-
-void
-std_readable(void *cb_arg, int err)
-{
-    os_sem_release(&test_sem);
-}
-
-static union mn_socket_cb sud_sock_cbs = {
-    .socket.writable = std_writable,
-    .socket.readable = std_readable
-};
-
-int
-std_newconn(void *cb_arg, struct mn_socket *new)
-{
-    struct mn_socket **r_sock;
-
-    r_sock = cb_arg;
-    *r_sock = new;
-
-    mn_socket_set_cbs(new, NULL, &sud_sock_cbs);
-
-    os_sem_release(&test_sem);
-    return 0;
-}
-
-void
-sock_tcp_data(void)
-{
-    struct mn_socket *listen_sock;
-    struct mn_socket *sock;
-    struct mn_sockaddr_in msin;
-    int rc;
-    union mn_socket_cb listen_cbs = {
-        .listen.newconn = std_newconn,
-    };
-    int connected = 0;
-    struct mn_socket *new_sock = NULL;
-    struct os_mbuf *m;
-    char data[] = "1234567890";
-
-    rc = mn_socket(&listen_sock, MN_PF_INET, MN_SOCK_STREAM, 0);
-    TEST_ASSERT(rc == 0);
-
-    msin.msin_family = MN_PF_INET;
-    msin.msin_len = sizeof(msin);
-    msin.msin_port = htons(12447);
-
-    mn_inet_pton(MN_PF_INET, "127.0.0.1", &msin.msin_addr);
-
-    mn_socket_set_cbs(listen_sock, &new_sock, &listen_cbs);
-    rc = mn_bind(listen_sock, (struct mn_sockaddr *)&msin);
-    TEST_ASSERT(rc == 0);
-
-    rc = mn_listen(listen_sock, 2);
-    TEST_ASSERT(rc == 0);
-
-    rc = mn_socket(&sock, MN_PF_INET, MN_SOCK_STREAM, 0);
-    TEST_ASSERT(rc == 0);
-
-    mn_socket_set_cbs(sock, &connected, &sud_sock_cbs);
-
-    rc = mn_connect(sock, (struct mn_sockaddr *)&msin);
-    TEST_ASSERT(rc == 0);
-
-    rc = os_sem_pend(&test_sem, OS_TICKS_PER_SEC);
-    TEST_ASSERT(rc == 0);
-    TEST_ASSERT(connected == 1);
-    TEST_ASSERT(new_sock != NULL);
-
-    m = os_msys_get(sizeof(data), 0);
-    TEST_ASSERT(m);
-    rc = os_mbuf_copyinto(m, 0, data, sizeof(data));
-    TEST_ASSERT(rc == 0);
-    rc = mn_sendto(new_sock, (struct os_mbuf *)m, (struct mn_sockaddr *)&msin);
-    TEST_ASSERT(rc == 0);
-
-    /*
-     * Wait for the packet.
-     */
-    rc = os_sem_pend(&test_sem, OS_TICKS_PER_SEC);
-    TEST_ASSERT(rc == 0);
-
-    memset(&msin, 0, sizeof(msin));
-    rc = mn_recvfrom(sock, &m, (struct mn_sockaddr *)&msin);
-    TEST_ASSERT(rc == 0);
-    TEST_ASSERT(m != NULL);
-    TEST_ASSERT(msin.msin_family == MN_AF_INET);
-    TEST_ASSERT(msin.msin_len == sizeof(msin));
-    TEST_ASSERT(msin.msin_port != 0);
-    TEST_ASSERT(msin.msin_addr.s_addr != 0);
-    os_mbuf_free_chain(m);
-
-    if (new_sock) {
-        mn_close(new_sock);
-    }
-    mn_close(sock);
-    mn_close(listen_sock);
-}
-
-void
-sock_itf_list(void)
-{
-    struct mn_itf itf;
-    struct mn_itf_addr itf_addr;
-    int if_cnt = 0;
-    int seen_127;
-    struct mn_in_addr addr127;
-    char addr_str[64];
-    int rc;
-
-    mn_inet_pton(MN_PF_INET, "127.0.0.1", &addr127);
-
-    memset(&itf, 0, sizeof(itf));
-
-    while (1) {
-        rc = mn_itf_getnext(&itf);
-        if (rc) {
-            break;
-        }
-        printf("%d: %x %s\n", itf.mif_idx, itf.mif_flags, itf.mif_name);
-        memset(&itf_addr, 0, sizeof(itf_addr));
-        while (1) {
-            rc = mn_itf_addr_getnext(&itf, &itf_addr);
-            if (rc) {
-                break;
-            }
-            if (itf_addr.mifa_family == MN_AF_INET &&
-              !memcmp(&itf_addr.mifa_addr, &addr127, sizeof(addr127))) {
-                seen_127 = 1;
-            }
-            addr_str[0] = '\0';
-            mn_inet_ntop(itf_addr.mifa_family, &itf_addr.mifa_addr,
-              addr_str, sizeof(addr_str));
-            printf(" %s/%d\n", addr_str, itf_addr.mifa_plen);
-        }
-        if_cnt++;
-    }
-    TEST_ASSERT(if_cnt > 0);
-    TEST_ASSERT(seen_127);
-}
-
-static int
-first_ll_addr(struct mn_sockaddr_in6 *ra)
-{
-    struct mn_itf itf;
-    struct mn_itf_addr itf_addr;
-    int rc;
-    struct mn_in6_addr *addr;
-
-    memset(&itf, 0, sizeof(itf));
-    addr = (struct mn_in6_addr *)&itf_addr.mifa_addr;
-    while (1) {
-        rc = mn_itf_getnext(&itf);
-        if (rc) {
-            break;
-        }
-        memset(&itf_addr, 0, sizeof(itf_addr));
-        while (1) {
-            rc = mn_itf_addr_getnext(&itf, &itf_addr);
-            if (rc) {
-                break;
-            }
-            if (itf_addr.mifa_family == MN_AF_INET6 &&
-              addr->s_addr[0] == 0xfe && addr->s_addr[1] == 0x80) {
-                memset(ra, 0, sizeof(*ra));
-                ra->msin6_family = MN_AF_INET6;
-                ra->msin6_len = sizeof(*ra);
-                ra->msin6_scope_id = itf.mif_idx;
-                memcpy(&ra->msin6_addr, addr, sizeof(*addr));
-                return 0;
-            }
-        }
-    }
-    return -1;
-}
-
-void
-sul_readable(void *cb_arg, int err)
-{
-    os_sem_release(&test_sem);
-}
-
-void
-sock_udp_ll(void)
-{
-    struct mn_socket *sock1;
-    struct mn_socket *sock2;
-    struct mn_sockaddr_in6 msin;
-    struct mn_sockaddr_in6 msin2;
-    int rc;
-    union mn_socket_cb sock_cbs = {
-        .socket.readable = sul_readable
-    };
-    struct os_mbuf *m;
-    char data[] = "1234567890";
-
-    rc = mn_socket(&sock1, MN_PF_INET6, MN_SOCK_DGRAM, 0);
-    TEST_ASSERT(rc == 0);
-    mn_socket_set_cbs(sock1, NULL, &sock_cbs);
-
-    rc = mn_socket(&sock2, MN_PF_INET6, MN_SOCK_DGRAM, 0);
-    TEST_ASSERT(rc == 0);
-    mn_socket_set_cbs(sock2, NULL, &sock_cbs);
-
-    rc = first_ll_addr(&msin);
-    if (rc != 0) {
-        printf("No ipv6 address present?\n");
-        return;
-    }
-    msin.msin6_port = htons(12445);
-
-    rc = mn_bind(sock1, (struct mn_sockaddr *)&msin);
-    TEST_ASSERT(rc == 0);
-
-    rc = mn_getsockname(sock1, (struct mn_sockaddr *)&msin2);
-    TEST_ASSERT(rc == 0);
-
-    m = os_msys_get(sizeof(data), 0);
-    TEST_ASSERT(m);
-    rc = os_mbuf_copyinto(m, 0, data, sizeof(data));
-    TEST_ASSERT(rc == 0);
-    rc = mn_sendto(sock2, (struct os_mbuf *)m, (struct mn_sockaddr *)&msin2);
-    TEST_ASSERT(rc == 0);
-
-    /*
-     * Wait for the packet.
-     */
-    rc = os_sem_pend(&test_sem, OS_TICKS_PER_SEC);
-    TEST_ASSERT(rc == 0);
-
-    rc = mn_recvfrom(sock1, &m, (struct mn_sockaddr *)&msin);
-    TEST_ASSERT(rc == 0);
-    TEST_ASSERT(m != NULL);
-
-    if (m) {
-        TEST_ASSERT(OS_MBUF_IS_PKTHDR(m));
-        TEST_ASSERT(OS_MBUF_PKTLEN(m) == sizeof(data));
-        TEST_ASSERT(m->om_len == sizeof(data));
-        TEST_ASSERT(!memcmp(m->om_data, data, sizeof(data)));
-        os_mbuf_free_chain(m);
-    }
-
-    mn_close(sock1);
-    mn_close(sock2);
-}
-
-static int
-sock_find_multicast_if(void)
-{
-    struct mn_itf itf;
-
-    memset(&itf, 0, sizeof(itf));
-
-    while (1) {
-        if (mn_itf_getnext(&itf)) {
-            break;
-        }
-        if ((itf.mif_flags & MN_ITF_F_UP) == 0) {
-            continue;
-        }
-        if (itf.mif_flags & MN_ITF_F_MULTICAST) {
-            return itf.mif_idx;
-        }
-    }
-    return -1;
-}
-
-void
-sum4_readable(void *cb_arg, int err)
-{
-    os_sem_release(&test_sem);
-}
-
-static void
-sock_udp_mcast_v4(void)
-{
-    int loop_if_idx;
-    struct mn_socket *rx_sock;
-    struct mn_socket *tx_sock;
-    struct mn_sockaddr_in msin;
-    union mn_socket_cb sock_cbs = {
-        .socket.readable = sum4_readable
-    };
-    struct os_mbuf *m;
-    char data[] = "1234567890";
-    int rc;
-    struct mn_mreq mreq;
-    loop_if_idx = sock_find_multicast_if();
-    TEST_ASSERT(loop_if_idx > 0);
-
-    msin.msin_family = MN_AF_INET;
-    msin.msin_len = sizeof(msin);
-    msin.msin_port = htons(44344);
-    memset(&msin.msin_addr, 0, sizeof(msin.msin_addr));
-
-    rc = mn_socket(&rx_sock, MN_PF_INET, MN_SOCK_DGRAM, 0);
-    TEST_ASSERT(rc == 0);
-    mn_socket_set_cbs(rx_sock, NULL, &sock_cbs);
-
-    rc = mn_bind(rx_sock, (struct mn_sockaddr *)&msin);
-    TEST_ASSERT(rc == 0);
-
-    rc = mn_socket(&tx_sock, MN_PF_INET, MN_SOCK_DGRAM, 0);
-    TEST_ASSERT(rc == 0);
-
-    rc = mn_setsockopt(tx_sock, MN_SO_LEVEL, MN_MCAST_IF, &loop_if_idx);
-    TEST_ASSERT(rc == 0);
-
-    m = os_msys_get(sizeof(data), 0);
-    rc = os_mbuf_copyinto(m, 0, data, sizeof(data));
-    TEST_ASSERT(rc == 0);
-
-    /*
-     * multicast tgt
-     */
-    mn_inet_pton(MN_PF_INET, "224.0.2.241", &msin.msin_addr);
-
-    rc = mn_sendto(tx_sock, (struct os_mbuf *)m, (struct mn_sockaddr *)&msin);
-    TEST_ASSERT(rc == 0);
-
-    /*
-     * RX socket has not joined group yet.
-     */
-    rc = os_sem_pend(&test_sem, OS_TICKS_PER_SEC / 2);
-    TEST_ASSERT(rc == OS_TIMEOUT);
-
-    mreq.mm_idx = loop_if_idx;
-    mreq.mm_family = MN_AF_INET;
-    mreq.mm_addr.v4.s_addr = msin.msin_addr.s_addr;
-
-    /*
-     * Now join it.
-     */
-    rc = mn_setsockopt(rx_sock, MN_SO_LEVEL, MN_MCAST_JOIN_GROUP, &mreq);
-    TEST_ASSERT(rc == 0);
-
-    m = os_msys_get(sizeof(data), 0);
-    rc = os_mbuf_copyinto(m, 0, data, sizeof(data));
-    TEST_ASSERT(rc == 0);
-
-    rc = mn_sendto(tx_sock, (struct os_mbuf *)m, (struct mn_sockaddr *)&msin);
-    TEST_ASSERT(rc == 0);
-
-    rc = os_sem_pend(&test_sem, OS_TICKS_PER_SEC);
-    TEST_ASSERT(rc == 0);
-
-    rc = mn_recvfrom(rx_sock, &m, NULL);
-    TEST_ASSERT(rc == 0);
-    TEST_ASSERT(m != NULL);
-    TEST_ASSERT(!memcmp(m->om_data, data, sizeof(data)));
-    os_mbuf_free_chain(m);
-
-    /*
-     * Then leave
-     */
-    rc = mn_setsockopt(rx_sock, MN_SO_LEVEL, MN_MCAST_LEAVE_GROUP, &mreq);
-    TEST_ASSERT(rc == 0);
-
-    m = os_msys_get(sizeof(data), 0);
-    TEST_ASSERT(m);
-    rc = os_mbuf_copyinto(m, 0, data, sizeof(data));
-    TEST_ASSERT(rc == 0);
-
-    rc = mn_sendto(tx_sock, (struct os_mbuf *)m, (struct mn_sockaddr *)&msin);
-    TEST_ASSERT(rc == 0);
-
-    rc = os_sem_pend(&test_sem, OS_TICKS_PER_SEC);
-    TEST_ASSERT(rc == OS_TIMEOUT);
-
-    mn_close(rx_sock);
-    mn_close(tx_sock);
-}
-
-static void
-sock_udp_mcast_v6(void)
-{
-    int loop_if_idx;
-    struct mn_socket *rx_sock;
-    struct mn_socket *tx_sock;
-    struct mn_sockaddr_in6 msin6;
-    union mn_socket_cb sock_cbs = {
-        .socket.readable = sum4_readable
-    };
-    struct os_mbuf *m;
-    char data[] = "1234567890";
-    int rc;
-    struct mn_mreq mreq;
-    uint8_t mcast_addr[16] = {
-        0xff, 2, 0, 0,
-        0, 0, 0, 0,
-        0, 0, 0, 0,
-        0, 0, 0, 2
-    };
-
-    loop_if_idx = sock_find_multicast_if();
-    TEST_ASSERT(loop_if_idx > 0);
-
-    msin6.msin6_family = MN_AF_INET6;
-    msin6.msin6_len = sizeof(msin6);
-    msin6.msin6_port = htons(44344);
-    memset(&msin6.msin6_addr, 0, sizeof(msin6.msin6_addr));
-
-    rc = mn_socket(&rx_sock, MN_PF_INET6, MN_SOCK_DGRAM, 0);
-    TEST_ASSERT(rc == 0);
-    mn_socket_set_cbs(rx_sock, NULL, &sock_cbs);
-
-    rc = mn_bind(rx_sock, (struct mn_sockaddr *)&msin6);
-    TEST_ASSERT(rc == 0);
-
-    rc = mn_socket(&tx_sock, MN_PF_INET6, MN_SOCK_DGRAM, 0);
-    TEST_ASSERT(rc == 0);
-
-    rc = mn_setsockopt(tx_sock, MN_SO_LEVEL, MN_MCAST_IF, &loop_if_idx);
-    TEST_ASSERT(rc == 0);
-
-    m = os_msys_get(sizeof(data), 0);
-    rc = os_mbuf_copyinto(m, 0, data, sizeof(data));
-    TEST_ASSERT(rc == 0);
-
-    /*
-     * multicast tgt
-     */
-    memcpy(&msin6.msin6_addr, mcast_addr, sizeof(mcast_addr));
-
-    rc = mn_sendto(tx_sock, (struct os_mbuf *)m, (struct mn_sockaddr *)&msin6);
-    TEST_ASSERT(rc == 0);
-
-    /*
-     * RX socket has not joined group yet.
-     */
-    rc = os_sem_pend(&test_sem, OS_TICKS_PER_SEC / 2);
-    TEST_ASSERT(rc == OS_TIMEOUT);
-
-    mreq.mm_idx = loop_if_idx;
-    mreq.mm_family = MN_AF_INET6;
-    memcpy(&mreq.mm_addr.v6.s_addr, msin6.msin6_addr.s_addr,
-      sizeof(msin6.msin6_addr.s_addr));
-
-    /*
-     * Now join it.
-     */
-    rc = mn_setsockopt(rx_sock, MN_SO_LEVEL, MN_MCAST_JOIN_GROUP, &mreq);
-    TEST_ASSERT(rc == 0);
-
-    m = os_msys_get(sizeof(data), 0);
-    rc = os_mbuf_copyinto(m, 0, data, sizeof(data));
-    TEST_ASSERT(rc == 0);
-
-    rc = mn_sendto(tx_sock, (struct os_mbuf *)m, (struct mn_sockaddr *)&msin6);
-    TEST_ASSERT(rc == 0);
-
-    rc = os_sem_pend(&test_sem, OS_TICKS_PER_SEC);
-    TEST_ASSERT(rc == 0);
-
-    rc = mn_recvfrom(rx_sock, &m, NULL);
-    TEST_ASSERT(rc == 0);
-    TEST_ASSERT(m != NULL);
-    TEST_ASSERT(!memcmp(m->om_data, data, sizeof(data)));
-    os_mbuf_free_chain(m);
-
-    /*
-     * Then leave
-     */
-    rc = mn_setsockopt(rx_sock, MN_SO_LEVEL, MN_MCAST_LEAVE_GROUP, &mreq);
-    TEST_ASSERT(rc == 0);
-
-    m = os_msys_get(sizeof(data), 0);
-    TEST_ASSERT(m);
-    rc = os_mbuf_copyinto(m, 0, data, sizeof(data));
-    TEST_ASSERT(rc == 0);
-
-    rc = mn_sendto(tx_sock, (struct os_mbuf *)m, (struct mn_sockaddr *)&msin6);
-    TEST_ASSERT(rc == 0);
-
-    rc = os_sem_pend(&test_sem, OS_TICKS_PER_SEC);
-    TEST_ASSERT(rc == OS_TIMEOUT);
-
-    mn_close(rx_sock);
-    mn_close(tx_sock);
-}
-
-void
-mn_socket_test_handler(void *arg)
-{
-    sock_open_close();
-    sock_listen();
-    sock_tcp_connect();
-    sock_udp_data();
-    sock_tcp_data();
-    sock_itf_list();
-    sock_udp_ll();
-    sock_udp_mcast_v4();
-    sock_udp_mcast_v6();
-    tu_restart();
-}
-
-TEST_CASE(socket_tests)
-{
-    os_init();
-    native_sock_init();
-
-    os_sem_init(&test_sem, 0);
-
-    os_task_init(&test_task, "mn_socket_test", mn_socket_test_handler, NULL,
-      TEST_PRIO, OS_WAIT_FOREVER, test_stack, TEST_STACK_SIZE);
-    os_start();
-}
-
-TEST_SUITE(mn_socket_test_all)
-{
-    int rc;
-
-    rc = os_mempool_init(&test_mbuf_mpool, MB_CNT, MB_SZ, test_mbuf_area, "mb");
-    TEST_ASSERT(rc == 0);
-    rc = os_mbuf_pool_init(&test_mbuf_pool, &test_mbuf_mpool, MB_CNT, MB_CNT);
-    TEST_ASSERT(rc == 0);
-    rc = os_msys_register(&test_mbuf_pool);
-    TEST_ASSERT(rc == 0);
-
-    inet_pton_test();
-    inet_ntop_test();
-
-    socket_tests();
-}
-
-#if MYNEWT_VAL(SELFTEST)
-
-int
-main(int argc, char **argv)
-{
-    tu_config.tc_print_results = 1;
-    tu_init();
-
-    mn_socket_test_all();
-
-    return tu_any_failed;
-}
-#endif
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/reboot/pkg.yml
----------------------------------------------------------------------
diff --git a/sys/reboot/pkg.yml b/sys/reboot/pkg.yml
index fd173e2..9e88f71 100644
--- a/sys/reboot/pkg.yml
+++ b/sys/reboot/pkg.yml
@@ -26,13 +26,13 @@ pkg.keywords:
     - logging
 
 pkg.deps:
-    - libs/os
+    - kernel/os
     - libs/util
     - sys/log
     - libs/imgmgr
     - sys/config
 pkg.deps.REBOOT_LOG_FCB:
-    - sys/fcb
+    - fs/fcb
 pkg.req_apis:
     - console
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/shell/include/shell/shell.h
----------------------------------------------------------------------
diff --git a/sys/shell/include/shell/shell.h b/sys/shell/include/shell/shell.h
new file mode 100644
index 0000000..48351a0
--- /dev/null
+++ b/sys/shell/include/shell/shell.h
@@ -0,0 +1,48 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 __SHELL_H__
+#define __SHELL_H__
+
+#include <os/os.h>
+
+typedef int (*shell_cmd_func_t)(int argc, char **argv);
+struct shell_cmd {
+    char *sc_cmd;
+    shell_cmd_func_t sc_cmd_func;
+    STAILQ_ENTRY(shell_cmd) sc_next;
+};
+
+int shell_cmd_register(struct shell_cmd *sc);
+
+#define SHELL_NLIP_PKT_START1 (6)
+#define SHELL_NLIP_PKT_START2 (9)
+#define SHELL_NLIP_DATA_START1 (4)
+#define SHELL_NLIP_DATA_START2 (20)
+
+typedef int (*shell_nlip_input_func_t)(struct os_mbuf *, void *arg);
+int shell_nlip_input_register(shell_nlip_input_func_t nf, void *arg);
+int shell_nlip_output(struct os_mbuf *m);
+
+void shell_console_rx_cb(void);
+void shell_init(void);
+
+int shell_cmd_list_lock(void);
+int shell_cmd_list_unlock(void);
+
+#endif /* __SHELL_H__ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/shell/include/shell/shell_prompt.h
----------------------------------------------------------------------
diff --git a/sys/shell/include/shell/shell_prompt.h b/sys/shell/include/shell/shell_prompt.h
new file mode 100644
index 0000000..f0e4dd3
--- /dev/null
+++ b/sys/shell/include/shell/shell_prompt.h
@@ -0,0 +1,25 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 H_SHELL_PROMPT_
+#define H_SHELL_PROMPT_
+
+int shell_prompt_cmd(int argc, char **argv);
+
+#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/shell/pkg.yml
----------------------------------------------------------------------
diff --git a/sys/shell/pkg.yml b/sys/shell/pkg.yml
new file mode 100644
index 0000000..c4449e5
--- /dev/null
+++ b/sys/shell/pkg.yml
@@ -0,0 +1,50 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+#
+
+pkg.name: sys/shell 
+pkg.description: Command processor for console-based applications.
+pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
+pkg.homepage: "http://mynewt.apache.org/"
+pkg.keywords:
+
+pkg.deps:
+    - kernel/os
+    - libs/util
+    - encoding/base64 
+    - encoding/crc
+pkg.req_apis:
+    - console
+
+pkg.init_function: shell_init
+pkg.init_stage: 5
+
+pkg.syscfg_defs:
+    SHELL_TASK:
+        description: 'TBD'
+        value: 0
+    SHELL_TASK_PRIO:
+        description: 'TBD'
+        type: 'task_priority'
+        value: 'any'
+    SHELL_STACK_SIZE:
+        description: 'TBD'
+        value: 512
+    SHELL_MAX_INPUT_LEN:
+        description: 'TBD'
+        value: 256

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/shell/src/shell.c
----------------------------------------------------------------------
diff --git a/sys/shell/src/shell.c b/sys/shell/src/shell.c
new file mode 100644
index 0000000..58481de
--- /dev/null
+++ b/sys/shell/src/shell.c
@@ -0,0 +1,579 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include <stdio.h>
+#include <string.h>
+#include <assert.h>
+
+#include "sysinit/sysinit.h"
+#include "syscfg/syscfg.h"
+#include "console/console.h"
+#include "console/prompt.h"
+#include "os/os.h"
+#include "os/endian.h"
+#include "base64/base64.h"
+#include "crc/crc16.h"
+#include "shell/shell.h"
+#include "shell_priv.h"
+
+static shell_nlip_input_func_t g_shell_nlip_in_func;
+static void *g_shell_nlip_in_arg;
+
+static struct os_mqueue g_shell_nlip_mq;
+
+#define OS_EVENT_T_CONSOLE_RDY  (OS_EVENT_T_PERUSER)
+#define SHELL_HELP_PER_LINE     6
+#define SHELL_MAX_ARGS          20
+
+static os_stack_t shell_stack[OS_STACK_ALIGN(MYNEWT_VAL(SHELL_STACK_SIZE))];
+
+static int shell_echo_cmd(int argc, char **argv);
+static int shell_help_cmd(int argc, char **argv);
+int shell_prompt_cmd(int argc, char **argv);
+
+static struct shell_cmd g_shell_echo_cmd = {
+    .sc_cmd = "echo",
+    .sc_cmd_func = shell_echo_cmd
+};
+static struct shell_cmd g_shell_help_cmd = {
+    .sc_cmd = "?",
+    .sc_cmd_func = shell_help_cmd
+};
+static struct shell_cmd g_shell_prompt_cmd = {
+   .sc_cmd = "prompt",
+   .sc_cmd_func = shell_prompt_cmd
+};
+static struct shell_cmd g_shell_os_tasks_display_cmd = {
+    .sc_cmd = "tasks",
+    .sc_cmd_func = shell_os_tasks_display_cmd
+};
+static struct shell_cmd g_shell_os_mpool_display_cmd = {
+    .sc_cmd = "mempools",
+    .sc_cmd_func = shell_os_mpool_display_cmd
+};
+static struct shell_cmd g_shell_os_date_cmd = {
+    .sc_cmd = "date",
+    .sc_cmd_func = shell_os_date_cmd
+};
+
+static struct os_task shell_task;
+static struct os_eventq shell_evq;
+static struct os_event console_rdy_ev;
+
+static struct os_mutex g_shell_cmd_list_lock;
+
+static char *shell_line;
+static int shell_line_len;
+static char *argv[SHELL_MAX_ARGS];
+
+static STAILQ_HEAD(, shell_cmd) g_shell_cmd_list =
+    STAILQ_HEAD_INITIALIZER(g_shell_cmd_list);
+
+static struct os_mbuf *g_nlip_mbuf;
+static uint16_t g_nlip_expected_len;
+
+int
+shell_cmd_list_lock(void)
+{
+    int rc;
+
+    if (!os_started()) {
+        return (0);
+    }
+
+    rc = os_mutex_pend(&g_shell_cmd_list_lock, OS_WAIT_FOREVER);
+    if (rc != 0) {
+        goto err;
+    }
+    return (0);
+err:
+    return (rc);
+}
+
+int
+shell_cmd_list_unlock(void)
+{
+    int rc;
+
+    if (!os_started()) {
+        return (0);
+    }
+
+    rc = os_mutex_release(&g_shell_cmd_list_lock);
+    if (rc != 0) {
+        goto err;
+    }
+    return (0);
+err:
+    return (rc);
+}
+
+int
+shell_cmd_register(struct shell_cmd *sc)
+{
+    int rc;
+
+    /* Add the command that is being registered. */
+    rc = shell_cmd_list_lock();
+    if (rc != 0) {
+        goto err;
+    }
+
+    STAILQ_INSERT_TAIL(&g_shell_cmd_list, sc, sc_next);
+
+    rc = shell_cmd_list_unlock();
+    if (rc != 0) {
+        goto err;
+    }
+
+    return (0);
+err:
+    return (rc);
+}
+
+static int
+shell_cmd(char *cmd, char **argv, int argc)
+{
+    struct shell_cmd *sc;
+    int rc;
+
+    rc = shell_cmd_list_lock();
+    if (rc != 0) {
+        goto err;
+    }
+
+    STAILQ_FOREACH(sc, &g_shell_cmd_list, sc_next) {
+        if (!strcmp(sc->sc_cmd, cmd)) {
+            break;
+        }
+    }
+
+    rc = shell_cmd_list_unlock();
+    if (rc != 0) {
+        goto err;
+    }
+
+    if (sc) {
+        sc->sc_cmd_func(argc, argv);
+    } else {
+        console_printf("Unknown command %s\n", cmd);
+    }
+
+    return (0);
+err:
+    return (rc);
+}
+
+static int
+shell_process_command(char *line, int len)
+{
+    char *tok;
+    char *tok_ptr;
+    int argc;
+
+    tok_ptr = NULL;
+    tok = strtok_r(line, " ", &tok_ptr);
+    argc = 0;
+    while (argc < SHELL_MAX_ARGS - 1 && tok != NULL) {
+        argv[argc++] = tok;
+
+        tok = strtok_r(NULL, " ", &tok_ptr);
+    }
+
+    /* Terminate the argument list with a null pointer. */
+    argv[argc] = NULL;
+
+    if (argc) {
+        (void) shell_cmd(argv[0], argv, argc);
+    }
+    else {
+        console_printf("\n");
+    }
+    console_print_prompt();
+    return (0);
+}
+
+
+static int
+shell_nlip_process(char *data, int len)
+{
+    uint16_t copy_len;
+    int rc;
+    struct os_mbuf *m;
+    uint16_t crc;
+
+    rc = base64_decode(data, data);
+    if (rc < 0) {
+        goto err;
+    }
+    len = rc;
+
+    if (g_nlip_mbuf == NULL) {
+        if (len < 2) {
+            rc = -1;
+            goto err;
+        }
+
+        g_nlip_expected_len = ntohs(*(uint16_t *) data);
+        g_nlip_mbuf = os_msys_get_pkthdr(g_nlip_expected_len, 0);
+        if (!g_nlip_mbuf) {
+            rc = -1;
+            goto err;
+        }
+
+        data += sizeof(uint16_t);
+        len -= sizeof(uint16_t);
+    }
+
+    copy_len = min(g_nlip_expected_len - OS_MBUF_PKTHDR(g_nlip_mbuf)->omp_len,
+            len);
+
+    rc = os_mbuf_copyinto(g_nlip_mbuf, OS_MBUF_PKTHDR(g_nlip_mbuf)->omp_len,
+            data, copy_len);
+    if (rc != 0) {
+        goto err;
+    }
+
+    if (OS_MBUF_PKTHDR(g_nlip_mbuf)->omp_len == g_nlip_expected_len) {
+        if (g_shell_nlip_in_func) {
+            crc = CRC16_INITIAL_CRC;
+            for (m = g_nlip_mbuf; m; m = SLIST_NEXT(m, om_next)) {
+                crc = crc16_ccitt(crc, m->om_data, m->om_len);
+            }
+            if (crc == 0 && g_nlip_expected_len >= sizeof(crc)) {
+                os_mbuf_adj(g_nlip_mbuf, -sizeof(crc));
+                g_shell_nlip_in_func(g_nlip_mbuf, g_shell_nlip_in_arg);
+            } else {
+                os_mbuf_free_chain(g_nlip_mbuf);
+            }
+        } else {
+            os_mbuf_free_chain(g_nlip_mbuf);
+        }
+        g_nlip_mbuf = NULL;
+        g_nlip_expected_len = 0;
+    }
+
+    return (0);
+err:
+    return (rc);
+}
+
+static int
+shell_nlip_mtx(struct os_mbuf *m)
+{
+#define SHELL_NLIP_MTX_BUF_SIZE (12)
+    uint8_t readbuf[SHELL_NLIP_MTX_BUF_SIZE];
+    char encodebuf[BASE64_ENCODE_SIZE(SHELL_NLIP_MTX_BUF_SIZE)];
+    char pkt_seq[2] = { SHELL_NLIP_PKT_START1, SHELL_NLIP_PKT_START2 };
+    char esc_seq[2] = { SHELL_NLIP_DATA_START1, SHELL_NLIP_DATA_START2 };
+    uint16_t totlen;
+    uint16_t dlen;
+    uint16_t off;
+    uint16_t crc;
+    int rb_off;
+    int elen;
+    uint16_t nwritten;
+    uint16_t linelen;
+    int rc;
+    struct os_mbuf *tmp;
+    void *ptr;
+
+    /* Convert the mbuf into a packet.
+     *
+     * starts with 06 09
+     * base64 encode:
+     *  - total packet length (uint16_t)
+     *  - data
+     *  - crc
+     * base64 encoded data must be less than 122 bytes per line to
+     * avoid overflows and adhere to convention.
+     *
+     * continuation packets are preceded by 04 20 until the entire
+     * buffer has been sent.
+     */
+    crc = CRC16_INITIAL_CRC;
+    for (tmp = m; tmp; tmp = SLIST_NEXT(tmp, om_next)) {
+        crc = crc16_ccitt(crc, tmp->om_data, tmp->om_len);
+    }
+    crc = htons(crc);
+    ptr = os_mbuf_extend(m, sizeof(crc));
+    if (!ptr) {
+        rc = -1;
+        goto err;
+    }
+    memcpy(ptr, &crc, sizeof(crc));
+
+    totlen = OS_MBUF_PKTHDR(m)->omp_len;
+    nwritten = 0;
+    off = 0;
+
+    /* Start a packet */
+    console_write(pkt_seq, sizeof(pkt_seq));
+
+    linelen = 0;
+
+    rb_off = 2;
+    dlen = htons(totlen);
+    memcpy(readbuf, &dlen, sizeof(dlen));
+
+    while (totlen > 0) {
+        dlen = min(SHELL_NLIP_MTX_BUF_SIZE - rb_off, totlen);
+
+        rc = os_mbuf_copydata(m, off, dlen, readbuf + rb_off);
+        if (rc != 0) {
+            goto err;
+        }
+        off += dlen;
+
+        /* If the next packet will overwhelm the line length, truncate
+         * this line.
+         */
+        if (linelen +
+                BASE64_ENCODE_SIZE(min(SHELL_NLIP_MTX_BUF_SIZE - rb_off,
+                        totlen - dlen)) >= 120) {
+            elen = base64_encode(readbuf, dlen + rb_off, encodebuf, 1);
+            console_write(encodebuf, elen);
+            console_write("\n", 1);
+            console_write(esc_seq, sizeof(esc_seq));
+            linelen = 0;
+        } else {
+            elen = base64_encode(readbuf, dlen + rb_off, encodebuf, 0);
+            console_write(encodebuf, elen);
+            linelen += elen;
+        }
+
+        rb_off = 0;
+
+        nwritten += elen;
+        totlen -= dlen;
+    }
+
+    elen = base64_pad(encodebuf, linelen);
+    console_write(encodebuf, elen);
+
+    console_write("\n", 1);
+
+    return (0);
+err:
+    return (rc);
+}
+
+static void
+shell_nlip_mqueue_process(void)
+{
+    struct os_mbuf *m;
+
+    /* Copy data out of the mbuf 12 bytes at a time and write it to
+     * the console.
+     */
+    while (1) {
+        m = os_mqueue_get(&g_shell_nlip_mq);
+        if (!m) {
+            break;
+        }
+
+        (void) shell_nlip_mtx(m);
+
+        os_mbuf_free_chain(m);
+    }
+}
+
+int
+shell_nlip_input_register(shell_nlip_input_func_t nf, void *arg)
+{
+    g_shell_nlip_in_func = nf;
+    g_shell_nlip_in_arg = arg;
+
+    return (0);
+}
+
+int
+shell_nlip_output(struct os_mbuf *m)
+{
+    int rc;
+
+    rc = os_mqueue_put(&g_shell_nlip_mq, &shell_evq, m);
+    if (rc != 0) {
+        goto err;
+    }
+
+    return (0);
+err:
+    return (rc);
+}
+
+static void
+shell_read_console(void)
+{
+    int rc;
+    int full_line;
+
+    while (1) {
+        rc = console_read(shell_line + shell_line_len,
+          MYNEWT_VAL(SHELL_MAX_INPUT_LEN) - shell_line_len, &full_line);
+        if (rc <= 0 && !full_line) {
+            break;
+        }
+        shell_line_len += rc;
+        if (full_line) {
+            if (shell_line_len > 2) {
+                if (shell_line[0] == SHELL_NLIP_PKT_START1 &&
+                        shell_line[1] == SHELL_NLIP_PKT_START2) {
+                    if (g_nlip_mbuf) {
+                        os_mbuf_free_chain(g_nlip_mbuf);
+                        g_nlip_mbuf = NULL;
+                    }
+                    g_nlip_expected_len = 0;
+
+                    rc = shell_nlip_process(&shell_line[2], shell_line_len - 2);
+                } else if (shell_line[0] == SHELL_NLIP_DATA_START1 &&
+                        shell_line[1] == SHELL_NLIP_DATA_START2) {
+                    rc = shell_nlip_process(&shell_line[2], shell_line_len - 2);
+                } else {
+                    shell_process_command(shell_line, shell_line_len);
+                }
+            } else {
+                shell_process_command(shell_line, shell_line_len);
+            }
+            shell_line_len = 0;
+        }
+    }
+}
+
+
+static void
+shell_task_func(void *arg)
+{
+    struct os_event *ev;
+
+    while (1) {
+        ev = os_eventq_get(&shell_evq);
+        assert(ev != NULL);
+
+        switch (ev->ev_type) {
+            case OS_EVENT_T_CONSOLE_RDY:
+                // Read and process all available lines on the console.
+                shell_read_console();
+                break;
+            case OS_EVENT_T_MQUEUE_DATA:
+                shell_nlip_mqueue_process();
+                break;
+        }
+    }
+}
+
+/**
+ * This function is called from the console APIs when data is available
+ * to be read.  This is either a full line, or when the
+ * console buffer (default = 128) is full.
+ */
+void
+shell_console_rx_cb(void)
+{
+    os_eventq_put(&shell_evq, &console_rdy_ev);
+}
+
+static int
+shell_echo_cmd(int argc, char **argv)
+{
+    int i;
+
+    for (i = 1; i < argc; i++) {
+        console_write(argv[i], strlen(argv[i]));
+        console_write(" ", sizeof(" ")-1);
+    }
+    console_write("\n", sizeof("\n")-1);
+
+    return (0);
+}
+
+static int
+shell_help_cmd(int argc, char **argv)
+{
+    int rc;
+    int i = 0;
+    struct shell_cmd *sc;
+
+    rc = shell_cmd_list_lock();
+    if (rc != 0) {
+        return -1;
+    }
+    console_printf("Commands:\n");
+    STAILQ_FOREACH(sc, &g_shell_cmd_list, sc_next) {
+        console_printf("%9s ", sc->sc_cmd);
+        if (i++ % SHELL_HELP_PER_LINE == SHELL_HELP_PER_LINE - 1) {
+            console_printf("\n");
+        }
+    }
+    if (i % SHELL_HELP_PER_LINE) {
+        console_printf("\n");
+    }
+    shell_cmd_list_unlock();
+
+    return (0);
+}
+
+void
+shell_init(void)
+{
+#if !MYNEWT_VAL(SHELL_TASK)
+    return;
+#endif
+
+    int rc;
+
+    free(shell_line);
+    shell_line = NULL;
+
+#if MYNEWT_VAL(SHELL_MAX_INPUT_LEN) > 0
+    shell_line = malloc(MYNEWT_VAL(SHELL_MAX_INPUT_LEN));
+    SYSINIT_PANIC_ASSERT(shell_line != NULL);
+#endif
+
+    rc = os_mutex_init(&g_shell_cmd_list_lock);
+    SYSINIT_PANIC_ASSERT(rc == 0);
+
+    rc = shell_cmd_register(&g_shell_echo_cmd);
+    SYSINIT_PANIC_ASSERT(rc == 0);
+
+    rc = shell_cmd_register(&g_shell_help_cmd);
+    SYSINIT_PANIC_ASSERT(rc == 0);
+
+    rc = shell_cmd_register(&g_shell_prompt_cmd);
+    SYSINIT_PANIC_ASSERT(rc == 0);
+
+    rc = shell_cmd_register(&g_shell_os_tasks_display_cmd);
+    SYSINIT_PANIC_ASSERT(rc == 0);
+
+    rc = shell_cmd_register(&g_shell_os_mpool_display_cmd);
+    SYSINIT_PANIC_ASSERT(rc == 0);
+
+    rc = shell_cmd_register(&g_shell_os_date_cmd);
+    SYSINIT_PANIC_ASSERT(rc == 0);
+
+    os_eventq_init(&shell_evq);
+    os_mqueue_init(&g_shell_nlip_mq, NULL);
+    console_rdy_ev.ev_type = OS_EVENT_T_CONSOLE_RDY;
+    console_init(shell_console_rx_cb);
+
+    rc = os_task_init(&shell_task, "shell", shell_task_func,
+            NULL, MYNEWT_VAL(SHELL_TASK_PRIO), OS_WAIT_FOREVER, shell_stack,
+            MYNEWT_VAL(SHELL_STACK_SIZE));
+    SYSINIT_PANIC_ASSERT(rc == 0);
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/shell/src/shell_os.c
----------------------------------------------------------------------
diff --git a/sys/shell/src/shell_os.c b/sys/shell/src/shell_os.c
new file mode 100644
index 0000000..283d429
--- /dev/null
+++ b/sys/shell/src/shell_os.c
@@ -0,0 +1,156 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include "os/os.h"
+
+#include "os/queue.h"
+#include "os/os_time.h"
+
+#include "console/console.h"
+#include "shell/shell.h"
+#include "shell_priv.h"
+
+#include <assert.h>
+#include <string.h>
+#include <util/datetime.h>
+
+int 
+shell_os_tasks_display_cmd(int argc, char **argv)
+{
+    struct os_task *prev_task;
+    struct os_task_info oti;
+    char *name;
+    int found;
+
+    name = NULL;
+    found = 0;
+
+    if (argc > 1 && strcmp(argv[1], "")) {
+        name = argv[1];
+    }
+
+    console_printf("Tasks: \n");
+    prev_task = NULL;
+    while (1) {
+        prev_task = os_task_info_get_next(prev_task, &oti);
+        if (prev_task == NULL) {
+            break;
+        }
+
+        if (name) {
+            if (strcmp(name, oti.oti_name)) {
+                continue;
+            } else {
+                found = 1;
+            }
+        }
+
+        console_printf("  %s (prio: %u, tid: %u, lcheck: %lu, ncheck: %lu, "
+                "flags: 0x%x, ssize: %u, susage: %u, cswcnt: %lu, "
+                "tot_run_time: %lums)\n",
+                oti.oti_name, oti.oti_prio, oti.oti_taskid, 
+                (unsigned long)oti.oti_last_checkin,
+                (unsigned long)oti.oti_next_checkin, oti.oti_flags,
+                oti.oti_stksize, oti.oti_stkusage, (unsigned long)oti.oti_cswcnt,
+                (unsigned long)oti.oti_runtime);
+
+    }
+
+    if (name && !found) {
+        console_printf("Couldn't find task with name %s\n", name);
+    }
+
+    return (0);
+}
+
+int 
+shell_os_mpool_display_cmd(int argc, char **argv)
+{
+    struct os_mempool *mp;
+    struct os_mempool_info omi;
+    char *name;
+    int found;
+
+    name = NULL;
+    found = 0;
+
+    if (argc > 1 && strcmp(argv[1], "")) {
+        name = argv[1];
+    }
+
+    console_printf("Mempools: \n");
+    mp = NULL;
+    while (1) {
+        mp = os_mempool_info_get_next(mp, &omi);
+        if (mp == NULL) {
+            break;
+        }
+
+        if (name) {
+            if (strcmp(name, omi.omi_name)) {
+                continue;
+            } else {
+                found = 1;
+            }
+        }
+
+        console_printf("  %s (blksize: %d, nblocks: %d, nfree: %d)\n",
+                omi.omi_name, omi.omi_block_size, omi.omi_num_blocks,
+                omi.omi_num_free);
+    }
+
+    if (name && !found) {
+        console_printf("Couldn't find a memory pool with name %s\n", 
+                name);
+    }
+
+    return (0);
+}
+
+int
+shell_os_date_cmd(int argc, char **argv)
+{
+    struct os_timeval tv;
+    struct os_timezone tz;
+    char buf[DATETIME_BUFSIZE];
+    int rc;
+
+    argc--; argv++;     /* skip command name */
+
+    if (argc == 0) {
+        /* Display the current datetime */
+        rc = os_gettimeofday(&tv, &tz);
+        assert(rc == 0);
+        rc = format_datetime(&tv, &tz, buf, sizeof(buf));
+        assert(rc == 0);
+        console_printf("%s\n", buf);
+    } else if (argc == 1) {
+        /* Set the current datetime */
+        rc = parse_datetime(*argv, &tv, &tz);
+        if (rc == 0) {
+            rc = os_settimeofday(&tv, &tz);
+        } else {
+            console_printf("Invalid datetime\n");
+        }
+    } else {
+        rc = -1;
+    }
+
+    return (rc);
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/shell/src/shell_priv.h
----------------------------------------------------------------------
diff --git a/sys/shell/src/shell_priv.h b/sys/shell/src/shell_priv.h
new file mode 100644
index 0000000..4e035e0
--- /dev/null
+++ b/sys/shell/src/shell_priv.h
@@ -0,0 +1,27 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 __SHELL_PRIV_H_
+#define __SHELL_PRIV_H_
+
+int shell_os_tasks_display_cmd(int argc, char **argv);
+int shell_os_mpool_display_cmd(int argc, char **argv);
+int shell_os_date_cmd(int argc, char **argv);
+
+#endif /* __SHELL_PRIV_H_ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/shell/src/shell_prompt.c
----------------------------------------------------------------------
diff --git a/sys/shell/src/shell_prompt.c b/sys/shell/src/shell_prompt.c
new file mode 100644
index 0000000..d1402ad
--- /dev/null
+++ b/sys/shell/src/shell_prompt.c
@@ -0,0 +1,69 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include <string.h>
+#include "shell/shell.h"
+#include <console/console.h>
+
+static char shell_prompt = '>';
+
+void console_set_prompt(char p);
+
+/**
+ * Handles the 'prompt' command
+ * with set argument, sets the prompt to the provided char
+ * with the show argument, echos the current prompt
+ * otherwise echos the prompt and the usage message
+ */
+int
+shell_prompt_cmd(int argc, char **argv)
+{
+    int rc;
+
+    rc = shell_cmd_list_lock();
+    if (rc != 0) {
+        return -1;
+    }
+    if(argc > 1){
+        if(!strcmp(argv[1], "show")){
+            console_printf("Prompt character: %c\n", shell_prompt);
+        }   
+        else if (!strcmp(argv[1],"set")){
+            shell_prompt = argv[2][0];
+            console_printf("Prompt set to: %c\n", argv[2][0]);
+            console_set_prompt(argv[2][0]);
+        }
+        else {
+            goto usage;
+        }
+        
+    } 
+    else {
+        goto usage;
+        
+    }
+usage:
+    console_printf("Usage: prompt [set|show] [prompt_char]\n");
+    
+    shell_cmd_list_unlock();
+    
+    return (0);
+  
+}
+ 
\ No newline at end of file



[06/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/console/full/src/cons_tty.c
----------------------------------------------------------------------
diff --git a/sys/console/full/src/cons_tty.c b/sys/console/full/src/cons_tty.c
new file mode 100644
index 0000000..157ed48
--- /dev/null
+++ b/sys/console/full/src/cons_tty.c
@@ -0,0 +1,561 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include <inttypes.h>
+#include <assert.h>
+#include "syscfg/syscfg.h"
+#include "sysinit/sysinit.h"
+#include "os/os.h"
+#include "uart/uart.h"
+#include "bsp/bsp.h"
+
+#include "console/console.h"
+#include "console/prompt.h"
+
+/** Indicates whether the previous line of output was completed. */
+int console_is_midline;
+
+#define CONSOLE_TX_BUF_SZ       32      /* IO buffering, must be power of 2 */
+#define CONSOLE_RX_BUF_SZ       128
+#define CONSOLE_RX_CHUNK        16
+
+#if MYNEWT_VAL(CONSOLE_HIST_ENABLE)
+#define CONSOLE_HIST_SZ         32
+#endif
+
+#define CONSOLE_DEL             0x7f    /* del character */
+#define CONSOLE_ESC             0x1b    /* esc character */
+#define CONSOLE_LEFT            'D'     /* esc-[-D emitted when moving left */
+#define CONSOLE_UP              'A'     /* esc-[-A moving up */
+#define CONSOLE_RIGHT           'C'     /* esc-[-C moving right */
+#define CONSOLE_DOWN            'B'     /* esc-[-B moving down */
+
+#define CONSOLE_HEAD_INC(cr)    (((cr)->cr_head + 1) & ((cr)->cr_size - 1))
+#define CONSOLE_TAIL_INC(cr)    (((cr)->cr_tail + 1) & ((cr)->cr_size - 1))
+
+typedef void (*console_write_char)(char);
+void console_print_prompt(void);
+
+struct console_ring {
+    uint8_t cr_head;
+    uint8_t cr_tail;
+    uint8_t cr_size;
+    uint8_t _pad;
+    uint8_t *cr_buf;
+};
+
+struct console_tty {
+    struct uart_dev *ct_dev;
+    struct console_ring ct_tx;
+    uint8_t ct_tx_buf[CONSOLE_TX_BUF_SZ]; /* must be after console_ring */
+    struct console_ring ct_rx;
+    uint8_t ct_rx_buf[CONSOLE_RX_BUF_SZ]; /* must be after console_ring */
+    console_rx_cb ct_rx_cb; /* callback that input is ready */
+    console_write_char ct_write_char;
+    uint8_t ct_echo_off:1;
+    uint8_t ct_esc_seq:2;
+} console_tty;
+
+#if MYNEWT_VAL(CONSOLE_HIST_ENABLE)
+struct console_hist {
+    uint8_t ch_head;
+    uint8_t ch_tail;
+    uint8_t ch_size;
+    uint8_t ch_curr;
+    uint8_t ch_buf[CONSOLE_HIST_SZ][CONSOLE_RX_BUF_SZ];
+} console_hist;
+#endif
+
+static void
+console_add_char(struct console_ring *cr, char ch)
+{
+    cr->cr_buf[cr->cr_head] = ch;
+    cr->cr_head = CONSOLE_HEAD_INC(cr);
+}
+
+static uint8_t
+console_pull_char(struct console_ring *cr)
+{
+    uint8_t ch;
+
+    ch = cr->cr_buf[cr->cr_tail];
+    cr->cr_tail = CONSOLE_TAIL_INC(cr);
+    return ch;
+}
+
+static int
+console_pull_char_head(struct console_ring *cr)
+{
+    if (cr->cr_head != cr->cr_tail) {
+        cr->cr_head = (cr->cr_head - 1) & (cr->cr_size - 1);
+        return 0;
+    } else {
+        return -1;
+    }
+}
+
+static void
+console_queue_char(char ch)
+{
+    struct console_tty *ct = &console_tty;
+    int sr;
+
+    OS_ENTER_CRITICAL(sr);
+    while (CONSOLE_HEAD_INC(&ct->ct_tx) == ct->ct_tx.cr_tail) {
+        /* TX needs to drain */
+        uart_start_tx(ct->ct_dev);
+        OS_EXIT_CRITICAL(sr);
+        if (os_started()) {
+            os_time_delay(1);
+        }
+        OS_ENTER_CRITICAL(sr);
+    }
+    console_add_char(&ct->ct_tx, ch);
+    OS_EXIT_CRITICAL(sr);
+}
+
+#if MYNEWT_VAL(CONSOLE_HIST_ENABLE)
+static void
+console_hist_init(void)
+{
+    struct console_hist *ch = &console_hist;
+
+    ch->ch_head = 0;
+    ch->ch_tail = 0;
+    ch->ch_curr = 0;
+    ch->ch_size = CONSOLE_HIST_SZ;
+}
+
+static void
+console_hist_add(struct console_ring *rx)
+{
+    struct console_hist *ch = &console_hist;
+    uint8_t *str = ch->ch_buf[ch->ch_head];
+    uint8_t tail;
+    uint8_t empty = 1;
+
+    tail = rx->cr_tail;
+    while (tail != rx->cr_head) {
+        *str = rx->cr_buf[tail];
+        if (*str != ' ' && *str != '\t' && *str != '\n') {
+            empty = 0;
+        }
+        if (*str == '\n') {
+            *str = '\0';
+            /* don't save empty history */
+            if (empty) {
+                return;
+            }
+            break;
+        }
+        str++;
+        tail = (tail + 1) % CONSOLE_RX_BUF_SZ;
+    }
+
+    ch->ch_head = (ch->ch_head + 1) & (ch->ch_size - 1);
+    ch->ch_curr = ch->ch_head;
+
+    /* buffer full, start overwriting old history */
+    if (ch->ch_head == ch->ch_tail) {
+        ch->ch_tail = (ch->ch_tail + 1) & (ch->ch_size - 1);
+    }
+}
+
+static int
+console_hist_move(struct console_ring *rx, uint8_t *tx_buf, uint8_t direction)
+{
+    struct console_hist *ch = &console_hist;
+    uint8_t *str = NULL;
+    int space = 0;
+    int i;
+    uint8_t limit = direction == CONSOLE_UP ? ch->ch_tail : ch->ch_head;
+
+    /* no more history to return in this direction */
+    if (ch->ch_curr == limit) {
+        return 0;
+    }
+
+    if (direction == CONSOLE_UP) {
+        ch->ch_curr = (ch->ch_curr - 1) & (ch->ch_size - 1);
+    } else {
+        ch->ch_curr = (ch->ch_curr + 1) & (ch->ch_size - 1);
+    }
+
+    /* consume all chars */
+    while (console_pull_char_head(rx) == 0) {
+        /* do nothing */
+    }
+
+    str = ch->ch_buf[ch->ch_curr];
+    for (i = 0; i < CONSOLE_RX_BUF_SZ; ++i) {
+        if (str[i] == '\0') {
+            break;
+        }
+        tx_buf[i] = str[i];
+        console_add_char(rx, str[i]);
+        space++;
+    }
+
+    return space;
+}
+#endif
+
+static void
+console_blocking_tx(char ch)
+{
+    struct console_tty *ct = &console_tty;
+
+    uart_blocking_tx(ct->ct_dev, ch);
+}
+
+/*
+ * Flush cnt characters from console output queue.
+ */
+static void
+console_tx_flush(struct console_tty *ct, int cnt)
+{
+    int i;
+    uint8_t byte;
+
+    for (i = 0; i < cnt; i++) {
+        if (ct->ct_tx.cr_head == ct->ct_tx.cr_tail) {
+            /*
+             * Queue is empty.
+             */
+            break;
+        }
+        byte = console_pull_char(&ct->ct_tx);
+        console_blocking_tx(byte);
+    }
+}
+
+void
+console_blocking_mode(void)
+{
+    struct console_tty *ct = &console_tty;
+    int sr;
+
+    OS_ENTER_CRITICAL(sr);
+    if (ct->ct_write_char) {
+        ct->ct_write_char = console_blocking_tx;
+
+        console_tx_flush(ct, CONSOLE_TX_BUF_SZ);
+    }
+    OS_EXIT_CRITICAL(sr);
+}
+
+void
+console_echo(int on)
+{
+    struct console_tty *ct = &console_tty;
+
+    ct->ct_echo_off = !on;
+}
+
+size_t
+console_file_write(void *arg, const char *str, size_t cnt)
+{
+    struct console_tty *ct = &console_tty;
+    int i;
+
+    if (!ct->ct_write_char) {
+        return cnt;
+    }
+    for (i = 0; i < cnt; i++) {
+        if (str[i] == '\n') {
+            ct->ct_write_char('\r');
+        }
+        ct->ct_write_char(str[i]);
+    }
+    if (cnt > 0) {
+        console_is_midline = str[cnt - 1] != '\n';
+    }
+    uart_start_tx(ct->ct_dev);
+    return cnt;
+}
+
+void
+console_write(const char *str, int cnt)
+{
+    console_file_write(NULL, str, cnt);
+}
+
+int
+console_read(char *str, int cnt, int *newline)
+{
+    struct console_tty *ct = &console_tty;
+    struct console_ring *cr = &ct->ct_rx;
+    int sr;
+    int i;
+    uint8_t ch;
+
+    *newline = 0;
+    OS_ENTER_CRITICAL(sr);
+    for (i = 0; i < cnt; i++) {
+        if (cr->cr_head == cr->cr_tail) {
+            break;
+        }
+
+        if ((i & (CONSOLE_RX_CHUNK - 1)) == (CONSOLE_RX_CHUNK - 1)) {
+            /*
+             * Make a break from blocking interrupts during the copy.
+             */
+            OS_EXIT_CRITICAL(sr);
+            OS_ENTER_CRITICAL(sr);
+        }
+
+        ch = console_pull_char(cr);
+        if (ch == '\n') {
+            *str = '\0';
+            *newline = 1;
+            break;
+        }
+        *str++ = ch;
+    }
+    OS_EXIT_CRITICAL(sr);
+    if (i > 0 || *newline) {
+        uart_start_rx(ct->ct_dev);
+    }
+    return i;
+}
+
+/*
+ * Interrupts disabled when console_tx_char/console_rx_char are called.
+ */
+static int
+console_tx_char(void *arg)
+{
+    struct console_tty *ct = (struct console_tty *)arg;
+    struct console_ring *cr = &ct->ct_tx;
+
+    if (cr->cr_head == cr->cr_tail) {
+        /*
+         * No more data.
+         */
+        return -1;
+    }
+    return console_pull_char(cr);
+}
+
+static int
+console_buf_space(struct console_ring *cr)
+{
+    int space;
+
+    space = (cr->cr_tail - cr->cr_head) & (cr->cr_size - 1);
+    return space - 1;
+}
+
+static int
+console_rx_char(void *arg, uint8_t data)
+{
+    struct console_tty *ct = (struct console_tty *)arg;
+    struct console_ring *tx = &ct->ct_tx;
+    struct console_ring *rx = &ct->ct_rx;
+    int tx_space = 0;
+    int i;
+#if MYNEWT_VAL(CONSOLE_HIST_ENABLE)
+    uint8_t tx_buf[CONSOLE_RX_BUF_SZ];
+#else
+    uint8_t tx_buf[3];
+#endif
+
+    if (CONSOLE_HEAD_INC(&ct->ct_rx) == ct->ct_rx.cr_tail) {
+        /*
+         * RX queue full. Reader must drain this.
+         */
+        if (ct->ct_rx_cb) {
+            ct->ct_rx_cb();
+        }
+        return -1;
+    }
+
+    /* echo */
+    switch (data) {
+    case '\r':
+    case '\n':
+        /*
+         * linefeed
+         */
+        tx_buf[0] = '\n';
+        tx_buf[1] = '\r';
+        tx_space = 2;
+        console_add_char(rx, '\n');
+#if MYNEWT_VAL(CONSOLE_HIST_ENABLE)
+        console_hist_add(rx);
+#endif
+        if (ct->ct_rx_cb) {
+            ct->ct_rx_cb();
+        }
+        break;
+    case CONSOLE_ESC:
+        ct->ct_esc_seq = 1;
+        goto out;
+    case '[':
+        if (ct->ct_esc_seq == 1) {
+            ct->ct_esc_seq = 2;
+            goto out;
+        } else {
+            goto queue_char;
+        }
+        break;
+    case CONSOLE_LEFT:
+        if (ct->ct_esc_seq == 2) {
+            goto backspace;
+        } else {
+            goto queue_char;
+        }
+        break;
+    case CONSOLE_UP:
+    case CONSOLE_DOWN:
+        if (ct->ct_esc_seq != 2) {
+            goto queue_char;
+        }
+#if MYNEWT_VAL(CONSOLE_HIST_ENABLE)
+        tx_space = console_hist_move(rx, tx_buf, data);
+        tx_buf[tx_space] = 0;
+        ct->ct_esc_seq = 0;
+        /*
+         * when moving up, stop on oldest history entry
+         * when moving down, let it delete input before leaving...
+         */
+        if (data == CONSOLE_UP && tx_space == 0) {
+            goto out;
+        }
+        if (!ct->ct_echo_off) {
+            /* HACK: clean line by backspacing up to maximum possible space */
+            for (i = 0; i < CONSOLE_TX_BUF_SZ; i++) {
+                if (console_buf_space(tx) < 3) {
+                    console_tx_flush(ct, 3);
+                }
+                console_add_char(tx, '\b');
+                console_add_char(tx, ' ');
+                console_add_char(tx, '\b');
+                uart_start_tx(ct->ct_dev);
+            }
+            if (tx_space == 0) {
+                goto out;
+            }
+        } else {
+            goto queue_char;
+        }
+        break;
+#else
+        ct->ct_esc_seq = 0;
+        goto out;
+#endif
+    case CONSOLE_RIGHT:
+        if (ct->ct_esc_seq == 2) {
+            data = ' '; /* add space */
+        }
+        goto queue_char;
+    case '\b':
+    case CONSOLE_DEL:
+backspace:
+        /*
+         * backspace
+         */
+        ct->ct_esc_seq = 0;
+        if (console_pull_char_head(rx) == 0) {
+            /*
+             * Only wipe out char if we can pull stuff off from head.
+             */
+            tx_buf[0] = '\b';
+            tx_buf[1] = ' ';
+            tx_buf[2] = '\b';
+            tx_space = 3;
+        } else {
+            goto out;
+        }
+        break;
+    default:
+queue_char:
+        tx_buf[0] = data;
+        tx_space = 1;
+        ct->ct_esc_seq = 0;
+        console_add_char(rx, data);
+        break;
+    }
+    if (!ct->ct_echo_off) {
+        if (console_buf_space(tx) < tx_space) {
+            console_tx_flush(ct, tx_space);
+        }
+        for (i = 0; i < tx_space; i++) {
+            console_add_char(tx, tx_buf[i]);
+        }
+        uart_start_tx(ct->ct_dev);
+    }
+out:
+    return 0;
+}
+
+int
+console_is_init(void)
+{
+    struct console_tty *ct = &console_tty;
+
+    return (ct->ct_dev != NULL);
+}
+
+int
+console_init(console_rx_cb rx_cb)
+{
+    struct console_tty *ct = &console_tty;
+    struct uart_conf uc = {
+        .uc_speed = CONSOLE_UART_SPEED,
+        .uc_databits = 8,
+        .uc_stopbits = 1,
+        .uc_parity = UART_PARITY_NONE,
+        .uc_flow_ctl = UART_FLOW_CTL_NONE,
+        .uc_tx_char = console_tx_char,
+        .uc_rx_char = console_rx_char,
+        .uc_cb_arg = ct
+    };
+
+    ct->ct_rx_cb = rx_cb;
+    if (!ct->ct_dev) {
+        ct->ct_tx.cr_size = CONSOLE_TX_BUF_SZ;
+        ct->ct_tx.cr_buf = ct->ct_tx_buf;
+        ct->ct_rx.cr_size = CONSOLE_RX_BUF_SZ;
+        ct->ct_rx.cr_buf = ct->ct_rx_buf;
+        ct->ct_write_char = console_queue_char;
+
+        ct->ct_dev = (struct uart_dev *)os_dev_open(CONSOLE_UART,
+          OS_TIMEOUT_NEVER, &uc);
+        if (!ct->ct_dev) {
+            return -1;
+        }
+        ct->ct_echo_off = ! MYNEWT_VAL(CONSOLE_ECHO);
+    }
+
+#if MYNEWT_VAL(CONSOLE_HIST_ENABLE)
+    console_hist_init();
+#endif
+
+    return 0;
+}
+
+void
+console_pkg_init(void)
+{
+    int rc;
+
+    rc = console_init(NULL);
+    SYSINIT_PANIC_ASSERT(rc == 0);
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/console/full/src/prompt.c
----------------------------------------------------------------------
diff --git a/sys/console/full/src/prompt.c b/sys/console/full/src/prompt.c
new file mode 100644
index 0000000..33e37c0
--- /dev/null
+++ b/sys/console/full/src/prompt.c
@@ -0,0 +1,49 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+
+#include "console/console.h"
+#include "console/prompt.h"
+#include <syscfg/syscfg.h>
+
+/* console prompt, always followed by a space */
+static char console_prompt[] = " > ";
+static char do_prompt = MYNEWT_VAL(CONSOLE_PROMPT);
+
+
+/* set the prompt character, leave the space */
+void
+console_set_prompt(char p)
+{
+    do_prompt = 1;
+    console_prompt[1] = p;
+}
+
+void console_no_prompt(void) {
+    do_prompt = 0;
+}
+
+/* print the prompt to the console */
+void
+console_print_prompt(void)
+{
+    if (do_prompt) {
+        console_printf("%s", console_prompt);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/console/stub/include/console/console.h
----------------------------------------------------------------------
diff --git a/sys/console/stub/include/console/console.h b/sys/console/stub/include/console/console.h
new file mode 100644
index 0000000..99db457
--- /dev/null
+++ b/sys/console/stub/include/console/console.h
@@ -0,0 +1,71 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 __CONSOLE_H__
+#define __CONSOLE_H__
+
+#include <stdarg.h>
+
+typedef void (*console_rx_cb)(void);
+
+static int inline
+console_is_init(void)
+{
+    return 0;
+}
+
+static int inline
+console_init(console_rx_cb rxcb)
+{
+    return 0;
+}
+
+static int inline
+console_read(char *str, int cnt, int *newline)
+{
+    *newline = 0;
+    return 0;
+}
+
+static void inline
+console_blocking_mode(void)
+{
+}
+
+static void inline
+console_write(const char *str, int cnt)
+{
+}
+
+static void inline console_printf(const char *fmt, ...)
+    __attribute__ ((format (printf, 1, 2)));
+
+static void inline
+console_printf(const char *fmt, ...)
+{
+}
+
+static void inline
+console_echo(int on)
+{
+}
+
+#define console_is_midline  (0)
+
+#endif /* __CONSOLE__ */
+

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/console/stub/include/console/prompt.h
----------------------------------------------------------------------
diff --git a/sys/console/stub/include/console/prompt.h b/sys/console/stub/include/console/prompt.h
new file mode 100644
index 0000000..a1d72c9
--- /dev/null
+++ b/sys/console/stub/include/console/prompt.h
@@ -0,0 +1,35 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 __CONSOLE_PROMPT_H__
+#define __CONSOLE_PROMPT_H__
+nclude/console/prompt.h
+
+#include <stdarg.h>
+
+/* print console prompt */
+void console_print_prompt(void);
+/* set the console prompt character */
+void console_set_prompt(char);
+
+
+extern char console_prompt[2];
+
+
+#endif /* __CONSOLE_PROMPT_H__ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/console/stub/pkg.yml
----------------------------------------------------------------------
diff --git a/sys/console/stub/pkg.yml b/sys/console/stub/pkg.yml
new file mode 100644
index 0000000..4159e8c
--- /dev/null
+++ b/sys/console/stub/pkg.yml
@@ -0,0 +1,27 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+#
+
+pkg.name: sys/console/stub
+pkg.description: Stub for text-based IO interface.
+pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
+pkg.homepage: "http://mynewt.apache.org/"
+pkg.keywords:
+
+pkg.deps:
+pkg.apis: console

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/coredump/pkg.yml
----------------------------------------------------------------------
diff --git a/sys/coredump/pkg.yml b/sys/coredump/pkg.yml
index 3da1277..2c84751 100644
--- a/sys/coredump/pkg.yml
+++ b/sys/coredump/pkg.yml
@@ -26,5 +26,5 @@ pkg.keywords:
 
 pkg.deps:
     - hw/hal
-    - libs/bootutil
+    - boot/bootutil
     - libs/imgmgr

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/fcb/README.md
----------------------------------------------------------------------
diff --git a/sys/fcb/README.md b/sys/fcb/README.md
deleted file mode 100644
index 5d13ccd..0000000
--- a/sys/fcb/README.md
+++ /dev/null
@@ -1,58 +0,0 @@
-<!--
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you 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.
-#
--->
-
-# Flash circular buffer
-
-# Overview
-
-Storage of elements in flash in FIFO fashion. Elements are appended to the of the area until storage space is exhausted. Then the oldest sector should be erased and that can be used in storing new entries.
-
-# API
-
-fcb_init()
-  - initialize fcb for a given array of flash sectors
-
-fcb_append()
-  - reserve space to store an element
-fcb_append_finish()
-  - storage of the element is finished; can calculate CRC for it
-
-fcb_walk(cb, sector)
-  - call cb for every element in the buffer. Or for every element in
-    a particular flash sector, if sector is specified
-fcb_getnext(elem)
-  - return element following elem
-
-fcb_rotate()
-  - erase oldest used sector, and make it current
-
-# Usage
-
-To add an element to circular buffer:
-1. call fcb_append() to get location; if this fails due to lack of space,
-   call fcb_rotate()
-2. use flash_area_write() to write contents
-3. call fcb_append_finish() when done
-
-To read contents of the circular buffer:
-1. call fcb_walk() with callback
-2. within callback: copy in data from the element using flash_area_read(),
-   call fcb_rotate() when all elements from a given sector have been read

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/fcb/include/fcb/fcb.h
----------------------------------------------------------------------
diff --git a/sys/fcb/include/fcb/fcb.h b/sys/fcb/include/fcb/fcb.h
deleted file mode 100644
index a6b3f88..0000000
--- a/sys/fcb/include/fcb/fcb.h
+++ /dev/null
@@ -1,134 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 __SYS_FCB_H_
-#define __SYS_FCB_H_
-
-/*
- * Flash circular buffer.
- */
-#include <inttypes.h>
-#include <limits.h>
-
-#include <hal/flash_map.h>
-
-#include <os/os_mutex.h>
-
-#define FCB_MAX_LEN	(CHAR_MAX | CHAR_MAX << 7) /* Max length of element */
-
-/*
- * Entry location is pointer to area (within fcb->f_sectors), and offset
- * within that area.
- */
-struct fcb_entry {
-    struct flash_area *fe_area;	/* ptr to area within fcb->f_sectors */
-    uint32_t fe_elem_off;	/* start of entry */
-    uint32_t fe_data_off;	/* start of data */
-    uint16_t fe_data_len;	/* size of data area */
-};
-
-struct fcb {
-    /* Caller of fcb_init fills this in */
-    uint32_t f_magic;		/* As placed on the disk */
-    uint8_t f_version;  	/* Current version number of the data */
-    uint8_t f_sector_cnt;	/* Number of elements in sector array */
-    uint8_t f_scratch_cnt;	/* How many sectors should be kept empty */
-    struct flash_area *f_sectors; /* Array of sectors, must be contiguous */
-
-    /* Flash circular buffer internal state */
-    struct os_mutex f_mtx;	/* Locking for accessing the FCB data */
-    struct flash_area *f_oldest;
-    struct fcb_entry f_active;
-    uint16_t f_active_id;
-    uint8_t f_align;		/* writes to flash have to aligned to this */
-};
-
-/*
- * Error codes.
- */
-#define FCB_OK		0
-#define FCB_ERR_ARGS	-1
-#define FCB_ERR_FLASH	-2
-#define FCB_ERR_NOVAR   -3
-#define FCB_ERR_NOSPACE	-4
-#define FCB_ERR_NOMEM	-5
-#define FCB_ERR_CRC	-6
-#define FCB_ERR_MAGIC   -7
-
-int fcb_init(struct fcb *fcb);
-
-/*
- * fcb_log is needed as the number of entries in a log
- */
-struct fcb_log {
-    struct fcb fl_fcb;
-    uint8_t fl_entries;
-};
-
-int log_fcb_init(struct fcb_log *fcblog, struct fcb *fcb, uint16_t entries);
-
-/*
- * fcb_append() appends an entry to circular buffer. When writing the
- * contents for the entry, use loc->fl_area and loc->fl_data_off with
- * flash_area_write(). When you're finished, call fcb_append_finish() with
- * loc as argument.
- */
-int fcb_append(struct fcb *, uint16_t len, struct fcb_entry *loc);
-int fcb_append_finish(struct fcb *, struct fcb_entry *append_loc);
-
-/*
- * Walk over all log entries in FCB, or entries in a given flash_area.
- * cb gets called for every entry. If cb wants to stop the walk, it should
- * return non-zero value.
- *
- * Entry data can be read using flash_area_read(), using
- * loc->fe_area, loc->fe_data_off, and loc->fe_data_len as arguments.
- */
-typedef int (*fcb_walk_cb)(struct fcb_entry *loc, void *arg);
-int fcb_walk(struct fcb *, struct flash_area *, fcb_walk_cb cb, void *cb_arg);
-int fcb_getnext(struct fcb *, struct fcb_entry *loc);
-
-/*
- * Erases the data from oldest sector.
- */
-int fcb_rotate(struct fcb *);
-
-/*
- * Start using the scratch block.
- */
-int fcb_append_to_scratch(struct fcb *);
-
-/*
- * How many sectors are unused.
- */
-int fcb_free_sector_cnt(struct fcb *fcb);
-
-/*
- * Whether FCB has any data.
- */
-int fcb_is_empty(struct fcb *fcb);
-
-int
-fcb_offset_last_n(struct fcb *fcb, uint8_t entries, uint32_t *last_n_off);
-
-/*
- * Clears FCB passed to it
- */
-int fcb_clear(struct fcb *fcb);
-
-#endif /* __SYS_FLASHVAR_H_ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/fcb/pkg.yml
----------------------------------------------------------------------
diff --git a/sys/fcb/pkg.yml b/sys/fcb/pkg.yml
deleted file mode 100644
index bba5355..0000000
--- a/sys/fcb/pkg.yml
+++ /dev/null
@@ -1,28 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you 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.
-#
-
-pkg.name: sys/fcb
-pkg.description: Flash circular buffer.
-pkg.keywords:
-    - flash
-    - storage
-    - log
-
-pkg.deps:
-    - libs/os

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/fcb/src/fcb.c
----------------------------------------------------------------------
diff --git a/sys/fcb/src/fcb.c b/sys/fcb/src/fcb.c
deleted file mode 100644
index fb85508..0000000
--- a/sys/fcb/src/fcb.c
+++ /dev/null
@@ -1,258 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-#include <limits.h>
-#include <stdlib.h>
-
-#include "fcb/fcb.h"
-#include "fcb_priv.h"
-#include "string.h"
-
-int
-fcb_init(struct fcb *fcb)
-{
-    struct flash_area *fap;
-    int rc;
-    int i;
-    int max_align = 1;
-    int align;
-    int oldest = -1, newest = -1;
-    struct flash_area *oldest_fap = NULL, *newest_fap = NULL;
-    struct fcb_disk_area fda;
-
-    if (!fcb->f_sectors || fcb->f_sector_cnt - fcb->f_scratch_cnt < 1) {
-        return FCB_ERR_ARGS;
-    }
-
-    /* Fill last used, first used */
-    for (i = 0; i < fcb->f_sector_cnt; i++) {
-        fap = &fcb->f_sectors[i];
-        align = flash_area_align(fap);
-        if (align > max_align) {
-            max_align = flash_area_align(fap);
-        }
-        rc = fcb_sector_hdr_read(fcb, fap, &fda);
-        if (rc <= 0) {
-            continue;
-        }
-        if (oldest < 0) {
-            oldest = newest = fda.fd_id;
-            oldest_fap = newest_fap = fap;
-            continue;
-        }
-        if (FCB_ID_GT(fda.fd_id, newest)) {
-            newest = fda.fd_id;
-            newest_fap = fap;
-        } else if (FCB_ID_GT(oldest, fda.fd_id)) {
-            oldest = fda.fd_id;
-            oldest_fap = fap;
-        }
-    }
-    if (oldest < 0) {
-        /*
-         * No initialized areas.
-         */
-        oldest_fap = newest_fap = &fcb->f_sectors[0];
-        rc = fcb_sector_hdr_init(fcb, oldest_fap, 0);
-        if (rc) {
-            return rc;
-        }
-        newest = oldest = 0;
-    }
-    fcb->f_align = max_align;
-    fcb->f_oldest = oldest_fap;
-    fcb->f_active.fe_area = newest_fap;
-    fcb->f_active.fe_elem_off = sizeof(struct fcb_disk_area);
-    fcb->f_active_id = newest;
-
-    while (1) {
-        rc = fcb_getnext_in_area(fcb, &fcb->f_active);
-        if (rc == FCB_ERR_NOVAR) {
-            rc = FCB_OK;
-            break;
-        }
-        if (rc != 0) {
-            break;
-        }
-    }
-    os_mutex_init(&fcb->f_mtx);
-    return rc;
-}
-
-int
-fcb_free_sector_cnt(struct fcb *fcb)
-{
-    int i;
-    struct flash_area *fa;
-
-    fa = fcb->f_active.fe_area;
-    for (i = 0; i < fcb->f_sector_cnt; i++) {
-        fa = fcb_getnext_area(fcb, fa);
-        if (fa == fcb->f_oldest) {
-            break;
-        }
-    }
-    return i;
-}
-
-int
-fcb_is_empty(struct fcb *fcb)
-{
-    return (fcb->f_active.fe_area == fcb->f_oldest &&
-      fcb->f_active.fe_elem_off == sizeof(struct fcb_disk_area));
-}
-
-/**
- * Length of an element is encoded in 1 or 2 bytes.
- * 1 byte for lengths < 128 bytes, and 2 bytes for < 16384.
- */
-int
-fcb_put_len(uint8_t *buf, uint16_t len)
-{
-    if (len < CHAR_MAX) {
-        buf[0] = len;
-        return 1;
-    } else if (len < FCB_MAX_LEN) {
-        buf[0] = (len & 0x7f) | 0x80;
-        buf[1] = len >> 7;
-        return 2;
-    } else {
-        return FCB_ERR_ARGS;
-    }
-}
-
-int
-fcb_get_len(uint8_t *buf, uint16_t *len)
-{
-    int rc;
-
-    if (buf[0] & 0x80) {
-        if (buf[0] == 0xff && buf[1] == 0xff) {
-            return FCB_ERR_NOVAR;
-        }
-        *len = (buf[0] & 0x7f) | (buf[1] << 7);
-        rc = 2;
-    } else {
-        *len = buf[0];
-        rc = 1;
-    }
-    return rc;
-}
-
-/**
- * Initialize erased sector for use.
- */
-int
-fcb_sector_hdr_init(struct fcb *fcb, struct flash_area *fap, uint16_t id)
-{
-    struct fcb_disk_area fda;
-    int rc;
-
-    fda.fd_magic = fcb->f_magic;
-    fda.fd_ver = fcb->f_version;
-    fda._pad = 0xff;
-    fda.fd_id = id;
-
-    rc = flash_area_write(fap, 0, &fda, sizeof(fda));
-    if (rc) {
-        return FCB_ERR_FLASH;
-    }
-    return 0;
-}
-
-/**
- * Checks whether FCB sector contains data or not.
- * Returns <0 in error.
- * Returns 0 if sector is unused;
- * Returns 1 if sector has data.
- */
-int
-fcb_sector_hdr_read(struct fcb *fcb, struct flash_area *fap,
-  struct fcb_disk_area *fdap)
-{
-    struct fcb_disk_area fda;
-    int rc;
-
-    if (!fdap) {
-        fdap = &fda;
-    }
-    rc = flash_area_read(fap, 0, fdap, sizeof(*fdap));
-    if (rc) {
-        return FCB_ERR_FLASH;
-    }
-    if (fdap->fd_magic == 0xffffffff) {
-        return 0;
-    }
-    if (fdap->fd_magic != fcb->f_magic) {
-        return FCB_ERR_MAGIC;
-    }
-    return 1;
-}
-
-/**
- * Finds n-th element offset
- * @param0 ptr to fcb
- * @param1 n number of entries to calculate offset before
- * @param2 ptr to the offset before to be returned
- * @return 0 on success; non-zero on failure
- */
-int
-fcb_offset_last_n(struct fcb *fcb, uint8_t entries, uint32_t *last_n_off)
-{
-    struct fcb_entry loc;
-    struct fcb_entry start;
-    int i;
-
-    i = 0;
-    memset(&loc, 0, sizeof(loc));
-    while (!fcb_getnext(fcb, &loc)) {
-        if (i == 0) {
-            /* Start from the beginning of fcb entries */
-            *last_n_off = loc.fe_elem_off;
-            start = loc;
-        }
-        /* Update last_n_off after n entries and keep updating */
-        if (i >= (entries - 1)) {
-            fcb_getnext(fcb, &start);
-            *last_n_off = start.fe_elem_off;
-        }
-        i++;
-    }
-
-    return 0;
-}
-
-/**
- * Clear fcb
- * @param fcb
- * @return 0 on success; non-zero on failure
- */
-int
-fcb_clear(struct fcb *fcb)
-{
-    int rc;
-
-    rc = 0;
-    while (!fcb_is_empty(fcb)) {
-        rc = fcb_rotate(fcb);
-        if (rc) {
-            break;
-        }
-    }
-    return rc;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/fcb/src/fcb_append.c
----------------------------------------------------------------------
diff --git a/sys/fcb/src/fcb_append.c b/sys/fcb/src/fcb_append.c
deleted file mode 100644
index c7f5ddc..0000000
--- a/sys/fcb/src/fcb_append.c
+++ /dev/null
@@ -1,143 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-#include <stddef.h>
-
-#include "fcb/fcb.h"
-#include "fcb_priv.h"
-
-static struct flash_area *
-fcb_new_area(struct fcb *fcb, int cnt)
-{
-    struct flash_area *fa;
-    struct flash_area *rfa;
-    int i;
-
-    rfa = NULL;
-    i = 0;
-    fa = fcb->f_active.fe_area;
-    do {
-        fa = fcb_getnext_area(fcb, fa);
-        if (!rfa) {
-            rfa = fa;
-        }
-        if (fa == fcb->f_oldest) {
-            return NULL;
-        }
-    } while (i++ < cnt);
-    return rfa;
-}
-
-/*
- * Take one of the scratch blocks into use, if at all possible.
- */
-int
-fcb_append_to_scratch(struct fcb *fcb)
-{
-    struct flash_area *fa;
-    int rc;
-
-    fa = fcb_new_area(fcb, 0);
-    if (!fa) {
-        return FCB_ERR_NOSPACE;
-    }
-    rc = fcb_sector_hdr_init(fcb, fa, fcb->f_active_id + 1);
-    if (rc) {
-        return rc;
-    }
-    fcb->f_active.fe_area = fa;
-    fcb->f_active.fe_elem_off = sizeof(struct fcb_disk_area);
-    fcb->f_active_id++;
-    return FCB_OK;
-}
-
-int
-fcb_append(struct fcb *fcb, uint16_t len, struct fcb_entry *append_loc)
-{
-    struct fcb_entry *active;
-    struct flash_area *fa;
-    uint8_t tmp_str[2];
-    int cnt;
-    int rc;
-
-    cnt = fcb_put_len(tmp_str, len);
-    if (cnt < 0) {
-        return cnt;
-    }
-    cnt = fcb_len_in_flash(fcb, cnt);
-    len = fcb_len_in_flash(fcb, len) + fcb_len_in_flash(fcb, FCB_CRC_SZ);
-
-    rc = os_mutex_pend(&fcb->f_mtx, OS_WAIT_FOREVER);
-    if (rc && rc != OS_NOT_STARTED) {
-        return FCB_ERR_ARGS;
-    }
-    active = &fcb->f_active;
-    if (active->fe_elem_off + len + cnt > active->fe_area->fa_size) {
-        fa = fcb_new_area(fcb, fcb->f_scratch_cnt);
-        if (!fa || (fa->fa_size <
-            sizeof(struct fcb_disk_area) + len + cnt)) {
-            rc = FCB_ERR_NOSPACE;
-            goto err;
-        }
-        rc = fcb_sector_hdr_init(fcb, fa, fcb->f_active_id + 1);
-        if (rc) {
-            goto err;
-        }
-        fcb->f_active.fe_area = fa;
-        fcb->f_active.fe_elem_off = sizeof(struct fcb_disk_area);
-        fcb->f_active_id++;
-    }
-
-    rc = flash_area_write(active->fe_area, active->fe_elem_off, tmp_str, cnt);
-    if (rc) {
-        rc = FCB_ERR_FLASH;
-        goto err;
-    }
-    append_loc->fe_area = active->fe_area;
-    append_loc->fe_elem_off = active->fe_elem_off;
-    append_loc->fe_data_off = active->fe_elem_off + cnt;
-
-    active->fe_elem_off = append_loc->fe_data_off + len;
-
-    os_mutex_release(&fcb->f_mtx);
-
-    return FCB_OK;
-err:
-    os_mutex_release(&fcb->f_mtx);
-    return rc;
-}
-
-int
-fcb_append_finish(struct fcb *fcb, struct fcb_entry *loc)
-{
-    int rc;
-    uint8_t crc8;
-    uint32_t off;
-
-    rc = fcb_elem_crc8(fcb, loc, &crc8);
-    if (rc) {
-        return rc;
-    }
-    off = loc->fe_data_off + fcb_len_in_flash(fcb, loc->fe_data_len);
-
-    rc = flash_area_write(loc->fe_area, off, &crc8, sizeof(crc8));
-    if (rc) {
-        return FCB_ERR_FLASH;
-    }
-    return 0;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/fcb/src/fcb_elem_info.c
----------------------------------------------------------------------
diff --git a/sys/fcb/src/fcb_elem_info.c b/sys/fcb/src/fcb_elem_info.c
deleted file mode 100644
index 58e5210..0000000
--- a/sys/fcb/src/fcb_elem_info.c
+++ /dev/null
@@ -1,101 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include <util/crc8.h>
-
-#include "fcb/fcb.h"
-#include "fcb_priv.h"
-
-/*
- * Given offset in flash area, fill in rest of the fcb_entry, and crc8 over
- * the data.
- */
-int
-fcb_elem_crc8(struct fcb *fcb, struct fcb_entry *loc, uint8_t *c8p)
-{
-    uint8_t tmp_str[FCB_TMP_BUF_SZ];
-    int cnt;
-    int blk_sz;
-    uint8_t crc8;
-    uint16_t len;
-    uint32_t off;
-    uint32_t end;
-    int rc;
-
-    if (loc->fe_elem_off + 2 > loc->fe_area->fa_size) {
-        return FCB_ERR_NOVAR;
-    }
-    rc = flash_area_read(loc->fe_area, loc->fe_elem_off, tmp_str, 2);
-    if (rc) {
-        return FCB_ERR_FLASH;
-    }
-
-    cnt = fcb_get_len(tmp_str, &len);
-    if (cnt < 0) {
-        return cnt;
-    }
-    loc->fe_data_off = loc->fe_elem_off + fcb_len_in_flash(fcb, cnt);
-    loc->fe_data_len = len;
-
-    crc8 = crc8_init();
-    crc8 = crc8_calc(crc8, tmp_str, cnt);
-
-    off = loc->fe_data_off;
-    end = loc->fe_data_off + len;
-    for (; off < end; off += blk_sz) {
-        blk_sz = end - off;
-        if (blk_sz > sizeof(tmp_str)) {
-            blk_sz = sizeof(tmp_str);
-        }
-
-        rc = flash_area_read(loc->fe_area, off, tmp_str, blk_sz);
-        if (rc) {
-            return FCB_ERR_FLASH;
-        }
-        crc8 = crc8_calc(crc8, tmp_str, blk_sz);
-    }
-    *c8p = crc8;
-
-    return 0;
-}
-
-int
-fcb_elem_info(struct fcb *fcb, struct fcb_entry *loc)
-{
-    int rc;
-    uint8_t crc8;
-    uint8_t fl_crc8;
-    uint32_t off;
-
-    rc = fcb_elem_crc8(fcb, loc, &crc8);
-    if (rc) {
-        return rc;
-    }
-    off = loc->fe_data_off + fcb_len_in_flash(fcb, loc->fe_data_len);
-
-    rc = flash_area_read(loc->fe_area, off, &fl_crc8, sizeof(fl_crc8));
-    if (rc) {
-        return FCB_ERR_FLASH;
-    }
-
-    if (fl_crc8 != crc8) {
-        return FCB_ERR_CRC;
-    }
-    return 0;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/fcb/src/fcb_getnext.c
----------------------------------------------------------------------
diff --git a/sys/fcb/src/fcb_getnext.c b/sys/fcb/src/fcb_getnext.c
deleted file mode 100644
index be92979..0000000
--- a/sys/fcb/src/fcb_getnext.c
+++ /dev/null
@@ -1,132 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-#include <stddef.h>
-
-#include "fcb/fcb.h"
-#include "fcb_priv.h"
-
-int
-fcb_getnext_in_area(struct fcb *fcb, struct fcb_entry *loc)
-{
-    int rc;
-
-    rc = fcb_elem_info(fcb, loc);
-    if (rc == 0 || rc == FCB_ERR_CRC) {
-        do {
-            loc->fe_elem_off = loc->fe_data_off +
-              fcb_len_in_flash(fcb, loc->fe_data_len) +
-              fcb_len_in_flash(fcb, FCB_CRC_SZ);
-            rc = fcb_elem_info(fcb, loc);
-            if (rc != FCB_ERR_CRC) {
-                break;
-            }
-        } while (rc == FCB_ERR_CRC);
-    }
-    return rc;
-}
-
-struct flash_area *
-fcb_getnext_area(struct fcb *fcb, struct flash_area *fap)
-{
-    fap++;
-    if (fap >= &fcb->f_sectors[fcb->f_sector_cnt]) {
-        fap = &fcb->f_sectors[0];
-    }
-    return fap;
-}
-
-int
-fcb_getnext_nolock(struct fcb *fcb, struct fcb_entry *loc)
-{
-    int rc;
-
-    if (loc->fe_area == NULL) {
-        /*
-         * Find the first one we have in flash.
-         */
-        loc->fe_area = fcb->f_oldest;
-    }
-    if (loc->fe_elem_off == 0) {
-        /*
-         * If offset is zero, we serve the first entry from the area.
-         */
-        loc->fe_elem_off = sizeof(struct fcb_disk_area);
-        rc = fcb_elem_info(fcb, loc);
-        switch (rc) {
-        case 0:
-            return 0;
-        case FCB_ERR_CRC:
-            break;
-        default:
-            goto next_sector;
-        }
-    } else {
-        rc = fcb_getnext_in_area(fcb, loc);
-        if (rc == 0) {
-            return 0;
-        }
-        if (rc == FCB_ERR_NOVAR) {
-            goto next_sector;
-        }
-    }
-    while (rc == FCB_ERR_CRC) {
-        rc = fcb_getnext_in_area(fcb, loc);
-        if (rc == 0) {
-            return 0;
-        }
-
-        if (rc != FCB_ERR_CRC) {
-            /*
-             * Moving to next sector.
-             */
-next_sector:
-            if (loc->fe_area == fcb->f_active.fe_area) {
-                return FCB_ERR_NOVAR;
-            }
-            loc->fe_area = fcb_getnext_area(fcb, loc->fe_area);
-            loc->fe_elem_off = sizeof(struct fcb_disk_area);
-            rc = fcb_elem_info(fcb, loc);
-            switch (rc) {
-            case 0:
-                return 0;
-            case FCB_ERR_CRC:
-                break;
-            default:
-                goto next_sector;
-            }
-        }
-    }
-
-    return 0;
-}
-
-int
-fcb_getnext(struct fcb *fcb, struct fcb_entry *loc)
-{
-    int rc;
-
-    rc = os_mutex_pend(&fcb->f_mtx, OS_WAIT_FOREVER);
-    if (rc && rc != OS_NOT_STARTED) {
-        return FCB_ERR_ARGS;
-    }
-    rc = fcb_getnext_nolock(fcb, loc);
-    os_mutex_release(&fcb->f_mtx);
-
-    return rc;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/fcb/src/fcb_priv.h
----------------------------------------------------------------------
diff --git a/sys/fcb/src/fcb_priv.h b/sys/fcb/src/fcb_priv.h
deleted file mode 100644
index b7a9e0b..0000000
--- a/sys/fcb/src/fcb_priv.h
+++ /dev/null
@@ -1,57 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 __SYS_FCB_PRIV_H_
-#define __SYS_FCB_PRIV_H_
-
-#define FCB_CRC_SZ	sizeof(uint8_t)
-#define FCB_TMP_BUF_SZ	32
-
-#define FCB_ID_GT(a, b) (((int16_t)(a) - (int16_t)(b)) > 0)
-
-struct fcb_disk_area {
-    uint32_t fd_magic;
-    uint8_t  fd_ver;
-    uint8_t  _pad;
-    uint16_t fd_id;
-};
-
-int fcb_put_len(uint8_t *buf, uint16_t len);
-int fcb_get_len(uint8_t *buf, uint16_t *len);
-
-static inline int
-fcb_len_in_flash(struct fcb *fcb, uint16_t len)
-{
-    if (fcb->f_align <= 1) {
-        return len;
-    }
-    return (len + (fcb->f_align - 1)) & ~(fcb->f_align - 1);
-}
-
-int fcb_getnext_in_area(struct fcb *fcb, struct fcb_entry *loc);
-struct flash_area *fcb_getnext_area(struct fcb *fcb, struct flash_area *fap);
-int fcb_getnext_nolock(struct fcb *fcb, struct fcb_entry *loc);
-
-int fcb_elem_info(struct fcb *, struct fcb_entry *);
-int fcb_elem_crc8(struct fcb *, struct fcb_entry *loc, uint8_t *crc8p);
-
-int fcb_sector_hdr_init(struct fcb *, struct flash_area *fap, uint16_t id);
-int fcb_sector_hdr_read(struct fcb *, struct flash_area *fap,
-  struct fcb_disk_area *fdap);
-
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/fcb/src/fcb_rotate.c
----------------------------------------------------------------------
diff --git a/sys/fcb/src/fcb_rotate.c b/sys/fcb/src/fcb_rotate.c
deleted file mode 100644
index 7b6df58..0000000
--- a/sys/fcb/src/fcb_rotate.c
+++ /dev/null
@@ -1,56 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include "fcb/fcb.h"
-#include "fcb_priv.h"
-
-int
-fcb_rotate(struct fcb *fcb)
-{
-    struct flash_area *fap;
-    int rc = 0;
-
-    rc = os_mutex_pend(&fcb->f_mtx, OS_WAIT_FOREVER);
-    if (rc && rc != OS_NOT_STARTED) {
-        return FCB_ERR_ARGS;
-    }
-
-    rc = flash_area_erase(fcb->f_oldest, 0, fcb->f_oldest->fa_size);
-    if (rc) {
-        rc = FCB_ERR_FLASH;
-        goto out;
-    }
-    if (fcb->f_oldest == fcb->f_active.fe_area) {
-        /*
-         * Need to create a new active area, as we're wiping the current.
-         */
-        fap = fcb_getnext_area(fcb, fcb->f_oldest);
-        rc = fcb_sector_hdr_init(fcb, fap, fcb->f_active_id + 1);
-        if (rc) {
-            goto out;
-        }
-        fcb->f_active.fe_area = fap;
-        fcb->f_active.fe_elem_off = sizeof(struct fcb_disk_area);
-        fcb->f_active_id++;
-    }
-    fcb->f_oldest = fcb_getnext_area(fcb, fcb->f_oldest);
-out:
-    os_mutex_release(&fcb->f_mtx);
-    return rc;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/fcb/src/fcb_walk.c
----------------------------------------------------------------------
diff --git a/sys/fcb/src/fcb_walk.c b/sys/fcb/src/fcb_walk.c
deleted file mode 100644
index e557262..0000000
--- a/sys/fcb/src/fcb_walk.c
+++ /dev/null
@@ -1,53 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include "fcb/fcb.h"
-#include "fcb_priv.h"
-
-/*
- * Call 'cb' for every element in flash circular buffer. If fap is specified,
- * only elements with that flash_area are reported.
- */
-int
-fcb_walk(struct fcb *fcb, struct flash_area *fap, fcb_walk_cb cb, void *cb_arg)
-{
-    struct fcb_entry loc;
-    int rc;
-
-    loc.fe_area = fap;
-    loc.fe_elem_off = 0;
-
-    rc = os_mutex_pend(&fcb->f_mtx, OS_WAIT_FOREVER);
-    if (rc && rc != OS_NOT_STARTED) {
-        return FCB_ERR_ARGS;
-    }
-    while ((rc = fcb_getnext_nolock(fcb, &loc)) != FCB_ERR_NOVAR) {
-        os_mutex_release(&fcb->f_mtx);
-        if (fap && loc.fe_area != fap) {
-            return 0;
-        }
-        rc = cb(&loc, cb_arg);
-        if (rc) {
-            return rc;
-        }
-        os_mutex_pend(&fcb->f_mtx, OS_WAIT_FOREVER);
-    }
-    os_mutex_release(&fcb->f_mtx);
-    return 0;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/fcb/test/pkg.yml
----------------------------------------------------------------------
diff --git a/sys/fcb/test/pkg.yml b/sys/fcb/test/pkg.yml
deleted file mode 100644
index 31a8669..0000000
--- a/sys/fcb/test/pkg.yml
+++ /dev/null
@@ -1,30 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you 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.
-#
-pkg.name: sys/fcb/test
-pkg.type: unittest
-pkg.description: "FCB unit tests."
-pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
-pkg.homepage: "http://mynewt.apache.org/"
-pkg.keywords:
-
-pkg.deps: 
-    - libs/testutil
-    - sys/fcb
-
-pkg.deps.SELFTEST:
-    - libs/console/stub

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/fcb/test/src/fcb_test.c
----------------------------------------------------------------------
diff --git a/sys/fcb/test/src/fcb_test.c b/sys/fcb/test/src/fcb_test.c
deleted file mode 100644
index b172eb0..0000000
--- a/sys/fcb/test/src/fcb_test.c
+++ /dev/null
@@ -1,672 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include <stdio.h>
-#include <string.h>
-
-#include "syscfg/syscfg.h"
-#include "os/os.h"
-#include "testutil/testutil.h"
-
-#include "fcb/fcb.h"
-#include "fcb/../../src/fcb_priv.h"
-
-static struct fcb test_fcb;
-
-static struct flash_area test_fcb_area[] = {
-    [0] = {
-        .fa_flash_id = 0,
-        .fa_off = 0,
-        .fa_size = 0x4000, /* 16K */
-    },
-    [1] = {
-        .fa_flash_id = 0,
-        .fa_off = 0x4000,
-        .fa_size = 0x4000
-    },
-    [2] = {
-        .fa_flash_id = 0,
-        .fa_off = 0x8000,
-        .fa_size = 0x4000
-    },
-    [3] = {
-        .fa_flash_id = 0,
-        .fa_off = 0xc000,
-        .fa_size = 0x4000
-    }
-};
-
-static void
-fcb_test_wipe(void)
-{
-    int i;
-    int rc;
-    struct flash_area *fap;
-
-    for (i = 0; i < sizeof(test_fcb_area) / sizeof(test_fcb_area[0]); i++) {
-        fap = &test_fcb_area[i];
-        rc = flash_area_erase(fap, 0, fap->fa_size);
-        TEST_ASSERT(rc == 0);
-    }
-}
-
-TEST_CASE(fcb_test_len)
-{
-    uint8_t buf[3];
-    uint16_t len;
-    uint16_t len2;
-    int rc;
-
-    for (len = 0; len < FCB_MAX_LEN; len++) {
-        rc = fcb_put_len(buf, len);
-        TEST_ASSERT(rc == 1 || rc == 2);
-
-        rc = fcb_get_len(buf, &len2);
-        TEST_ASSERT(rc == 1 || rc == 2);
-
-        TEST_ASSERT(len == len2);
-    }
-}
-
-TEST_CASE(fcb_test_init)
-{
-    int rc;
-    struct fcb *fcb;
-
-    fcb = &test_fcb;
-    memset(fcb, 0, sizeof(*fcb));
-
-    rc = fcb_init(fcb);
-    TEST_ASSERT(rc == FCB_ERR_ARGS);
-
-    fcb->f_sectors = test_fcb_area;
-
-    rc = fcb_init(fcb);
-    TEST_ASSERT(rc == FCB_ERR_ARGS);
-
-    fcb->f_sector_cnt = 2;
-    rc = fcb_init(fcb);
-    TEST_ASSERT(rc == 0);
-}
-
-static int
-fcb_test_empty_walk_cb(struct fcb_entry *loc, void *arg)
-{
-    TEST_ASSERT(0);
-    return 0;
-}
-
-TEST_CASE(fcb_test_empty_walk)
-{
-    int rc;
-    struct fcb *fcb;
-
-    fcb_test_wipe();
-    fcb = &test_fcb;
-    memset(fcb, 0, sizeof(*fcb));
-
-    fcb->f_sector_cnt = 2;
-    fcb->f_sectors = test_fcb_area;
-
-    rc = fcb_init(fcb);
-    TEST_ASSERT(rc == 0);
-
-    rc = fcb_walk(fcb, 0, fcb_test_empty_walk_cb, NULL);
-    TEST_ASSERT(rc == 0);
-}
-
-static uint8_t
-fcb_test_append_data(int msg_len, int off)
-{
-    return (msg_len ^ off);
-}
-
-static int
-fcb_test_data_walk_cb(struct fcb_entry *loc, void *arg)
-{
-    uint16_t len;
-    uint8_t test_data[128];
-    int rc;
-    int i;
-    int *var_cnt = (int *)arg;
-
-    len = loc->fe_data_len;
-
-    TEST_ASSERT(len == *var_cnt);
-
-    rc = flash_area_read(loc->fe_area, loc->fe_data_off, test_data, len);
-    TEST_ASSERT(rc == 0);
-
-    for (i = 0; i < len; i++) {
-        TEST_ASSERT(test_data[i] == fcb_test_append_data(len, i));
-    }
-    (*var_cnt)++;
-    return 0;
-}
-
-TEST_CASE(fcb_test_append)
-{
-    int rc;
-    struct fcb *fcb;
-    struct fcb_entry loc;
-    uint8_t test_data[128];
-    int i;
-    int j;
-    int var_cnt;
-
-    fcb_test_wipe();
-    fcb = &test_fcb;
-    memset(fcb, 0, sizeof(*fcb));
-    fcb->f_sector_cnt = 2;
-    fcb->f_sectors = test_fcb_area;
-
-    rc = fcb_init(fcb);
-    TEST_ASSERT(rc == 0);
-
-    for (i = 0; i < sizeof(test_data); i++) {
-        for (j = 0; j < i; j++) {
-            test_data[j] = fcb_test_append_data(i, j);
-        }
-        rc = fcb_append(fcb, i, &loc);
-        TEST_ASSERT_FATAL(rc == 0);
-        rc = flash_area_write(loc.fe_area, loc.fe_data_off, test_data, i);
-        TEST_ASSERT(rc == 0);
-        rc = fcb_append_finish(fcb, &loc);
-        TEST_ASSERT(rc == 0);
-    }
-
-    var_cnt = 0;
-    rc = fcb_walk(fcb, 0, fcb_test_data_walk_cb, &var_cnt);
-    TEST_ASSERT(rc == 0);
-    TEST_ASSERT(var_cnt == sizeof(test_data));
-}
-
-TEST_CASE(fcb_test_append_too_big)
-{
-    struct fcb *fcb;
-    int rc;
-    int len;
-    struct fcb_entry elem_loc;
-
-    fcb_test_wipe();
-    fcb = &test_fcb;
-    memset(fcb, 0, sizeof(*fcb));
-    fcb->f_sector_cnt = 2;
-    fcb->f_sectors = test_fcb_area;
-
-    rc = fcb_init(fcb);
-    TEST_ASSERT(rc == 0);
-
-    /*
-     * Max element which fits inside sector is
-     * sector size - (disk header + crc + 1-2 bytes of length).
-     */
-    len = fcb->f_active.fe_area->fa_size;
-
-    rc = fcb_append(fcb, len, &elem_loc);
-    TEST_ASSERT(rc != 0);
-
-    len--;
-    rc = fcb_append(fcb, len, &elem_loc);
-    TEST_ASSERT(rc != 0);
-
-    len -= sizeof(struct fcb_disk_area);
-    rc = fcb_append(fcb, len, &elem_loc);
-    TEST_ASSERT(rc != 0);
-
-    len = fcb->f_active.fe_area->fa_size -
-      (sizeof(struct fcb_disk_area) + 1 + 2);
-    rc = fcb_append(fcb, len, &elem_loc);
-    TEST_ASSERT(rc == 0);
-
-    rc = fcb_append_finish(fcb, &elem_loc);
-    TEST_ASSERT(rc == 0);
-
-    rc = fcb_elem_info(fcb, &elem_loc);
-    TEST_ASSERT(rc == 0);
-    TEST_ASSERT(elem_loc.fe_data_len == len);
-}
-
-struct append_arg {
-    int *elem_cnts;
-};
-
-static int
-fcb_test_cnt_elems_cb(struct fcb_entry *loc, void *arg)
-{
-    struct append_arg *aa = (struct append_arg *)arg;
-    int idx;
-
-    idx = loc->fe_area - &test_fcb_area[0];
-    aa->elem_cnts[idx]++;
-    return 0;
-}
-
-TEST_CASE(fcb_test_append_fill)
-{
-    struct fcb *fcb;
-    int rc;
-    int i;
-    struct fcb_entry loc;
-    uint8_t test_data[128];
-    int elem_cnts[2] = {0, 0};
-    int aa_together_cnts[2];
-    struct append_arg aa_together = {
-        .elem_cnts = aa_together_cnts
-    };
-    int aa_separate_cnts[2];
-    struct append_arg aa_separate = {
-        .elem_cnts = aa_separate_cnts
-    };
-
-    fcb_test_wipe();
-    fcb = &test_fcb;
-    memset(fcb, 0, sizeof(*fcb));
-    fcb->f_sector_cnt = 2;
-    fcb->f_sectors = test_fcb_area;
-
-    rc = fcb_init(fcb);
-    TEST_ASSERT(rc == 0);
-
-    for (i = 0; i < sizeof(test_data); i++) {
-        test_data[i] = fcb_test_append_data(sizeof(test_data), i);
-    }
-
-    while (1) {
-        rc = fcb_append(fcb, sizeof(test_data), &loc);
-        if (rc == FCB_ERR_NOSPACE) {
-            break;
-        }
-        if (loc.fe_area == &test_fcb_area[0]) {
-            elem_cnts[0]++;
-        } else if (loc.fe_area == &test_fcb_area[1]) {
-            elem_cnts[1]++;
-        } else {
-            TEST_ASSERT(0);
-        }
-
-        rc = flash_area_write(loc.fe_area, loc.fe_data_off, test_data,
-          sizeof(test_data));
-        TEST_ASSERT(rc == 0);
-
-        rc = fcb_append_finish(fcb, &loc);
-        TEST_ASSERT(rc == 0);
-    }
-    TEST_ASSERT(elem_cnts[0] > 0);
-    TEST_ASSERT(elem_cnts[0] == elem_cnts[1]);
-
-    memset(&aa_together_cnts, 0, sizeof(aa_together_cnts));
-    rc = fcb_walk(fcb, NULL, fcb_test_cnt_elems_cb, &aa_together);
-    TEST_ASSERT(rc == 0);
-    TEST_ASSERT(aa_together.elem_cnts[0] == elem_cnts[0]);
-    TEST_ASSERT(aa_together.elem_cnts[1] == elem_cnts[1]);
-
-    memset(&aa_separate_cnts, 0, sizeof(aa_separate_cnts));
-    rc = fcb_walk(fcb, &test_fcb_area[0], fcb_test_cnt_elems_cb,
-      &aa_separate);
-    TEST_ASSERT(rc == 0);
-    rc = fcb_walk(fcb, &test_fcb_area[1], fcb_test_cnt_elems_cb,
-      &aa_separate);
-    TEST_ASSERT(rc == 0);
-    TEST_ASSERT(aa_separate.elem_cnts[0] == elem_cnts[0]);
-    TEST_ASSERT(aa_separate.elem_cnts[1] == elem_cnts[1]);
-
-}
-
-TEST_CASE(fcb_test_reset)
-{
-    struct fcb *fcb;
-    int rc;
-    int i;
-    struct fcb_entry loc;
-    uint8_t test_data[128];
-    int var_cnt;
-
-    fcb_test_wipe();
-    fcb = &test_fcb;
-    memset(fcb, 0, sizeof(*fcb));
-    fcb->f_sector_cnt = 2;
-    fcb->f_sectors = test_fcb_area;
-
-    rc = fcb_init(fcb);
-    TEST_ASSERT(rc == 0);
-
-    var_cnt = 0;
-    rc = fcb_walk(fcb, 0, fcb_test_data_walk_cb, &var_cnt);
-    TEST_ASSERT(rc == 0);
-    TEST_ASSERT(var_cnt == 0);
-
-    rc = fcb_append(fcb, 32, &loc);
-    TEST_ASSERT(rc == 0);
-
-    /*
-     * No ready ones yet. CRC should not match.
-     */
-    var_cnt = 0;
-    rc = fcb_walk(fcb, 0, fcb_test_data_walk_cb, &var_cnt);
-    TEST_ASSERT(rc == 0);
-    TEST_ASSERT(var_cnt == 0);
-
-    for (i = 0; i < sizeof(test_data); i++) {
-        test_data[i] = fcb_test_append_data(32, i);
-    }
-    rc = flash_area_write(loc.fe_area, loc.fe_data_off, test_data, 32);
-    TEST_ASSERT(rc == 0);
-
-    rc = fcb_append_finish(fcb, &loc);
-    TEST_ASSERT(rc == 0);
-
-    /*
-     * one entry
-     */
-    var_cnt = 32;
-    rc = fcb_walk(fcb, 0, fcb_test_data_walk_cb, &var_cnt);
-    TEST_ASSERT(rc == 0);
-    TEST_ASSERT(var_cnt == 33);
-
-    /*
-     * Pretend reset
-     */
-    memset(fcb, 0, sizeof(*fcb));
-    fcb->f_sector_cnt = 2;
-    fcb->f_sectors = test_fcb_area;
-
-    rc = fcb_init(fcb);
-    TEST_ASSERT(rc == 0);
-
-    var_cnt = 32;
-    rc = fcb_walk(fcb, 0, fcb_test_data_walk_cb, &var_cnt);
-    TEST_ASSERT(rc == 0);
-    TEST_ASSERT(var_cnt == 33);
-
-    rc = fcb_append(fcb, 33, &loc);
-    TEST_ASSERT(rc == 0);
-
-    for (i = 0; i < sizeof(test_data); i++) {
-        test_data[i] = fcb_test_append_data(33, i);
-    }
-    rc = flash_area_write(loc.fe_area, loc.fe_data_off, test_data, 33);
-    TEST_ASSERT(rc == 0);
-
-    rc = fcb_append_finish(fcb, &loc);
-    TEST_ASSERT(rc == 0);
-
-    var_cnt = 32;
-    rc = fcb_walk(fcb, 0, fcb_test_data_walk_cb, &var_cnt);
-    TEST_ASSERT(rc == 0);
-    TEST_ASSERT(var_cnt == 34);
-
-    /*
-     * Add partial one, make sure that we survive reset then.
-     */
-    rc = fcb_append(fcb, 34, &loc);
-    TEST_ASSERT(rc == 0);
-
-    memset(fcb, 0, sizeof(*fcb));
-    fcb->f_sector_cnt = 2;
-    fcb->f_sectors = test_fcb_area;
-
-    rc = fcb_init(fcb);
-    TEST_ASSERT(rc == 0);
-
-    /*
-     * Walk should skip that.
-     */
-    var_cnt = 32;
-    rc = fcb_walk(fcb, 0, fcb_test_data_walk_cb, &var_cnt);
-    TEST_ASSERT(rc == 0);
-    TEST_ASSERT(var_cnt == 34);
-
-    /* Add a 3rd one, should go behind corrupt entry */
-    rc = fcb_append(fcb, 34, &loc);
-    TEST_ASSERT(rc == 0);
-
-    for (i = 0; i < sizeof(test_data); i++) {
-        test_data[i] = fcb_test_append_data(34, i);
-    }
-    rc = flash_area_write(loc.fe_area, loc.fe_data_off, test_data, 34);
-    TEST_ASSERT(rc == 0);
-
-    rc = fcb_append_finish(fcb, &loc);
-    TEST_ASSERT(rc == 0);
-
-    /*
-     * Walk should skip corrupt entry, but report the next one.
-     */
-    var_cnt = 32;
-    rc = fcb_walk(fcb, 0, fcb_test_data_walk_cb, &var_cnt);
-    TEST_ASSERT(rc == 0);
-    TEST_ASSERT(var_cnt == 35);
-}
-
-TEST_CASE(fcb_test_rotate)
-{
-    struct fcb *fcb;
-    int rc;
-    int old_id;
-    struct fcb_entry loc;
-    uint8_t test_data[128];
-    int elem_cnts[2] = {0, 0};
-    int cnts[2];
-    struct append_arg aa_arg = {
-        .elem_cnts = cnts
-    };
-
-    fcb_test_wipe();
-    fcb = &test_fcb;
-    memset(fcb, 0, sizeof(*fcb));
-    fcb->f_sector_cnt = 2;
-    fcb->f_sectors = test_fcb_area;
-
-    rc = fcb_init(fcb);
-    TEST_ASSERT(rc == 0);
-
-    old_id = fcb->f_active_id;
-    rc = fcb_rotate(fcb);
-    TEST_ASSERT(rc == 0);
-    TEST_ASSERT(fcb->f_active_id == old_id + 1);
-
-    /*
-     * Now fill up the
-     */
-    while (1) {
-        rc = fcb_append(fcb, sizeof(test_data), &loc);
-        if (rc == FCB_ERR_NOSPACE) {
-            break;
-        }
-        if (loc.fe_area == &test_fcb_area[0]) {
-            elem_cnts[0]++;
-        } else if (loc.fe_area == &test_fcb_area[1]) {
-            elem_cnts[1]++;
-        } else {
-            TEST_ASSERT(0);
-        }
-
-        rc = flash_area_write(loc.fe_area, loc.fe_data_off, test_data,
-          sizeof(test_data));
-        TEST_ASSERT(rc == 0);
-
-        rc = fcb_append_finish(fcb, &loc);
-        TEST_ASSERT(rc == 0);
-    }
-    TEST_ASSERT(elem_cnts[0] > 0 && elem_cnts[0] == elem_cnts[1]);
-
-    old_id = fcb->f_active_id;
-    rc = fcb_rotate(fcb);
-    TEST_ASSERT(rc == 0);
-    TEST_ASSERT(fcb->f_active_id == old_id); /* no new area created */
-
-    memset(cnts, 0, sizeof(cnts));
-    rc = fcb_walk(fcb, NULL, fcb_test_cnt_elems_cb, &aa_arg);
-    TEST_ASSERT(rc == 0);
-    TEST_ASSERT(aa_arg.elem_cnts[0] == elem_cnts[0] ||
-      aa_arg.elem_cnts[1] == elem_cnts[1]);
-    TEST_ASSERT(aa_arg.elem_cnts[0] == 0 || aa_arg.elem_cnts[1] == 0);
-
-    /*
-     * One sector is full. The other one should have one entry in it.
-     */
-    rc = fcb_append(fcb, sizeof(test_data), &loc);
-    TEST_ASSERT(rc == 0);
-
-    rc = flash_area_write(loc.fe_area, loc.fe_data_off, test_data,
-      sizeof(test_data));
-    TEST_ASSERT(rc == 0);
-
-    rc = fcb_append_finish(fcb, &loc);
-    TEST_ASSERT(rc == 0);
-
-    old_id = fcb->f_active_id;
-    rc = fcb_rotate(fcb);
-    TEST_ASSERT(rc == 0);
-    TEST_ASSERT(fcb->f_active_id == old_id);
-
-    memset(cnts, 0, sizeof(cnts));
-    rc = fcb_walk(fcb, NULL, fcb_test_cnt_elems_cb, &aa_arg);
-    TEST_ASSERT(rc == 0);
-    TEST_ASSERT(aa_arg.elem_cnts[0] == 1 || aa_arg.elem_cnts[1] == 1);
-    TEST_ASSERT(aa_arg.elem_cnts[0] == 0 || aa_arg.elem_cnts[1] == 0);
-}
-
-TEST_CASE(fcb_test_multiple_scratch)
-{
-    struct fcb *fcb;
-    int rc;
-    struct fcb_entry loc;
-    uint8_t test_data[128];
-    int elem_cnts[4];
-    int idx;
-    int cnts[4];
-    struct append_arg aa_arg = {
-        .elem_cnts = cnts
-    };
-
-    fcb_test_wipe();
-    fcb = &test_fcb;
-    memset(fcb, 0, sizeof(*fcb));
-    fcb->f_sector_cnt = 4;
-    fcb->f_scratch_cnt = 1;
-    fcb->f_sectors = test_fcb_area;
-
-    rc = fcb_init(fcb);
-    TEST_ASSERT(rc == 0);
-
-    /*
-     * Now fill up everything. We should be able to get 3 of the sectors
-     * full.
-     */
-    memset(elem_cnts, 0, sizeof(elem_cnts));
-    while (1) {
-        rc = fcb_append(fcb, sizeof(test_data), &loc);
-        if (rc == FCB_ERR_NOSPACE) {
-            break;
-        }
-        idx = loc.fe_area - &test_fcb_area[0];
-        elem_cnts[idx]++;
-
-        rc = flash_area_write(loc.fe_area, loc.fe_data_off, test_data,
-          sizeof(test_data));
-        TEST_ASSERT(rc == 0);
-
-        rc = fcb_append_finish(fcb, &loc);
-        TEST_ASSERT(rc == 0);
-    }
-
-    TEST_ASSERT(elem_cnts[0] > 0);
-    TEST_ASSERT(elem_cnts[0] == elem_cnts[1] && elem_cnts[0] == elem_cnts[2]);
-    TEST_ASSERT(elem_cnts[3] == 0);
-
-    /*
-     * Ask to use scratch block, then fill it up.
-     */
-    rc = fcb_append_to_scratch(fcb);
-    TEST_ASSERT(rc == 0);
-
-    while (1) {
-        rc = fcb_append(fcb, sizeof(test_data), &loc);
-        if (rc == FCB_ERR_NOSPACE) {
-            break;
-        }
-        idx = loc.fe_area - &test_fcb_area[0];
-        elem_cnts[idx]++;
-
-        rc = flash_area_write(loc.fe_area, loc.fe_data_off, test_data,
-          sizeof(test_data));
-        TEST_ASSERT(rc == 0);
-
-        rc = fcb_append_finish(fcb, &loc);
-        TEST_ASSERT(rc == 0);
-    }
-    TEST_ASSERT(elem_cnts[3] == elem_cnts[0]);
-
-    /*
-     * Rotate
-     */
-    rc = fcb_rotate(fcb);
-    TEST_ASSERT(rc == 0);
-
-    memset(&cnts, 0, sizeof(cnts));
-    rc = fcb_walk(fcb, NULL, fcb_test_cnt_elems_cb, &aa_arg);
-    TEST_ASSERT(rc == 0);
-
-    TEST_ASSERT(cnts[0] == 0);
-    TEST_ASSERT(cnts[1] > 0);
-    TEST_ASSERT(cnts[1] == cnts[2] && cnts[1] == cnts[3]);
-
-    rc = fcb_append_to_scratch(fcb);
-    TEST_ASSERT(rc == 0);
-    rc = fcb_append_to_scratch(fcb);
-    TEST_ASSERT(rc != 0);
-}
-
-TEST_SUITE(fcb_test_all)
-{
-    fcb_test_len();
-
-    fcb_test_init();
-
-    fcb_test_empty_walk();
-
-    fcb_test_append();
-
-    fcb_test_append_too_big();
-
-    fcb_test_append_fill();
-
-    fcb_test_reset();
-
-    fcb_test_rotate();
-
-    fcb_test_multiple_scratch();
-}
-
-#if MYNEWT_VAL(SELFTEST)
-
-int
-main(int argc, char **argv)
-{
-    tu_config.tc_print_results = 1;
-    tu_init();
-
-    fcb_test_all();
-
-    return tu_any_failed;
-}
-#endif
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/id/pkg.yml
----------------------------------------------------------------------
diff --git a/sys/id/pkg.yml b/sys/id/pkg.yml
index 2795d49..055a98e 100644
--- a/sys/id/pkg.yml
+++ b/sys/id/pkg.yml
@@ -28,11 +28,12 @@ pkg.keywords:
 
 pkg.deps:
     - hw/hal
-    - libs/os
+    - kernel/os
     - libs/util
     - sys/config
+    - encoding/base64
 pkg.deps.ID_CLI:
-    - libs/shell
+    - sys/shell
 pkg.req_apis.ID_CLI:
     - console
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/id/src/id.c
----------------------------------------------------------------------
diff --git a/sys/id/src/id.c b/sys/id/src/id.c
index 36eac5a..c58a652 100644
--- a/sys/id/src/id.c
+++ b/sys/id/src/id.c
@@ -25,7 +25,7 @@
 #include "hal/hal_bsp.h"
 #include "os/os.h"
 #include "config/config.h"
-#include "util/base64.h"
+#include "base64/base64.h"
 
 #include "id/id.h"
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/log/pkg.yml
----------------------------------------------------------------------
diff --git a/sys/log/pkg.yml b/sys/log/pkg.yml
index bd57e84..b931e43 100644
--- a/sys/log/pkg.yml
+++ b/sys/log/pkg.yml
@@ -25,13 +25,13 @@ pkg.keywords:
     - logging
 
 pkg.deps:
-    - libs/os
+    - kernel/os
     - libs/util
 pkg.deps.LOG_FCB:
     - hw/hal
-    - sys/fcb
+    - fs/fcb
 pkg.deps.LOG_CLI:
-    - libs/shell
+    - sys/shell
 
 pkg.req_apis.LOG_NEWTMGR:
     - newtmgr

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/mn_socket/include/mn_socket/arch/sim/native_sock.h
----------------------------------------------------------------------
diff --git a/sys/mn_socket/include/mn_socket/arch/sim/native_sock.h b/sys/mn_socket/include/mn_socket/arch/sim/native_sock.h
deleted file mode 100644
index 66e8016..0000000
--- a/sys/mn_socket/include/mn_socket/arch/sim/native_sock.h
+++ /dev/null
@@ -1,25 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 __NATIVE_SOCK_H_
-#define __NATIVE_SOCK_H_
-
-int native_sock_init(void);
-
-#endif /* __NATIVE_SOCK_H_ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/mn_socket/include/mn_socket/mn_socket.h
----------------------------------------------------------------------
diff --git a/sys/mn_socket/include/mn_socket/mn_socket.h b/sys/mn_socket/include/mn_socket/mn_socket.h
deleted file mode 100644
index 47c54fb..0000000
--- a/sys/mn_socket/include/mn_socket/mn_socket.h
+++ /dev/null
@@ -1,218 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 __SYS_MN_SOCKET_H_
-#define __SYS_MN_SOCKET_H_
-
-#include <inttypes.h>
-
-/*
- * Address/protocol family.
- */
-#define MN_AF_INET              4
-#define MN_PF_INET              MN_AF_INET
-#define MN_AF_INET6             6
-#define MN_PF_INET6             MN_AF_INET6
-
-/*
- * Socket types
- */
-#define MN_SOCK_STREAM          1
-#define MN_SOCK_DGRAM           2
-
-/*
- * Error codes from mn_socket interface.
- */
-#define MN_EAFNOSUPPORT         1
-#define MN_EPROTONOSUPPORT      2
-#define MN_ENOBUFS              3
-#define MN_EINVAL               4
-#define MN_ENOTCONN             5
-#define MN_ECONNABORTED         6
-#define MN_EDESTADDRREQ         7
-#define MN_EADDRINUSE           8
-#define MN_ETIMEDOUT            9
-#define MN_EAGAIN               10
-#define MN_EUNKNOWN             11
-#define MN_EADDRNOTAVAIL        12
-
-/*
- * Multicast macros
- */
-#define MN_IN_MULTICAST(a)                                              \
-    ((((uint32_t)(a)) & 0xf0000000) == 0xe0000000)
-
-#define MN_IN6_IS_ADDR_MULTICAST(a)                                     \
-    ((a)->s_addr[0] == 0xff)
-
-struct mn_socket;
-struct mn_socket_ops;
-struct mn_sock_cb;
-struct os_mbuf;
-
-struct mn_socket {
-    const union mn_socket_cb *ms_cbs;          /* filled in by user */
-    void *ms_cb_arg;                           /* filled in by user */
-    const struct mn_socket_ops *ms_ops;        /* filled in by mn_socket */
-};
-
-/*
- * Callbacks. Socket callbacks are for sockets which exchange
- * data. Listen callback is for TCP listen sockets.
- */
-union mn_socket_cb {
-    struct {
-        void (*readable)(void *cb_arg, int err);
-        void (*writable)(void *cb_arg, int err);
-    } socket;
-    struct {
-        int (*newconn)(void *cb_arg, struct mn_socket *new);
-    } listen;
-};
-
-struct mn_sockaddr {
-    uint8_t msa_len;
-    uint8_t msa_family;
-    char    msa_data[2];
-};
-
-struct mn_in_addr {
-    uint32_t s_addr;
-};
-
-struct mn_sockaddr_in {
-    uint8_t msin_len;
-    uint8_t msin_family;
-    uint16_t msin_port;
-    struct mn_in_addr msin_addr;
-};
-
-struct mn_in6_addr {
-    uint8_t s_addr[16];
-};
-
-struct mn_sockaddr_in6 {
-    uint8_t msin6_len;
-    uint8_t msin6_family;
-    uint16_t msin6_port;
-    uint32_t msin6_flowinfo;
-    struct mn_in6_addr msin6_addr;
-    uint32_t msin6_scope_id;
-};
-
-extern const uint32_t nm_in6addr_any[4];
-
-/*
- * Structure for multicast join/leave
- */
-struct mn_mreq {
-    uint8_t mm_idx;			/* interface index */
-    uint8_t mm_family;			/* address family */
-    union {
-        struct mn_in_addr v4;
-        struct mn_in6_addr v6;
-    } mm_addr;
-};
-
-#define MN_SO_LEVEL                     0xfe
-
-#define MN_MCAST_JOIN_GROUP             1
-#define MN_MCAST_LEAVE_GROUP            2
-#define MN_MCAST_IF                     3
-
-/*
- * Socket calls.
- *
- * mn_connect() for TCP is asynchronous. Once connection has been established,
- * socket callback (*writable) will be called.
- *
- * mn_sendto() is asynchronous as well. If it fails due to buffer shortage,
- * socket provider should call (*writable) when more data can be sent.
- *
- * mn_recvfrom() returns immediatelly if no data is available. If data arrives,
- * the callback (*readable) will be called. Once that happens, owner of the
- * socket should keep calling mn_recvfrom() until it has drained all the
- * data from the socket.
- *
- * If remote end closes the socket, socket callback (*readable) will be
- * called.
- */
-int mn_socket(struct mn_socket **, uint8_t domain, uint8_t type, uint8_t proto);
-int mn_bind(struct mn_socket *, struct mn_sockaddr *);
-int mn_connect(struct mn_socket *, struct mn_sockaddr *);
-int mn_listen(struct mn_socket *, uint8_t qlen);
-
-int mn_recvfrom(struct mn_socket *, struct os_mbuf **,
-  struct mn_sockaddr *from);
-int mn_sendto(struct mn_socket *, struct os_mbuf *, struct mn_sockaddr *to);
-
-int mn_getsockopt(struct mn_socket *, uint8_t level, uint8_t optname,
-  void *optval);
-int mn_setsockopt(struct mn_socket *, uint8_t level, uint8_t optname,
-  void *optval);
-
-int mn_getsockname(struct mn_socket *, struct mn_sockaddr *);
-int mn_getpeername(struct mn_socket *, struct mn_sockaddr *);
-
-int mn_close(struct mn_socket *);
-
-#define mn_socket_set_cbs(sock, cb_arg, cbs)                            \
-    do {                                                                \
-        (sock)->ms_cbs = (cbs);                                         \
-        (sock)->ms_cb_arg = (cb_arg);                                   \
-    } while (0)
-
-/*
- * Address conversion
- */
-int mn_inet_pton(int af, const char *src, void *dst);
-const char *mn_inet_ntop(int af, const void *src, void *dst, int len);
-
-/*
- * Info about interfaces.
- */
-#define MN_ITF_NAME_MAX    8
-
-/*
- * Interface flags
- */
-#define MN_ITF_F_UP        1
-#define MN_ITF_F_MULTICAST 2
-
-struct mn_itf {
-    char mif_name[MN_ITF_NAME_MAX];
-    uint8_t mif_idx;
-    uint8_t mif_flags;
-};
-
-struct mn_itf_addr {
-    uint8_t mifa_family;
-    uint8_t mifa_plen;
-    union {
-        struct mn_in_addr v4;
-        struct mn_in6_addr v6;
-    } mifa_addr;
-};
-
-/*
- * Iterate through interfaces, and their addresses
- */
-int mn_itf_getnext(struct mn_itf *);
-int mn_itf_addr_getnext(struct mn_itf *, struct mn_itf_addr *);
-
-#endif /* __SYS_MN_SOCKET_H_ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/mn_socket/include/mn_socket/mn_socket_ops.h
----------------------------------------------------------------------
diff --git a/sys/mn_socket/include/mn_socket/mn_socket_ops.h b/sys/mn_socket/include/mn_socket/mn_socket_ops.h
deleted file mode 100644
index 39f11c1..0000000
--- a/sys/mn_socket/include/mn_socket/mn_socket_ops.h
+++ /dev/null
@@ -1,85 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 __SYS_MN_SOCKET_OPS_H_
-#define __SYS_MN_SOCKET_OPS_H_
-
-#include <inttypes.h>
-
-/*
- * Interface for socket providers.
- * - mso_create() creates a socket, memory allocation has to be done by
- *   the socket provider.
- * - mso_close() closes the socket, memory should be freed. User should not
- *   be using the socket pointer once it has been closed.
- */
-struct mn_socket_ops {
-    int (*mso_create)(struct mn_socket **, uint8_t domain, uint8_t type,
-      uint8_t protocol);
-    int (*mso_close)(struct mn_socket *);
-
-    int (*mso_bind)(struct mn_socket *, struct mn_sockaddr *);
-    int (*mso_connect)(struct mn_socket *, struct mn_sockaddr *);
-    int (*mso_listen)(struct mn_socket *, uint8_t qlen);
-
-    int (*mso_sendto)(struct mn_socket *, struct os_mbuf *,
-      struct mn_sockaddr *to);
-    int (*mso_recvfrom)(struct mn_socket *, struct os_mbuf **,
-      struct mn_sockaddr *from);
-
-    int (*mso_getsockopt)(struct mn_socket *, uint8_t level, uint8_t name,
-      void *val);
-    int (*mso_setsockopt)(struct mn_socket *, uint8_t level, uint8_t name,
-      void *val);
-
-    int (*mso_getsockname)(struct mn_socket *, struct mn_sockaddr *);
-    int (*mso_getpeername)(struct mn_socket *, struct mn_sockaddr *);
-
-    int (*mso_itf_getnext)(struct mn_itf *);
-    int (*mso_itf_addr_getnext)(struct mn_itf *, struct mn_itf_addr *);
-};
-
-int mn_socket_ops_reg(const struct mn_socket_ops *ops);
-
-static inline void
-mn_socket_writable(struct mn_socket *s, int error)
-{
-    if (s->ms_cbs && s->ms_cbs->socket.writable) {
-        s->ms_cbs->socket.writable(s->ms_cb_arg, error);
-    }
-}
-
-static inline void
-mn_socket_readable(struct mn_socket *s, int error)
-{
-    if (s->ms_cbs && s->ms_cbs->socket.readable) {
-        s->ms_cbs->socket.readable(s->ms_cb_arg, error);
-    }
-}
-
-static inline int
-mn_socket_newconn(struct mn_socket *s, struct mn_socket *new)
-{
-    if (s->ms_cbs && s->ms_cbs->listen.newconn) {
-        return s->ms_cbs->listen.newconn(s->ms_cb_arg, new);
-    } else {
-        return -1;
-    }
-}
-
-#endif /* __SYS_MN_SOCKET_OPS_H_ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/mn_socket/pkg.yml
----------------------------------------------------------------------
diff --git a/sys/mn_socket/pkg.yml b/sys/mn_socket/pkg.yml
deleted file mode 100644
index 4242b46..0000000
--- a/sys/mn_socket/pkg.yml
+++ /dev/null
@@ -1,30 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you 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.
-#
-
-pkg.name: sys/mn_socket
-pkg.description: Socket interface for Mynewt.
-pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
-pkg.homepage: "http://mynewt.apache.org/"
-pkg.keywords:
-    - socket
-    - IP
-
-pkg.deps:
-    - libs/os
-    - libs/util


[11/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/shell/src/shell.c
----------------------------------------------------------------------
diff --git a/libs/shell/src/shell.c b/libs/shell/src/shell.c
deleted file mode 100644
index 3aba773..0000000
--- a/libs/shell/src/shell.c
+++ /dev/null
@@ -1,579 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include <stdio.h>
-#include <string.h>
-#include <assert.h>
-
-#include "sysinit/sysinit.h"
-#include "syscfg/syscfg.h"
-#include "console/console.h"
-#include "console/prompt.h"
-#include "os/os.h"
-#include "os/endian.h"
-#include "util/base64.h"
-#include "util/crc16.h"
-#include "shell/shell.h"
-#include "shell_priv.h"
-
-static shell_nlip_input_func_t g_shell_nlip_in_func;
-static void *g_shell_nlip_in_arg;
-
-static struct os_mqueue g_shell_nlip_mq;
-
-#define OS_EVENT_T_CONSOLE_RDY  (OS_EVENT_T_PERUSER)
-#define SHELL_HELP_PER_LINE     6
-#define SHELL_MAX_ARGS          20
-
-static os_stack_t shell_stack[OS_STACK_ALIGN(MYNEWT_VAL(SHELL_STACK_SIZE))];
-
-static int shell_echo_cmd(int argc, char **argv);
-static int shell_help_cmd(int argc, char **argv);
-int shell_prompt_cmd(int argc, char **argv);
-
-static struct shell_cmd g_shell_echo_cmd = {
-    .sc_cmd = "echo",
-    .sc_cmd_func = shell_echo_cmd
-};
-static struct shell_cmd g_shell_help_cmd = {
-    .sc_cmd = "?",
-    .sc_cmd_func = shell_help_cmd
-};
-static struct shell_cmd g_shell_prompt_cmd = {
-   .sc_cmd = "prompt",
-   .sc_cmd_func = shell_prompt_cmd
-};
-static struct shell_cmd g_shell_os_tasks_display_cmd = {
-    .sc_cmd = "tasks",
-    .sc_cmd_func = shell_os_tasks_display_cmd
-};
-static struct shell_cmd g_shell_os_mpool_display_cmd = {
-    .sc_cmd = "mempools",
-    .sc_cmd_func = shell_os_mpool_display_cmd
-};
-static struct shell_cmd g_shell_os_date_cmd = {
-    .sc_cmd = "date",
-    .sc_cmd_func = shell_os_date_cmd
-};
-
-static struct os_task shell_task;
-static struct os_eventq shell_evq;
-static struct os_event console_rdy_ev;
-
-static struct os_mutex g_shell_cmd_list_lock;
-
-static char *shell_line;
-static int shell_line_len;
-static char *argv[SHELL_MAX_ARGS];
-
-static STAILQ_HEAD(, shell_cmd) g_shell_cmd_list =
-    STAILQ_HEAD_INITIALIZER(g_shell_cmd_list);
-
-static struct os_mbuf *g_nlip_mbuf;
-static uint16_t g_nlip_expected_len;
-
-int
-shell_cmd_list_lock(void)
-{
-    int rc;
-
-    if (!os_started()) {
-        return (0);
-    }
-
-    rc = os_mutex_pend(&g_shell_cmd_list_lock, OS_WAIT_FOREVER);
-    if (rc != 0) {
-        goto err;
-    }
-    return (0);
-err:
-    return (rc);
-}
-
-int
-shell_cmd_list_unlock(void)
-{
-    int rc;
-
-    if (!os_started()) {
-        return (0);
-    }
-
-    rc = os_mutex_release(&g_shell_cmd_list_lock);
-    if (rc != 0) {
-        goto err;
-    }
-    return (0);
-err:
-    return (rc);
-}
-
-int
-shell_cmd_register(struct shell_cmd *sc)
-{
-    int rc;
-
-    /* Add the command that is being registered. */
-    rc = shell_cmd_list_lock();
-    if (rc != 0) {
-        goto err;
-    }
-
-    STAILQ_INSERT_TAIL(&g_shell_cmd_list, sc, sc_next);
-
-    rc = shell_cmd_list_unlock();
-    if (rc != 0) {
-        goto err;
-    }
-
-    return (0);
-err:
-    return (rc);
-}
-
-static int
-shell_cmd(char *cmd, char **argv, int argc)
-{
-    struct shell_cmd *sc;
-    int rc;
-
-    rc = shell_cmd_list_lock();
-    if (rc != 0) {
-        goto err;
-    }
-
-    STAILQ_FOREACH(sc, &g_shell_cmd_list, sc_next) {
-        if (!strcmp(sc->sc_cmd, cmd)) {
-            break;
-        }
-    }
-
-    rc = shell_cmd_list_unlock();
-    if (rc != 0) {
-        goto err;
-    }
-
-    if (sc) {
-        sc->sc_cmd_func(argc, argv);
-    } else {
-        console_printf("Unknown command %s\n", cmd);
-    }
-
-    return (0);
-err:
-    return (rc);
-}
-
-static int
-shell_process_command(char *line, int len)
-{
-    char *tok;
-    char *tok_ptr;
-    int argc;
-
-    tok_ptr = NULL;
-    tok = strtok_r(line, " ", &tok_ptr);
-    argc = 0;
-    while (argc < SHELL_MAX_ARGS - 1 && tok != NULL) {
-        argv[argc++] = tok;
-
-        tok = strtok_r(NULL, " ", &tok_ptr);
-    }
-
-    /* Terminate the argument list with a null pointer. */
-    argv[argc] = NULL;
-
-    if (argc) {
-        (void) shell_cmd(argv[0], argv, argc);
-    }
-    else {
-        console_printf("\n");
-    }
-    console_print_prompt();
-    return (0);
-}
-
-
-static int
-shell_nlip_process(char *data, int len)
-{
-    uint16_t copy_len;
-    int rc;
-    struct os_mbuf *m;
-    uint16_t crc;
-
-    rc = base64_decode(data, data);
-    if (rc < 0) {
-        goto err;
-    }
-    len = rc;
-
-    if (g_nlip_mbuf == NULL) {
-        if (len < 2) {
-            rc = -1;
-            goto err;
-        }
-
-        g_nlip_expected_len = ntohs(*(uint16_t *) data);
-        g_nlip_mbuf = os_msys_get_pkthdr(g_nlip_expected_len, 0);
-        if (!g_nlip_mbuf) {
-            rc = -1;
-            goto err;
-        }
-
-        data += sizeof(uint16_t);
-        len -= sizeof(uint16_t);
-    }
-
-    copy_len = min(g_nlip_expected_len - OS_MBUF_PKTHDR(g_nlip_mbuf)->omp_len,
-            len);
-
-    rc = os_mbuf_copyinto(g_nlip_mbuf, OS_MBUF_PKTHDR(g_nlip_mbuf)->omp_len,
-            data, copy_len);
-    if (rc != 0) {
-        goto err;
-    }
-
-    if (OS_MBUF_PKTHDR(g_nlip_mbuf)->omp_len == g_nlip_expected_len) {
-        if (g_shell_nlip_in_func) {
-            crc = CRC16_INITIAL_CRC;
-            for (m = g_nlip_mbuf; m; m = SLIST_NEXT(m, om_next)) {
-                crc = crc16_ccitt(crc, m->om_data, m->om_len);
-            }
-            if (crc == 0 && g_nlip_expected_len >= sizeof(crc)) {
-                os_mbuf_adj(g_nlip_mbuf, -sizeof(crc));
-                g_shell_nlip_in_func(g_nlip_mbuf, g_shell_nlip_in_arg);
-            } else {
-                os_mbuf_free_chain(g_nlip_mbuf);
-            }
-        } else {
-            os_mbuf_free_chain(g_nlip_mbuf);
-        }
-        g_nlip_mbuf = NULL;
-        g_nlip_expected_len = 0;
-    }
-
-    return (0);
-err:
-    return (rc);
-}
-
-static int
-shell_nlip_mtx(struct os_mbuf *m)
-{
-#define SHELL_NLIP_MTX_BUF_SIZE (12)
-    uint8_t readbuf[SHELL_NLIP_MTX_BUF_SIZE];
-    char encodebuf[BASE64_ENCODE_SIZE(SHELL_NLIP_MTX_BUF_SIZE)];
-    char pkt_seq[2] = { SHELL_NLIP_PKT_START1, SHELL_NLIP_PKT_START2 };
-    char esc_seq[2] = { SHELL_NLIP_DATA_START1, SHELL_NLIP_DATA_START2 };
-    uint16_t totlen;
-    uint16_t dlen;
-    uint16_t off;
-    uint16_t crc;
-    int rb_off;
-    int elen;
-    uint16_t nwritten;
-    uint16_t linelen;
-    int rc;
-    struct os_mbuf *tmp;
-    void *ptr;
-
-    /* Convert the mbuf into a packet.
-     *
-     * starts with 06 09
-     * base64 encode:
-     *  - total packet length (uint16_t)
-     *  - data
-     *  - crc
-     * base64 encoded data must be less than 122 bytes per line to
-     * avoid overflows and adhere to convention.
-     *
-     * continuation packets are preceded by 04 20 until the entire
-     * buffer has been sent.
-     */
-    crc = CRC16_INITIAL_CRC;
-    for (tmp = m; tmp; tmp = SLIST_NEXT(tmp, om_next)) {
-        crc = crc16_ccitt(crc, tmp->om_data, tmp->om_len);
-    }
-    crc = htons(crc);
-    ptr = os_mbuf_extend(m, sizeof(crc));
-    if (!ptr) {
-        rc = -1;
-        goto err;
-    }
-    memcpy(ptr, &crc, sizeof(crc));
-
-    totlen = OS_MBUF_PKTHDR(m)->omp_len;
-    nwritten = 0;
-    off = 0;
-
-    /* Start a packet */
-    console_write(pkt_seq, sizeof(pkt_seq));
-
-    linelen = 0;
-
-    rb_off = 2;
-    dlen = htons(totlen);
-    memcpy(readbuf, &dlen, sizeof(dlen));
-
-    while (totlen > 0) {
-        dlen = min(SHELL_NLIP_MTX_BUF_SIZE - rb_off, totlen);
-
-        rc = os_mbuf_copydata(m, off, dlen, readbuf + rb_off);
-        if (rc != 0) {
-            goto err;
-        }
-        off += dlen;
-
-        /* If the next packet will overwhelm the line length, truncate
-         * this line.
-         */
-        if (linelen +
-                BASE64_ENCODE_SIZE(min(SHELL_NLIP_MTX_BUF_SIZE - rb_off,
-                        totlen - dlen)) >= 120) {
-            elen = base64_encode(readbuf, dlen + rb_off, encodebuf, 1);
-            console_write(encodebuf, elen);
-            console_write("\n", 1);
-            console_write(esc_seq, sizeof(esc_seq));
-            linelen = 0;
-        } else {
-            elen = base64_encode(readbuf, dlen + rb_off, encodebuf, 0);
-            console_write(encodebuf, elen);
-            linelen += elen;
-        }
-
-        rb_off = 0;
-
-        nwritten += elen;
-        totlen -= dlen;
-    }
-
-    elen = base64_pad(encodebuf, linelen);
-    console_write(encodebuf, elen);
-
-    console_write("\n", 1);
-
-    return (0);
-err:
-    return (rc);
-}
-
-static void
-shell_nlip_mqueue_process(void)
-{
-    struct os_mbuf *m;
-
-    /* Copy data out of the mbuf 12 bytes at a time and write it to
-     * the console.
-     */
-    while (1) {
-        m = os_mqueue_get(&g_shell_nlip_mq);
-        if (!m) {
-            break;
-        }
-
-        (void) shell_nlip_mtx(m);
-
-        os_mbuf_free_chain(m);
-    }
-}
-
-int
-shell_nlip_input_register(shell_nlip_input_func_t nf, void *arg)
-{
-    g_shell_nlip_in_func = nf;
-    g_shell_nlip_in_arg = arg;
-
-    return (0);
-}
-
-int
-shell_nlip_output(struct os_mbuf *m)
-{
-    int rc;
-
-    rc = os_mqueue_put(&g_shell_nlip_mq, &shell_evq, m);
-    if (rc != 0) {
-        goto err;
-    }
-
-    return (0);
-err:
-    return (rc);
-}
-
-static void
-shell_read_console(void)
-{
-    int rc;
-    int full_line;
-
-    while (1) {
-        rc = console_read(shell_line + shell_line_len,
-          MYNEWT_VAL(SHELL_MAX_INPUT_LEN) - shell_line_len, &full_line);
-        if (rc <= 0 && !full_line) {
-            break;
-        }
-        shell_line_len += rc;
-        if (full_line) {
-            if (shell_line_len > 2) {
-                if (shell_line[0] == SHELL_NLIP_PKT_START1 &&
-                        shell_line[1] == SHELL_NLIP_PKT_START2) {
-                    if (g_nlip_mbuf) {
-                        os_mbuf_free_chain(g_nlip_mbuf);
-                        g_nlip_mbuf = NULL;
-                    }
-                    g_nlip_expected_len = 0;
-
-                    rc = shell_nlip_process(&shell_line[2], shell_line_len - 2);
-                } else if (shell_line[0] == SHELL_NLIP_DATA_START1 &&
-                        shell_line[1] == SHELL_NLIP_DATA_START2) {
-                    rc = shell_nlip_process(&shell_line[2], shell_line_len - 2);
-                } else {
-                    shell_process_command(shell_line, shell_line_len);
-                }
-            } else {
-                shell_process_command(shell_line, shell_line_len);
-            }
-            shell_line_len = 0;
-        }
-    }
-}
-
-
-static void
-shell_task_func(void *arg)
-{
-    struct os_event *ev;
-
-    while (1) {
-        ev = os_eventq_get(&shell_evq);
-        assert(ev != NULL);
-
-        switch (ev->ev_type) {
-            case OS_EVENT_T_CONSOLE_RDY:
-                // Read and process all available lines on the console.
-                shell_read_console();
-                break;
-            case OS_EVENT_T_MQUEUE_DATA:
-                shell_nlip_mqueue_process();
-                break;
-        }
-    }
-}
-
-/**
- * This function is called from the console APIs when data is available
- * to be read.  This is either a full line, or when the
- * console buffer (default = 128) is full.
- */
-void
-shell_console_rx_cb(void)
-{
-    os_eventq_put(&shell_evq, &console_rdy_ev);
-}
-
-static int
-shell_echo_cmd(int argc, char **argv)
-{
-    int i;
-
-    for (i = 1; i < argc; i++) {
-        console_write(argv[i], strlen(argv[i]));
-        console_write(" ", sizeof(" ")-1);
-    }
-    console_write("\n", sizeof("\n")-1);
-
-    return (0);
-}
-
-static int
-shell_help_cmd(int argc, char **argv)
-{
-    int rc;
-    int i = 0;
-    struct shell_cmd *sc;
-
-    rc = shell_cmd_list_lock();
-    if (rc != 0) {
-        return -1;
-    }
-    console_printf("Commands:\n");
-    STAILQ_FOREACH(sc, &g_shell_cmd_list, sc_next) {
-        console_printf("%9s ", sc->sc_cmd);
-        if (i++ % SHELL_HELP_PER_LINE == SHELL_HELP_PER_LINE - 1) {
-            console_printf("\n");
-        }
-    }
-    if (i % SHELL_HELP_PER_LINE) {
-        console_printf("\n");
-    }
-    shell_cmd_list_unlock();
-
-    return (0);
-}
-
-void
-shell_init(void)
-{
-#if !MYNEWT_VAL(SHELL_TASK)
-    return;
-#endif
-
-    int rc;
-
-    free(shell_line);
-    shell_line = NULL;
-
-#if MYNEWT_VAL(SHELL_MAX_INPUT_LEN) > 0
-    shell_line = malloc(MYNEWT_VAL(SHELL_MAX_INPUT_LEN));
-    SYSINIT_PANIC_ASSERT(shell_line != NULL);
-#endif
-
-    rc = os_mutex_init(&g_shell_cmd_list_lock);
-    SYSINIT_PANIC_ASSERT(rc == 0);
-
-    rc = shell_cmd_register(&g_shell_echo_cmd);
-    SYSINIT_PANIC_ASSERT(rc == 0);
-
-    rc = shell_cmd_register(&g_shell_help_cmd);
-    SYSINIT_PANIC_ASSERT(rc == 0);
-
-    rc = shell_cmd_register(&g_shell_prompt_cmd);
-    SYSINIT_PANIC_ASSERT(rc == 0);
-
-    rc = shell_cmd_register(&g_shell_os_tasks_display_cmd);
-    SYSINIT_PANIC_ASSERT(rc == 0);
-
-    rc = shell_cmd_register(&g_shell_os_mpool_display_cmd);
-    SYSINIT_PANIC_ASSERT(rc == 0);
-
-    rc = shell_cmd_register(&g_shell_os_date_cmd);
-    SYSINIT_PANIC_ASSERT(rc == 0);
-
-    os_eventq_init(&shell_evq);
-    os_mqueue_init(&g_shell_nlip_mq, NULL);
-    console_rdy_ev.ev_type = OS_EVENT_T_CONSOLE_RDY;
-    console_init(shell_console_rx_cb);
-
-    rc = os_task_init(&shell_task, "shell", shell_task_func,
-            NULL, MYNEWT_VAL(SHELL_TASK_PRIO), OS_WAIT_FOREVER, shell_stack,
-            MYNEWT_VAL(SHELL_STACK_SIZE));
-    SYSINIT_PANIC_ASSERT(rc == 0);
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/shell/src/shell_os.c
----------------------------------------------------------------------
diff --git a/libs/shell/src/shell_os.c b/libs/shell/src/shell_os.c
deleted file mode 100644
index 283d429..0000000
--- a/libs/shell/src/shell_os.c
+++ /dev/null
@@ -1,156 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include "os/os.h"
-
-#include "os/queue.h"
-#include "os/os_time.h"
-
-#include "console/console.h"
-#include "shell/shell.h"
-#include "shell_priv.h"
-
-#include <assert.h>
-#include <string.h>
-#include <util/datetime.h>
-
-int 
-shell_os_tasks_display_cmd(int argc, char **argv)
-{
-    struct os_task *prev_task;
-    struct os_task_info oti;
-    char *name;
-    int found;
-
-    name = NULL;
-    found = 0;
-
-    if (argc > 1 && strcmp(argv[1], "")) {
-        name = argv[1];
-    }
-
-    console_printf("Tasks: \n");
-    prev_task = NULL;
-    while (1) {
-        prev_task = os_task_info_get_next(prev_task, &oti);
-        if (prev_task == NULL) {
-            break;
-        }
-
-        if (name) {
-            if (strcmp(name, oti.oti_name)) {
-                continue;
-            } else {
-                found = 1;
-            }
-        }
-
-        console_printf("  %s (prio: %u, tid: %u, lcheck: %lu, ncheck: %lu, "
-                "flags: 0x%x, ssize: %u, susage: %u, cswcnt: %lu, "
-                "tot_run_time: %lums)\n",
-                oti.oti_name, oti.oti_prio, oti.oti_taskid, 
-                (unsigned long)oti.oti_last_checkin,
-                (unsigned long)oti.oti_next_checkin, oti.oti_flags,
-                oti.oti_stksize, oti.oti_stkusage, (unsigned long)oti.oti_cswcnt,
-                (unsigned long)oti.oti_runtime);
-
-    }
-
-    if (name && !found) {
-        console_printf("Couldn't find task with name %s\n", name);
-    }
-
-    return (0);
-}
-
-int 
-shell_os_mpool_display_cmd(int argc, char **argv)
-{
-    struct os_mempool *mp;
-    struct os_mempool_info omi;
-    char *name;
-    int found;
-
-    name = NULL;
-    found = 0;
-
-    if (argc > 1 && strcmp(argv[1], "")) {
-        name = argv[1];
-    }
-
-    console_printf("Mempools: \n");
-    mp = NULL;
-    while (1) {
-        mp = os_mempool_info_get_next(mp, &omi);
-        if (mp == NULL) {
-            break;
-        }
-
-        if (name) {
-            if (strcmp(name, omi.omi_name)) {
-                continue;
-            } else {
-                found = 1;
-            }
-        }
-
-        console_printf("  %s (blksize: %d, nblocks: %d, nfree: %d)\n",
-                omi.omi_name, omi.omi_block_size, omi.omi_num_blocks,
-                omi.omi_num_free);
-    }
-
-    if (name && !found) {
-        console_printf("Couldn't find a memory pool with name %s\n", 
-                name);
-    }
-
-    return (0);
-}
-
-int
-shell_os_date_cmd(int argc, char **argv)
-{
-    struct os_timeval tv;
-    struct os_timezone tz;
-    char buf[DATETIME_BUFSIZE];
-    int rc;
-
-    argc--; argv++;     /* skip command name */
-
-    if (argc == 0) {
-        /* Display the current datetime */
-        rc = os_gettimeofday(&tv, &tz);
-        assert(rc == 0);
-        rc = format_datetime(&tv, &tz, buf, sizeof(buf));
-        assert(rc == 0);
-        console_printf("%s\n", buf);
-    } else if (argc == 1) {
-        /* Set the current datetime */
-        rc = parse_datetime(*argv, &tv, &tz);
-        if (rc == 0) {
-            rc = os_settimeofday(&tv, &tz);
-        } else {
-            console_printf("Invalid datetime\n");
-        }
-    } else {
-        rc = -1;
-    }
-
-    return (rc);
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/shell/src/shell_priv.h
----------------------------------------------------------------------
diff --git a/libs/shell/src/shell_priv.h b/libs/shell/src/shell_priv.h
deleted file mode 100644
index 4e035e0..0000000
--- a/libs/shell/src/shell_priv.h
+++ /dev/null
@@ -1,27 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 __SHELL_PRIV_H_
-#define __SHELL_PRIV_H_
-
-int shell_os_tasks_display_cmd(int argc, char **argv);
-int shell_os_mpool_display_cmd(int argc, char **argv);
-int shell_os_date_cmd(int argc, char **argv);
-
-#endif /* __SHELL_PRIV_H_ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/shell/src/shell_prompt.c
----------------------------------------------------------------------
diff --git a/libs/shell/src/shell_prompt.c b/libs/shell/src/shell_prompt.c
deleted file mode 100644
index d1402ad..0000000
--- a/libs/shell/src/shell_prompt.c
+++ /dev/null
@@ -1,69 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include <string.h>
-#include "shell/shell.h"
-#include <console/console.h>
-
-static char shell_prompt = '>';
-
-void console_set_prompt(char p);
-
-/**
- * Handles the 'prompt' command
- * with set argument, sets the prompt to the provided char
- * with the show argument, echos the current prompt
- * otherwise echos the prompt and the usage message
- */
-int
-shell_prompt_cmd(int argc, char **argv)
-{
-    int rc;
-
-    rc = shell_cmd_list_lock();
-    if (rc != 0) {
-        return -1;
-    }
-    if(argc > 1){
-        if(!strcmp(argv[1], "show")){
-            console_printf("Prompt character: %c\n", shell_prompt);
-        }   
-        else if (!strcmp(argv[1],"set")){
-            shell_prompt = argv[2][0];
-            console_printf("Prompt set to: %c\n", argv[2][0]);
-            console_set_prompt(argv[2][0]);
-        }
-        else {
-            goto usage;
-        }
-        
-    } 
-    else {
-        goto usage;
-        
-    }
-usage:
-    console_printf("Usage: prompt [set|show] [prompt_char]\n");
-    
-    shell_cmd_list_unlock();
-    
-    return (0);
-  
-}
- 
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/split/README.md
----------------------------------------------------------------------
diff --git a/libs/split/README.md b/libs/split/README.md
deleted file mode 100644
index 1ef4cc5..0000000
--- a/libs/split/README.md
+++ /dev/null
@@ -1,63 +0,0 @@
-
-
-<img src="http://mynewt.apache.org/img/logo.svg" width="250" alt="Apache Mynewt">
-
-## Overview
-
-`libs/split` is a library required to build split applications.  When building a split application you must include `libs/split` in your loader and your application
-
-## Split Image
-
-Split applications allow the user to build the application content separate from the library content by splitting an application into two pieces:
-
-* A "loader" which contains a separate application that can perform upgrades and manage split images
-* A "split app" which contains the main application content and references the libraries in the loader by static linkage
-
-See [split image architecture](http://mynewt.apache.org/latest/os/modules/split/split/) for the details of split image design.
-
-
-## Contents
-
-`libs/split` contains the following components
-
-* The split app configuration which tells the system whether to run the "loader" or the "app"
-* The newrmgr commands to access split functionality
-* The functions used by the loader to check and run a split application
-
-## Examples
-
-### Split App
-
-Your split application and loader must initialize the library by calling
-
-```
-#include "split/split.h"
-void split_app_init(void);
-```
-
-This registers the configuration and commands for split applications.
-
-### Loader
-
-Your loader can call 
-
-```
-int split_app_go(void **entry, int toBoot);
-```
-
-to check whether the split application can be run.  A example is shown below
-
-```
-#include "split/split.h"
-#include "bootutil/bootutil.h"
-    {
-        void *entry;
-        rc = split_app_go(&entry, true);
-        if(rc == 0) {
-            system_start(entry);
-        }
-    }
-```
-
-
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/split/include/split/split.h
----------------------------------------------------------------------
diff --git a/libs/split/include/split/split.h b/libs/split/include/split/split.h
deleted file mode 100644
index 0cf78e3..0000000
--- a/libs/split/include/split/split.h
+++ /dev/null
@@ -1,57 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 _SPLIT_H__
-#define _SPLIT_H__
-
-#define SPLIT_NMGR_OP_SPLIT 0
-
-typedef enum {
-    SPLIT_NONE,
-    SPLIT_TEST,
-    SPLIT_RUN,
-} split_mode_t;
-
-
-typedef enum {
-    SPLIT_INVALID,
-    SPLIT_NOT_MATCHING,
-    SPLIT_MATCHING,
-} split_status_t;
-
-/*
-  * Initializes the split application library */
-void split_app_init(void);
-
-/**
-  * checks the split application state.
-  * If the application is configured to be run (and valid)
-  * returns zero and puts the entry data into entry. NOTE:
-  * Entry data is not a function pointer, but a pointer
-  * suitable to call system_start
-  *
-  * If toBoot is true, also performs the necessary steps
-  * to prepare to boot.  An application may set toBoot to
-  * false and call this function to check whether the split
-  * application is bootable.
- *
- * @Returns zero on success, non-zero on failures */
-int split_app_go(void **entry, int toboot);
-
-#endif /* _SPLIT_H__ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/split/include/split/split_priv.h
----------------------------------------------------------------------
diff --git a/libs/split/include/split/split_priv.h b/libs/split/include/split/split_priv.h
deleted file mode 100644
index 0478b75..0000000
--- a/libs/split/include/split/split_priv.h
+++ /dev/null
@@ -1,30 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 SPLIT_PRIV_H
-#define SPLIT_PRIV_H
-
-int split_conf_init(void);
-int split_nmgr_register(void);
-int split_read_split(split_mode_t *split);
-int split_write_split(split_mode_t mode);
-split_status_t split_check_status(void);
-
-#endif /* SPLIT_PRIV_H */
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/split/pkg.yml
----------------------------------------------------------------------
diff --git a/libs/split/pkg.yml b/libs/split/pkg.yml
deleted file mode 100644
index 0e1260e..0000000
--- a/libs/split/pkg.yml
+++ /dev/null
@@ -1,30 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you 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.
-#
-
-pkg.name: libs/split
-pkg.description: The split image library helps manage and configure split image operation
-pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
-pkg.homepage: "http://mynewt.apache.org/"
-pkg.keywords:
-    - split
-
-
-pkg.deps: 
-    - libs/bootutil
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/split/src/split.c
----------------------------------------------------------------------
diff --git a/libs/split/src/split.c b/libs/split/src/split.c
deleted file mode 100644
index cd0e528..0000000
--- a/libs/split/src/split.c
+++ /dev/null
@@ -1,77 +0,0 @@
-
-#include <assert.h>
-#include <bootutil/bootutil_misc.h>
-#include <bootutil/image.h>
-#include <bootutil/loader.h>
-#include <split/split.h>
-#include <split/split_priv.h>
-
-#define LOADER_IMAGE_SLOT    0
-#define SPLIT_IMAGE_SLOT    1
-#define SPLIT_TOTAL_IMAGES  2
-
-void
-split_app_init(void)
-{
-    int rc;
-
-    rc = split_conf_init();
-    assert(rc==0);
-
-    rc = split_nmgr_register();
-    assert(rc==0);
-}
-
-split_status_t
-split_check_status(void)
-{
-    void *entry;
-    int rc;
-
-    rc = split_go(LOADER_IMAGE_SLOT, SPLIT_IMAGE_SLOT, &entry);
-
-    if(rc == SPLIT_GO_ERR) {
-        return SPLIT_INVALID;
-    } else if (rc) {
-    }
-
-    return SPLIT_MATCHING;
-}
-
-/**
- * This validates and provides the loader image data
- *
- * @param req                   Contains information about the flash layout.
- * @param rsp                   On success, indicates how booting should occur.
- *
- * @return                      0 on success; nonzero on failure.
- */
-int
-split_app_go(void **entry, int toboot)
-{
-    split_mode_t split;
-    int rc;
-
-    if (toboot) {
-        /* if we can't read this, then we don't boot an app */
-        rc = split_read_split(&split);
-        if(rc) {
-            return -1;
-        }
-
-        /* if we are told not to, then we don't boot an app */
-        if (split == SPLIT_NONE) {
-            return -1;
-        }
-
-        /* if this is a one-time test, reset the split mode */
-        if (split == SPLIT_TEST) {
-            split_write_split(SPLIT_NONE);
-        }
-    }
-
-    rc = split_go(LOADER_IMAGE_SLOT, SPLIT_IMAGE_SLOT, entry);
-
-    return (rc);
-}
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/split/src/split_config.c
----------------------------------------------------------------------
diff --git a/libs/split/src/split_config.c b/libs/split/src/split_config.c
deleted file mode 100644
index 57332da..0000000
--- a/libs/split/src/split_config.c
+++ /dev/null
@@ -1,95 +0,0 @@
-
-#include <assert.h>
-#include <string.h>
-#include <config/config.h>
-#include <split/split.h>
-#include <split/split_priv.h>
-
-#define LOADER_IMAGE_SLOT    0
-#define SPLIT_IMAGE_SLOT    1
-#define SPLIT_TOTAL_IMAGES  2
-
-
-static char *split_conf_get(int argc, char **argv, char *buf, int max_len);
-static int split_conf_set(int argc, char **argv, char *val);
-static int split_conf_commit(void);
-static int split_conf_export(void (*func)(char *name, char *val), enum conf_export_tgt tgt);
-
-static struct conf_handler split_conf_handler = {
-    .ch_name = "split",
-    .ch_get =split_conf_get,
-    .ch_set = split_conf_set,
-    .ch_commit = split_conf_commit,
-    .ch_export = split_conf_export
-};
-
-static int8_t split_status;
-
-int
-split_conf_init(void)
-{
-    int rc;
-
-    rc = conf_register(&split_conf_handler);
-
-    return rc;
-}
-
-
-static char *
-split_conf_get(int argc, char **argv, char *buf, int max_len)
-{
-    if (argc == 1) {
-        if (!strcmp(argv[0], "status")) {
-            return conf_str_from_value(CONF_INT8, &split_status, buf, max_len);
-        }
-    }
-    return NULL;
-}
-
-static int
-split_conf_set(int argc, char **argv, char *val)
-{
-    if (argc == 1) {
-        if (!strcmp(argv[0], "status")) {
-            return CONF_VALUE_SET(val, CONF_INT8, split_status);
-        }
-    }
-    return -1;
-}
-
-static int
-split_conf_commit(void)
-{
-    return 0;
-}
-
-static int
-split_conf_export(void (*func)(char *name, char *val), enum conf_export_tgt tgt)
-{
-    char buf[4];
-
-    conf_str_from_value(CONF_INT8, &split_status, buf, sizeof(buf));
-    func("split/status", buf);
-    return 0;
-}
-
-int
-split_read_split(split_mode_t *split)
-{
-    *split = (split_mode_t) split_status;
-    return 0;
-}
-
-int
-split_write_split(split_mode_t split)
-{
-    char str[CONF_STR_FROM_BYTES_LEN(sizeof(split_mode_t))];
-
-    split_status = (int8_t) split;
-    if (!conf_str_from_value(CONF_INT8, &split_status, str, sizeof(str))) {
-        return -1;
-    }
-    return conf_save_one("split/status", str);
-}
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/split/src/split_netmgr.c
----------------------------------------------------------------------
diff --git a/libs/split/src/split_netmgr.c b/libs/split/src/split_netmgr.c
deleted file mode 100644
index 7d2e7dc..0000000
--- a/libs/split/src/split_netmgr.c
+++ /dev/null
@@ -1,149 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include <json/json.h>
-#include <newtmgr/newtmgr.h>
-#include <bootutil/bootutil_misc.h>
-#include <bootutil/image.h>
-#include <split/split.h>
-#include <split/split_priv.h>
-
-
-static int imgr_splitapp_read(struct nmgr_jbuf *njb);
-static int imgr_splitapp_write(struct nmgr_jbuf *njb);
-
-static const struct nmgr_handler split_nmgr_handlers[] = {
-    [SPLIT_NMGR_OP_SPLIT] = {
-        .nh_read = imgr_splitapp_read,
-        .nh_write = imgr_splitapp_write
-    },
-};
-
-static struct nmgr_group split_nmgr_group = {
-    .ng_handlers = (struct nmgr_handler *)split_nmgr_handlers,
-    .ng_handlers_count =
-        sizeof(split_nmgr_handlers) / sizeof(split_nmgr_handlers[0]),
-    .ng_group_id = NMGR_GROUP_ID_SPLIT,
-};
-
-int
-split_nmgr_register(void)
-{
-    int rc;
-    rc = nmgr_group_register(&split_nmgr_group);
-    return (rc);
-}
-
-int
-imgr_splitapp_read(struct nmgr_jbuf *njb)
-{
-    int rc;
-    int x;
-    split_mode_t split;
-    struct json_encoder *enc;
-    struct json_value jv;
-
-    enc = &njb->njb_enc;
-
-    json_encode_object_start(enc);
-
-    rc = split_read_split(&split);
-    if (!rc) {
-        x = split;
-    } else {
-        x = SPLIT_NONE;
-    }
-    JSON_VALUE_INT(&jv, x)
-    json_encode_object_entry(enc, "splitMode", &jv);
-
-    x = split_check_status();
-    JSON_VALUE_INT(&jv, x)
-    json_encode_object_entry(enc, "splitStatus", &jv);
-
-    JSON_VALUE_INT(&jv, NMGR_ERR_EOK);
-    json_encode_object_entry(enc, "rc", &jv);
-
-    json_encode_object_finish(enc);
-
-    return 0;
-}
-
-int
-imgr_splitapp_write(struct nmgr_jbuf *njb)
-{
-    long long int split_mode;
-    long long int send_split_status;  /* ignored */
-    long long int sent_rc; /* ignored */
-    const struct json_attr_t split_write_attr[4] = {
-        [0] =
-        {
-            .attribute = "splitMode",
-            .type = t_integer,
-            .addr.integer = &split_mode,
-            .nodefault = true,
-        },
-        [1] =
-        {
-            .attribute = "splitStatus",
-            .type = t_integer,
-            .addr.integer = &send_split_status,
-            .nodefault = true,
-        },
-        [2] =
-        {
-            .attribute = "rc",
-            .type = t_integer,
-            .addr.integer = &sent_rc,
-            .nodefault = true,
-        },
-        [3] =
-        {
-            .attribute = NULL
-        }
-    };
-    struct json_encoder *enc;
-    struct json_value jv;
-    int rc;
-
-    rc = json_read_object(&njb->njb_buf, split_write_attr);
-    if (rc) {
-        rc = NMGR_ERR_EINVAL;
-        goto err;
-    }
-
-    rc = split_write_split((split_mode_t) split_mode);
-    if (rc) {
-        rc = NMGR_ERR_EINVAL;
-        goto err;
-    }
-
-    enc = &njb->njb_enc;
-
-    json_encode_object_start(enc);
-
-    JSON_VALUE_INT(&jv, NMGR_ERR_EOK);
-    json_encode_object_entry(enc, "rc", &jv);
-
-    json_encode_object_finish(enc);
-
-    return 0;
-err:
-    nmgr_jbuf_setoerr(njb, rc);
-    return 0;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/testreport/include/testreport/testreport.h
----------------------------------------------------------------------
diff --git a/libs/testreport/include/testreport/testreport.h b/libs/testreport/include/testreport/testreport.h
deleted file mode 100644
index 7a0d3e4..0000000
--- a/libs/testreport/include/testreport/testreport.h
+++ /dev/null
@@ -1,34 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 H_TESTREPORT_
-#define H_TESTREPORT_
-
-struct nffs_area_desc;
-
-struct tr_config {
-    const char *tc_base_path;
-    const struct nffs_area_desc *tc_area_descs;
-};
-
-extern struct tr_config tr_config;
-
-int tr_init(void);
-
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/testreport/pkg.yml
----------------------------------------------------------------------
diff --git a/libs/testreport/pkg.yml b/libs/testreport/pkg.yml
deleted file mode 100644
index 502d2c5..0000000
--- a/libs/testreport/pkg.yml
+++ /dev/null
@@ -1,30 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you 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.
-#
-
-pkg.name: libs/testreport
-pkg.description: Library for recording unit test results to flash.
-pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
-pkg.homepage: "http://mynewt.apache.org/"
-pkg.keywords:
-    - unit
-    - test
-
-pkg.deps:
-    - fs/nffs
-    - libs/testutil

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/testreport/src/arch/cortex_m4/io.c
----------------------------------------------------------------------
diff --git a/libs/testreport/src/arch/cortex_m4/io.c b/libs/testreport/src/arch/cortex_m4/io.c
deleted file mode 100644
index fd27585..0000000
--- a/libs/testreport/src/arch/cortex_m4/io.c
+++ /dev/null
@@ -1,91 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include <stddef.h>
-#include "nffs/nffs.h"
-#include "nffs/nffsutil.h"
-#include "testreport_priv.h"
-
-int
-tr_io_write(const char *path, const void *contents, size_t len)
-{
-    int rc;
-
-    rc = nffsutil_write_file(path, contents, len);
-    if (rc != 0) {
-        return -1;
-    }
-
-    return 0;
-}
-
-int
-tr_io_mkdir(const char *path)
-{
-    int rc;
-
-    rc = nffs_mkdir(path);
-    if (rc != 0 && rc != NFFS_EEXIST) {
-        return -1;
-    }
-
-    return 0;
-}
-
-int
-tr_io_rmdir(const char *path)
-{
-    int rc;
-
-    rc = nffs_unlink(path);
-    if (rc != 0 && rc != NFFS_ENOENT) {
-        return -1;
-    }
-
-    return 0;
-}
-
-int
-tr_io_read(const char *path, void *out_data, size_t len, size_t *out_len)
-{
-    uint32_t u32;
-    int rc;
-
-    rc = nffsutil_read_file(path, 0, len, out_data, &u32);
-    if (rc != 0) {
-        return -1;
-    }
-
-    *out_len = u32;
-
-    return 0;
-}
-
-int
-tr_io_delete(const char *path)
-{
-    int rc;
-
-    rc = nffs_unlink(path);
-    if (rc != 0 && rc != NFFS_ENOENT) {
-        return -1;
-    }
-
-    return 0;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/testreport/src/arch/sim/io.c
----------------------------------------------------------------------
diff --git a/libs/testreport/src/arch/sim/io.c b/libs/testreport/src/arch/sim/io.c
deleted file mode 100644
index a5233e5..0000000
--- a/libs/testreport/src/arch/sim/io.c
+++ /dev/null
@@ -1,140 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <errno.h>
-#include <unistd.h>
-#include <sys/stat.h>
-#include "testreport_priv.h"
-
-static char tr_io_buf[1024];
-
-int
-tr_io_write(const char *path, const void *contents, size_t len)
-{
-    FILE *fp;
-    int rc;
-
-    fp = NULL;
-
-    fp = fopen(path, "w+");
-    if (fp == NULL) {
-        rc = -1;
-        goto done;
-    }
-
-    if (contents != NULL && len > 0) {
-        rc = fwrite(contents, len, 1, fp);
-        if (rc != 1) {
-            rc = -1;
-            goto done;
-        }
-    }
-
-    rc = 0;
-
-done:
-    if (fp != NULL) {
-        fclose(fp);
-    }
-
-    return rc;
-}
-
-int
-tr_io_mkdir(const char *path)
-{
-    int rc;
-
-    rc = mkdir(path, 0755);
-    if (rc == -1 && errno != EEXIST) {
-        return -1;
-    }
-
-    return 0;
-}
-
-/* XXX security risk, not portable, blah blah blah */
-int
-tr_io_rmdir(const char *path)
-{
-    int rc; 
-
-    rc = snprintf(tr_io_buf, sizeof tr_io_buf,
-                  "rm -rf '%s'", path);
-    if (rc >= sizeof tr_io_buf) {
-        return -1;
-    }
-
-    rc = system(tr_io_buf);
-    if (rc != 0) {
-        return rc;
-    }
-
-    return 0;
-}
-
-int
-tr_io_read(const char *path, void *out_data, size_t len, size_t *out_len)
-{
-    FILE *fp;
-    uint8_t *dst;
-    int rc;
-    int i;
-
-    fp = NULL;
-
-    fp = fopen(path, "rb");
-    if (fp == NULL) {
-        rc = -1;
-        goto done;
-    }
-
-    dst = out_data;
-    for (i = 0; i < len; i++) {
-        rc = getc(fp);
-        if (rc == EOF) {
-            rc = -1;
-            goto done;
-        }
-
-        dst[i] = rc;
-    }
-
-    *out_len = i;
-    rc = 0;
-
-done:
-    if (fp != NULL) {
-        fclose(fp);
-    }
-
-    return rc;
-}
-
-int
-tr_io_delete(const char *path)
-{
-    int rc;
-
-    rc = remove(path);
-
-    return rc;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/testreport/src/results.c
----------------------------------------------------------------------
diff --git a/libs/testreport/src/results.c b/libs/testreport/src/results.c
deleted file mode 100644
index 77b26c2..0000000
--- a/libs/testreport/src/results.c
+++ /dev/null
@@ -1,190 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include <stdio.h>
-#include "testutil/testutil.h"
-#include "testreport/testreport.h"
-#include "testreport_priv.h"
-
-#define TU_REPORT_META_DIR          ".meta"
-#define TU_REPORT_STATUS_FILENAME   "status"
-
-static char tr_report_buf[1024];
-
-int
-tr_report_rmdir_results(void)
-{
-    if (tr_config.tc_base_path == NULL) {
-        return 0;
-    }
-
-    return tr_io_rmdir(tr_config.tc_base_path);
-}
-
-int
-tr_report_mkdir_results(void)
-{
-    int rc;
-
-    if (tr_config.tc_base_path == NULL) {
-        return 0;
-    }
-
-    rc = snprintf(tr_report_buf, sizeof tr_report_buf,
-                  "%s", tr_config.tc_base_path);
-    if (rc >= sizeof tr_report_buf) {
-        return -1;
-    }
-    return tr_io_mkdir(tr_report_buf);
-}
-
-int
-tr_report_mkdir_meta(void)
-{
-    int rc;
-
-    if (tr_config.tc_base_path == NULL) {
-        return 0;
-    }
-
-    rc = snprintf(tr_report_buf, sizeof tr_report_buf,
-                  "%s/" TU_REPORT_META_DIR, tr_config.tc_base_path);
-    if (rc >= sizeof tr_report_buf) {
-        return -1;
-    }
-    return tr_io_mkdir(tr_report_buf);
-}
-
-int
-tr_report_mkdir_suite(void)
-{
-    int rc;
-
-    if (tr_config.tc_base_path == NULL) {
-        return 0;
-    }
-
-    rc = snprintf(tr_report_buf, sizeof tr_report_buf,
-                  "%s/%s", tr_config.tc_base_path,
-                  tu_suite_name);
-    if (rc >= sizeof tr_report_buf) {
-        return -1;
-    }
-
-    rc = tr_io_mkdir(tr_report_buf);
-    if (rc != 0) {
-        return rc;
-    }
-
-    return 0;
-}
-
-int
-tr_report_mkdir_case(void)
-{
-    int rc;
-
-    if (tr_config.tc_base_path == NULL) {
-        return 0;
-    }
-
-    rc = snprintf(tr_report_buf, sizeof tr_report_buf,
-                  "%s/%s/%s", tr_config.tc_base_path,
-                  tu_suite_name, tu_case_name);
-    if (rc >= sizeof tr_report_buf) {
-        return -1;
-    }
-
-    rc = tr_io_mkdir(tr_report_buf);
-    if (rc != 0) {
-        return rc;
-    }
-
-    return 0;
-}
-
-int
-tr_report_write_file(const char *filename, const uint8_t *data,
-                     size_t data_len)
-{
-    int rc;
-
-    if (tr_config.tc_base_path == NULL) {
-        return 0;
-    }
-
-    rc = snprintf(tr_report_buf, sizeof tr_report_buf,
-                  "%s/%s/%s/%s", tr_config.tc_base_path,
-                  tu_suite_name, tu_case_name, filename);
-    if (rc >= sizeof tr_report_buf) {
-        return -1;
-    }
-
-    rc = tr_io_write(tr_report_buf, data, data_len);
-    if (rc != 0) {
-        return rc;
-    }
-
-    return 0;
-}
-
-int
-tr_report_read_status(void)
-{
-    size_t bytes_read;
-    int rc;
-
-    rc = snprintf(tr_report_buf, sizeof tr_report_buf,
-                  "%s/%s/%s", tr_config.tc_base_path,
-                  TU_REPORT_META_DIR, TU_REPORT_STATUS_FILENAME);
-    if (rc >= sizeof tr_report_buf) {
-        return -1;
-    }
-
-    rc = tr_io_read(tr_report_buf, &tu_first_idx, sizeof tu_first_idx,
-                    &bytes_read);
-    if (rc != 0 || bytes_read != sizeof tu_first_idx) {
-        return -1;
-    }
-
-    tr_io_delete(tr_report_buf);
-
-    return 0;
-}
-
-int
-tr_report_write_status(void)
-{
-    int rc;
-
-    rc = snprintf(tr_report_buf, sizeof tr_report_buf,
-                  "%s/%s/%s", tr_config.tc_base_path,
-                  TU_REPORT_META_DIR, TU_REPORT_STATUS_FILENAME);
-    if (rc >= sizeof tr_report_buf) {
-        return -1;
-    }
-
-    rc = tr_io_write(tr_report_buf, &tu_first_idx, sizeof tu_first_idx);
-    if (rc != 0) {
-        return -1;
-    }
-
-    return 0;
-
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/testreport/src/testreport.c
----------------------------------------------------------------------
diff --git a/libs/testreport/src/testreport.c b/libs/testreport/src/testreport.c
deleted file mode 100644
index c29221b..0000000
--- a/libs/testreport/src/testreport.c
+++ /dev/null
@@ -1,131 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include <assert.h>
-#include <stdio.h>
-#include "hal/hal_flash.h"
-#include "fs/fs.h"
-#include "nffs/nffs.h"
-#include "testutil/testutil.h"
-#include "testreport/testreport.h"
-#include "testreport_priv.h"
-
-struct tr_config tr_config;
-
-static int tr_case_fail_idx;
-
-static void
-tr_case_init(void *unused)
-{
-    int rc;
-
-    rc = tr_results_mkdir_case();
-    assert(rc == 0);
-}
-
-static void
-tr_case_fail(char *msg, int msg_len, void *unused)
-{
-    char filename[14];
-    int rc;
-
-    rc = snprintf(filename, sizeof filename, "fail-%04d.txt",
-                  tr_case_fail_idx);
-    assert(rc < sizeof filename);
-
-    rc = tr_results_write_file(filename, (uint8_t *)msg, msg_len);
-    assert(rc == 0);
-
-    tr_case_fail_idx++;
-}
-
-static void
-tr_case_pass(char *msg, int msg_len, void *unused)
-{
-    int rc;
-
-    rc = tr_results_write_file("pass.txt", (uint8_t *)msg, msg_len);
-    assert(rc == 0);
-}
-
-static void
-tr_suite_init(void *unused)
-{
-    int rc;
-
-    rc = tr_results_mkdir_suite();
-    assert(rc == 0);
-}
-
-static void
-tr_restart(void *unused)
-{
-    tr_results_write_status();
-}
-
-int
-tr_init(void)
-{
-    int rc;
-
-    if (tr_config.tc_base_path != NULL) {
-        if (tr_config.tc_area_descs != NULL) {
-            rc = hal_flash_init();
-            if (rc != 0) {
-                return -1;
-            }
-
-            rc = nffs_init();
-            if (rc != 0) {
-                return -1;
-            }
-
-            rc = nffs_detect(tr_config.tc_area_descs);
-            if (rc == FS_ECORRUPT) {
-                rc = nffs_format(tr_config.tc_area_descs);
-            }
-            if (rc != 0) {
-                return -1;
-            }
-        }
-
-        rc = tr_results_read_status();
-        if (rc != 0) {
-            tr_results_rmdir_results();
-        }
-
-        rc = tr_results_mkdir_results();
-        if (rc != 0) {
-            return -1;
-        }
-
-        rc = tr_results_mkdir_meta();
-        if (rc != 0) {
-            return -1;
-        }
-    }
-
-    tu_config.tc_case_init_cb = tr_case_init;
-    tu_config.tc_case_fail_cb = tr_case_fail;
-    tu_config.tc_case_pass_cb = tr_case_pass;
-    tu_config.tc_suite_init_cb = tr_suite_init;
-    tu_config.tc_restart_cb = tr_restart;
-
-    return 0;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/testreport/src/testreport_priv.h
----------------------------------------------------------------------
diff --git a/libs/testreport/src/testreport_priv.h b/libs/testreport/src/testreport_priv.h
deleted file mode 100644
index 88576b6..0000000
--- a/libs/testreport/src/testreport_priv.h
+++ /dev/null
@@ -1,48 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 H_TESTREPORT_PRIV_
-#define H_TESTREPORT_PRIV_
-
-#include <stddef.h>
-#include <inttypes.h>
-
-int tr_results_mkdir_results(void);
-int tr_results_rmdir_results(void);
-
-int tr_results_mkdir_meta(void);
-
-int tr_results_mkdir_suite(void);
-int tr_results_mkdir_case(void);
-
-int tr_results_write_file(const char *filename, const uint8_t *data,
-                          size_t data_len);
-
-int tr_results_read_status(void);
-int tr_results_write_status(void);
-
-int tr_io_read(const char *path, void *out_data, size_t len, size_t *out_len);
-int tr_io_write(const char *path, const void *contents, size_t len);
-
-int tr_io_delete(const char *path);
-
-int tr_io_mkdir(const char *path);
-int tr_io_rmdir(const char *path);
-
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/testutil/design.txt
----------------------------------------------------------------------
diff --git a/libs/testutil/design.txt b/libs/testutil/design.txt
deleted file mode 100644
index a1dfd9b..0000000
--- a/libs/testutil/design.txt
+++ /dev/null
@@ -1,476 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you 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.
-#
-
-****** TEST AUTOMATION
-
-*** HISTORY
-Rev.    Date            Changes
-2       2015/09/07      Addition of tu_restart(); clarification of exported
-                            preprocessor symbols.
-1       2015/08/28
-
-
-*** SUMMARY
-
-Automated testing can be done in either of two ways:
-    1. Testing a set of packages on embedded hardware or a simulated
-       environment.
-    2. Testing an individual package in a simulated environment.
-
-
-***** PACKAGE SET TESTING
-
-Automated testing of package sets consists of two components:
-    1. "PC software" which administers tests and manages results.
-    2. Test images which run on the units under test (UUTs).
-
-
-**** PC SOFTWARE
-
-The PC software will need to perform the following tasks:
-    1. Connect to UUT (e.g., via JTAG and OpenOCD) (if embedded).
-    2. Upload test image (if embedded).
-    3. Run test image.
-    4. Read test results from UUT.
-    5. Generate test report.
-
-If any of these tasks fail, a fatal error would need to be logged to the test
-report.
-
-The details of the PC software are TBD, and are not discussed further here.
-
-
-**** TEST IMAGES
-
-Test images are build using the stack tool.  The user will need to create a
-separate stack tool target for each platform under test.  In addition, there
-will be a single stack tool project which contains code to call the appropriate
-test code.  Each test image typically consists of the following:
-    1. The test cases from all relevant packages.
-    2. Some "glue code" from a special test project.
-
-
-*** PACKAGE TEST CASES
-
-A package may optionally contain a set of test cases.  Test cases are not
-normally compiled and linked when a package is built; they are only included
-when the "test" identity is specified.  All of a
-package's test code goes in its 'src/test' directory.  For example, the ffs
-package's test code is located in the following directory:
-
-    libs/ffs/src/test/
-
-This directory contains the source and header files that implement the ffs test
-code.
-
-The test code has access to all the header files in the following directories:
-    * src
-    * src/arch/<target-arch>
-    * include
-    * src/test
-    * src/test/arch/<target-arch>
-    * include directories of all package dependencies
-
-Package test code typically depends on the testutil package, described later in
-this document.  If a package's test code uses testutil, then the package itself
-needs to have testutil in its dependency list.
-
-Some test cases or test initialization code may be platform-specific.  In such
-cases, the platform-specific function definitions are placed in arch
-subdirectories within the package test directory.
-
-When test code is built (i.e., when the "test" identity is specified), the
-stack tool defines the "TEST" macro.  This macro is defined during complilation
-of all C source files in all projects and packages..
-
-
-***** TESTUTIL
-
-The testutil package is a test framework that provides facilities for
-specifying test cases and recording test results.  
-
-
-*** TEST STRUCTURE
-
-Tests are structures according to the following hierarchy:
-
-                [test]
-               /      \
-        [suite]        [suite]
-       /       \      /       \
-     [case] [case]  [case] [case]
-
-
-I.e., a test consists of test suites, and a test suite consits of test cases.
-
-The test code uses testutil to define test suites and test cases.
-
-
-*** TESTUTIL EXAMPLE
-
-The following example demonstrates how to create a simple test suite.
-
-    TEST_CASE(test_addition)
-    {
-        int sum;
-
-        sum = 5 + 10;
-        TEST_ASSERT(sum == 15, "actual value: %d", sum);
-    }
-
-    TEST_CASE(test_times_0)
-    {
-        TEST_ASSERT(3 * 0 == 0);
-        TEST_ASSERT(4 * 0 == 0);
-        TEST_ASSERT(712 * 0 == 0);
-    }
-
-    TEST_SUITE(test_suite_arithmetic)
-    {
-        test_addition();
-        test_times_0();
-    }
-
-The test suite would then be executed via a call to test_suite_arithmetic().
-
-
-*** TEST RESULTS
-
-The testutil package optionally writes test results to a file system residing
-on the UUT.  The contents of the file system can then be retrieved from the UUT
-by the PC software.  When run in an embedded environment, the results are
-written to an ffs file system.  When run in a simulated environment, the
-results are written to the native file system.
-
-Results directory structure:
-    /
-    \u2514\u2500\u2500 test-results
-        \u251c\u2500\u2500 <test-suite-1>
-        |   \u251c\u2500\u2500 <test-case-1>
-        |   \u2502�� \u251c\u2500\u2500 <result-1>.txt
-        |   \u2502�� \u251c\u2500\u2500 [<result-2>.txt]
-        |   \u2502�� \u251c\u2500\u2500 [...]
-        |   \u2502�� \u2514\u2500\u2500 [other-data-files]
-        |   \u251c\u2500\u2500 <test-case-2>
-        |   \u2502�� \u251c\u2500\u2500 <result-1>.txt
-        |   \u2502�� \u251c\u2500\u2500 [<result-2>.txt]
-        |   \u2502�� \u251c\u2500\u2500 [...]
-        |   \u2502�� \u2514\u2500\u2500 [other-data-files]
-        |   \u2514\u2500\u2500 [...]
-        \u251c\u2500\u2500 <test-suite-2>
-        |   \u2514\u2500\u2500 [...]
-        \u2514\u2500\u2500 [...]
-
-The name of the top-level directory is configurable.  This document uses
-'test-results' in its examples.
-
-Each test case directory contains a set of result files, and optionally
-contains data files containing information collected during the test.  Result
-files are named according to one of the following templates:
-
-    * pass.txt
-    * fail-xxxx.txt
-
-Where "xxxx" is a numeric index automatically generated by testutil.  If a test
-passes, its results directory is populated with a single 'pass' file and no
-'fail' files.  If a test fails, its results directory is populated with one or
-more 'fail' files and no 'pass' files.  A result file (pass or fail) optionally
-contains a text string.
-
-In addition, a results directory can contains data files containing information
-collected during the test.  For example, a test case may record timing
-information or statistics.  Test case code specifies the name and contents of a
-data file when it writes one.  Data files can be written during a test case
-regardless of the test outcome.  There are no restrictions on the size or
-contents of data files, but their filenames should be distinct from the test
-result naming scheme described above.  There is no limit to the number of data
-files that a particular test case can write.
-
-Returning to the earlier arithmetic test suite example, suppose the test suite
-completed with the following results:
-
-    * test_addition: 1 assertion success, 0 assertion failures
-    * test_times_0:  1 assertion success, 2 assertion failures
-
-Such a test run would produce the following directory tree:
-
-    /
-    \u2514\u2500\u2500 test-results
-        \u2514\u2500\u2500 test_suite_arithmetic
-            \u251c\u2500\u2500 test_addition
-            \u2502�� \u2514\u2500\u2500 pass.txt
-            \u2514\u2500\u2500 test_times_0
-                \u251c\u2500\u2500 fail-0000.txt
-                \u2514\u2500\u2500 fail-0001.txt
-
-Each 'fail' file would contain a string describing the failure.
-
-
-*** TESTUTIL API
-
-struct tu_config {
-    /** If nonzero, test results are printed to stdout. */
-    int tc_print_results;
-
-    /**
-     * Name of the base results directory (e.g., "test-results").  If null,
-     * results are not written to disk.
-     */
-    const char *tc_results_path;
-
-    /**
-     * Array of flash areas where an ffs file system should be located.  Unused
-     * if run in a simulated environment.  This array must be terminated with a
-     * zero-length area.
-     */
-    const struct ffs_area_desc *tc_area_descs;
-};
-extern struct tu_config tu_config;
-
-Description:
-    The global tu_config struct contains all the testutil package's settings.
-    The struct must be populated before tu_init() is called.
-
--
-
-int tu_init(void)
-
-Description:
-    Initializes the test framework according to the contents of the tu_config
-    struct.  If run in an embedded environment and the
-    tu_config.tc_results_path and tu_config.tc_area_descs fields are non-null,
-    this function ensures an ffs file system is present within the specified
-    flash areas.  If testutil is using an ffs file system, and no valid ffs
-    file system is detected in the specified region of flash, the region is
-    formatted with a new file system.  This function must be called before any
-    tests are run.
-
-    If, immediately prior to a call to tu_init(), the UUT was restarted via a
-    call to tu_restart(), this function skips all the test cases that have
-    already been executed.  See tu_restart() for details.
-
-    Returns 0 on success; nonzero on failure.
-
--
-
-TEST_ASSERT(expression)
-TEST_ASSERT(expression, fail_msg, ...)
-
-Description:
-    Asserts that the specified condition is true.  If the expression is true,
-    nothing gets reported.  The expression argument is mandatory; the rest are
-    optional.  The fail_msg argument is a printf format string which specifies
-    how the remaining arguments are parsed.
-
-    If the expression is false, testutil reports the following message:
-
-        |<file>:<line-number>| failed assertion: <expression>
-        <fail_msg>
-
-    If no fail_msg is specified, only the first line gets reported.
-
-    The test case proceeds as normal after this macro is invoked.
-
-Example:
-    TEST_ASSERT(num_blocks == 1024,
-                "expected: 1024 blocks; got: %d", num_blocks);
-
-    On failure, the above assertion would result in a report like the
-    following:
-
-        |ffs_test.c:426| failed assertion: num_blocks == 1024
-        expected: 1024 blocks; got 12
-
--
-
-TEST_ASSERT_FATAL(expression)
-TEST_ASSERT_FATAL(expression, fail_msg, ...)
-
-Description:
-    These are identical to their TEST_ASSERT counterparts, except that a
-    failure causes the current test case to be aborted.
-
--
-
-TEST_PASS(msg, ...)
-
-Description:
-    Reports a success result for the current test.  This function is not
-    normally needed, as all successful tests automatically write an empty pass
-    result at completion.  This function is only needed when the success result
-    report should contain text.  The msg argument is a printf format string
-    which specifies how the remaining arguments are parsed.  The result file
-    produced by this function contains the following text:
-
-        |<file>:<line-number>| manual pass
-        <msg>
-
-    After this function is called, the remainder of the test case is not
-    executed.  If the current test has already failed when this macro is
-    invoked, the macro has no effect.
-
--
-
-testutil_write_data(const char *filename, const uint8_t *data, size_t data_len)
-
-Description:
-    Writes a data file to the current test results directory.  The file's
-    contents are fully specified by the data and data_len arguments.  If a file
-    with the specified name already exists, it is overwritten.  After this
-    function is called, the test case proceeds as normal.
-
-    Data does not get written to stdout; it only gets written to disk.  This
-    function has no effect if testutil is configured to not write results to
-    disk.
-
--
-
-TEST_CASE(test_case_name) { /* test case code */ }
-
-Description:
-    Defines a test case function with the following type:
-
-        int test_case_name(void)
-
-    The return value is 0 if the test case passed; nonzero if it failed.
-    Generally, the return code is not used.
-
-
--
-
-TEST_SUITE(test_suite_name) { /* test suite code */ }
-
-Description:
-    Defines a test suite function with the following type:
-
-        int test_suite_name(void)
-
-    The return value is 0 if the test suite passed; nonzero if it failed.
-    Generally, the return code is not used.
-
--
-
-void tu_restart(void)
-
-Description:
-    This function is used when a system reset is necessary to proceed with
-    testing.  For example, the OS is designed to run forever once started, so a
-    test which creates several OS tasks and then starts the OS has no means of
-    completing.  This function, when called from such a test, gracefully ends
-    the current test case and proceeds to the next test case.
-
-    The particulars of this function depend on whether it is called from a
-    simulated environment.  In a simulated environment, this function uses a
-    longjmp() call to break out of the current test case.
-
-    In a non-simulated environment, this function performs the following
-    procedure:
-
-        1. Record the current test status to the file system.
-        2. Perform a software reset of the UUT.
-        3. Read test status and delete it from the file system.
-        4. Skip all previously completed test cases.
-
-    If this function is called before any results have been reported for the
-    current test case, a "pass" result gets reported.
-
-    Note: after this function performs a software reset, the UUT may not be
-    fully initialized, depending on the test environment.  For example, if the
-    UUT has been set up to run the test image from RAM via JTAG, variables in
-    the .data section will not get properly initialized by the software reset.
-    Proper initialization in this case would require that data be re-read from
-    the image file via an additional run of the JTAG script.
-
--
-
-ASSERT_IF_TEST(cond)
-
-Description:
-    The effect of this macro depends on whether the TEST macro is defined:
-
-        If defined:     expands to assert().
-        If not defined: expands to nothing.
-
-    This macro is not intended for use within test cases.  Instead, it should
-    be used in normal non-test code to perform computationally-expensive
-    checks.  In non-test builds, the checks do not get performed.
-
-
-***** INDIVIDUAL PACKAGE TESTING
-
-Testing individual packages is performed via the "target test" stack tool
-command.  When testing is done in this manner, the stack tool automatically
-runs the test code on the host machine.  There is no need for an extra stack
-project for producing a test image.
-
-Testing a package in this manner requires a special target that is specific to
-the package.  The target specifies the package to test via the "pkg"
-configuration variable.  The target must not specify a project, or the test
-command will fail.
-
-Below is an example target called testffs that tests the ffs package:
-
-    testffs
-            compiler: sim
-            compiler_def: debug
-            pkg: libs/ffs
-            bsp: hw/bsp/native
-            arch: sim
-            name: testffs
-
-The target specifies the "native" bsp.  This is necessary so that the ffs test
-code can link with the appropriate implementations of the hal functions that it
-depends on.
-
-The test is run by specifying the following stack arguments:
-
-    target test testffs
-
-When the "target test" command is used, the PKG_TEST macro is defined during
-compilation of the package under test.  This is in addition to the TEST macro,
-which is defined during compilation of all packages.
-
-
-***** ISSUES / QUESTIONS
-
-* For individual package tests, the requirement for a separate target for each
-  package may become unwieldy.  Perhaps the stack tool should be modified to
-  allow arbitrary key-value pairs to be specified on the command line.  That
-  way, the target's "pkg" variable could be unset, and the user would specify
-  the package to test when he executes the test command.  This would allow the
-  same target to be used for all packages, e.g.,
-
-        target test testtarget pkg=libs/ffs
-        target test testtarget pkg=libs/os
-
-* Most test frameworks define a lot of extra assertions (e.g., assert_equal(),
-  assert_not_null(), assert_false(), etc).  These don't seem particularly
-  useful to me, so I did not add them.  Typing TEST_ASSERT(x == 5) is no more
-  difficult than TEST_ASSERT_EQUAL(x, 5).  The benefit of the more specific
-  assertions is that they can automatically produce more helpful failure
-  messages.  For example, if TEST_ASSERT_EQUAL(x, 5) fails, the failure message
-  can contain the actual value of x in most cases, whereas a plain
-  TEST_ASSERT() won't automatically log that information.  This didn't seem
-  useful enough to me to justify growing the interface, but I am interested in
-  hearing what others think.
-
-* During testing on embedded devices, the PC software will need some
-  notification when testing is complete, so that it knows when to retrieve the
-  test results.  The testutil package should expose some state that the PC
-  software can poll for this purpose.

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/testutil/include/testutil/testutil.h
----------------------------------------------------------------------
diff --git a/libs/testutil/include/testutil/testutil.h b/libs/testutil/include/testutil/testutil.h
deleted file mode 100644
index de61394..0000000
--- a/libs/testutil/include/testutil/testutil.h
+++ /dev/null
@@ -1,174 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 H_TESTUTIL_
-#define H_TESTUTIL_
-
-#include <inttypes.h>
-#include <setjmp.h>
-
-#include "syscfg/syscfg.h"
-
-/*****************************************************************************
- * Public declarations                                                       *
- *****************************************************************************/
-
-typedef void tu_case_init_fn_t(void *arg);
-typedef void tu_case_report_fn_t(char *msg, int msg_len, void *arg);
-typedef void tu_suite_init_fn_t(void *arg);
-typedef void tu_restart_fn_t(void *arg);
-
-struct tu_config {
-    int tc_print_results;
-    int tc_system_assert;
-
-    tu_case_init_fn_t *tc_case_init_cb;
-    void *tc_case_init_arg;
-
-    tu_case_report_fn_t *tc_case_fail_cb;
-    void *tc_case_fail_arg;
-
-    tu_case_report_fn_t *tc_case_pass_cb;
-    void *tc_case_pass_arg;
-
-    tu_suite_init_fn_t *tc_suite_init_cb;
-    void *tc_suite_init_arg;
-
-    tu_restart_fn_t *tc_restart_cb;
-    void *tc_restart_arg;
-};
-
-extern struct tu_config tu_config;
-extern const char *tu_suite_name;
-extern const char *tu_case_name;
-extern int tu_first_idx;
-
-typedef void tu_post_test_fn_t(void *arg);
-
-void tu_suite_set_post_test_cb(tu_post_test_fn_t *cb, void *cb_arg);
-int tu_parse_args(int argc, char **argv);
-int tu_init(void);
-void tu_restart(void);
-
-/*****************************************************************************
- * Private declarations                                                      *
- *****************************************************************************/
-
-void tu_suite_complete(void);
-void tu_suite_init(const char *name);
-
-void tu_case_init(const char *name);
-void tu_case_complete(void);
-void tu_case_fail_assert(int fatal, const char *file, int line,
-                         const char *expr, const char *format, ...);
-void tu_case_write_pass_auto(void);
-void tu_case_pass_manual(const char *file, int line,
-                         const char *format, ...);
-void tu_case_post_test(void);
-
-extern int tu_any_failed;
-extern int tu_suite_failed;
-extern int tu_case_reported;
-extern int tu_case_failed;
-extern int tu_case_idx;
-extern jmp_buf tu_case_jb;
-
-#define TEST_SUITE(suite_name)                                                \
-    static void TEST_SUITE_##suite_name(void);                                \
-                                                                              \
-    int                                                                       \
-    suite_name(void)                                                          \
-    {                                                                         \
-        tu_suite_init(#suite_name);                                           \
-        TEST_SUITE_##suite_name();                                            \
-        tu_suite_complete();                                                  \
-                                                                              \
-        return tu_suite_failed;                                               \
-    }                                                                         \
-                                                                              \
-    static void                                                               \
-    TEST_SUITE_##suite_name(void)
-
-/* for creating multiple files with test cases all belonging to the same
- * suite */
-#define TEST_CASE_DECL(case_name)  int case_name(void);
-
-#define TEST_CASE(case_name)                                                  \
-    static void TEST_CASE_##case_name(void);                                  \
-                                                                              \
-    int                                                                       \
-    case_name(void)                                                           \
-    {                                                                         \
-        if (tu_case_idx >= tu_first_idx) {                                    \
-            tu_case_init(#case_name);                                         \
-                                                                              \
-            if (setjmp(tu_case_jb) == 0) {                                    \
-                TEST_CASE_##case_name();                                      \
-                tu_case_post_test();                                          \
-                tu_case_write_pass_auto();                                    \
-            }                                                                 \
-        }                                                                     \
-                                                                              \
-        tu_case_complete();                                                   \
-                                                                              \
-        return tu_case_failed;                                                \
-    }                                                                         \
-                                                                              \
-    static void                                                               \
-    TEST_CASE_##case_name(void)
-
-#define FIRST_AUX(first, ...) first
-#define FIRST(...) FIRST_AUX(__VA_ARGS__, _)
-
-#define NUM(...) ARG10(__VA_ARGS__, N, N, N, N, N, N, N, N, 1, _)
-#define ARG10(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, ...) a10
-
-#define REST_OR_0(...) REST_OR_0_AUX(NUM(__VA_ARGS__), __VA_ARGS__)
-#define REST_OR_0_AUX(qty, ...) REST_OR_0_AUX_INNER(qty, __VA_ARGS__)
-#define REST_OR_0_AUX_INNER(qty, ...) REST_OR_0_AUX_##qty(__VA_ARGS__)
-#define REST_OR_0_AUX_1(first) 0
-#define REST_OR_0_AUX_N(first, ...) __VA_ARGS__
-
-#define XSTR(s) STR(s)
-#define STR(s) #s
-
-#define TEST_ASSERT_FULL(fatal, expr, ...) do                                 \
-{                                                                             \
-    if (!(expr)) {                                                            \
-        tu_case_fail_assert((fatal), __FILE__, __LINE__, XSTR(expr),          \
-                            __VA_ARGS__);                                     \
-    }                                                                         \
-} while (0)
-
-#define TEST_ASSERT(...)                                                      \
-    TEST_ASSERT_FULL(0, FIRST(__VA_ARGS__), REST_OR_0(__VA_ARGS__))
-
-#define TEST_ASSERT_FATAL(...)                                                \
-    TEST_ASSERT_FULL(1, FIRST(__VA_ARGS__), REST_OR_0(__VA_ARGS__))
-
-#define TEST_PASS(...)                                                        \
-    tu_case_pass_manual(__FILE__, __LINE__, __VA_ARGS__);
-
-#if MYNEWT_VAL(TEST)
-#define ASSERT_IF_TEST(expr) assert(expr)
-#else
-#define ASSERT_IF_TEST(expr)
-#endif
-
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/testutil/pkg.yml
----------------------------------------------------------------------
diff --git a/libs/testutil/pkg.yml b/libs/testutil/pkg.yml
deleted file mode 100644
index 8314776..0000000
--- a/libs/testutil/pkg.yml
+++ /dev/null
@@ -1,30 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you 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.
-#
-
-pkg.name: libs/testutil
-pkg.description: Support library for implementing unit tests.
-pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
-pkg.homepage: "http://mynewt.apache.org/"
-pkg.keywords:
-    - unit
-    - test
-
-pkg.deps:
-    - hw/hal
-    - libs/os

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/testutil/src/arch/cortex_m4/testutil_arch_arm.c
----------------------------------------------------------------------
diff --git a/libs/testutil/src/arch/cortex_m4/testutil_arch_arm.c b/libs/testutil/src/arch/cortex_m4/testutil_arch_arm.c
deleted file mode 100644
index 52ace63..0000000
--- a/libs/testutil/src/arch/cortex_m4/testutil_arch_arm.c
+++ /dev/null
@@ -1,27 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include "hal/hal_system.h"
-#include "testutil_priv.h"
-
-void
-tu_arch_restart(void)
-{
-    system_reset();
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/testutil/src/arch/sim/testutil_arch_sim.c
----------------------------------------------------------------------
diff --git a/libs/testutil/src/arch/sim/testutil_arch_sim.c b/libs/testutil/src/arch/sim/testutil_arch_sim.c
deleted file mode 100644
index 2d90501..0000000
--- a/libs/testutil/src/arch/sim/testutil_arch_sim.c
+++ /dev/null
@@ -1,30 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include "os/os.h"
-#include "os/os_arch.h"
-#include "os/os_test.h"
-#include "testutil_priv.h"
-
-void
-tu_arch_restart(void)
-{
-    os_arch_os_stop();
-    tu_case_abort();
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/testutil/src/arch/sim/tu_args.c
----------------------------------------------------------------------
diff --git a/libs/testutil/src/arch/sim/tu_args.c b/libs/testutil/src/arch/sim/tu_args.c
deleted file mode 100644
index 75a2900..0000000
--- a/libs/testutil/src/arch/sim/tu_args.c
+++ /dev/null
@@ -1,23 +0,0 @@
-#include <errno.h>
-#include <unistd.h>
-
-#include "testutil/testutil.h"
-
-int
-tu_parse_args(int argc, char **argv)
-{
-    int ch;
-
-    while ((ch = getopt(argc, argv, "s")) != -1) {
-        switch (ch) {
-        case 's':
-            tu_config.tc_system_assert = 1;
-            break;
-
-        default:
-            return EINVAL;
-        }
-    }
-
-    return 0;
-}



[44/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/encoding/tinycbor/src/cborparser.c
----------------------------------------------------------------------
diff --git a/encoding/tinycbor/src/cborparser.c b/encoding/tinycbor/src/cborparser.c
new file mode 100644
index 0000000..1d81091
--- /dev/null
+++ b/encoding/tinycbor/src/cborparser.c
@@ -0,0 +1,1293 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 Intel Corporation
+**
+** Permission is hereby granted, free of charge, to any person obtaining a copy
+** of this software and associated documentation files (the "Software"), to deal
+** in the Software without restriction, including without limitation the rights
+** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+** copies of the Software, and to permit persons to whom the Software is
+** furnished to do so, subject to the following conditions:
+**
+** The above copyright notice and this permission notice shall be included in
+** all copies or substantial portions of the Software.
+**
+** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+** THE SOFTWARE.
+**
+****************************************************************************/
+
+#define _BSD_SOURCE 1
+#define _DEFAULT_SOURCE 1
+#ifndef __STDC_LIMIT_MACROS
+#  define __STDC_LIMIT_MACROS 1
+#endif
+
+#include "cbor.h"
+#include "cborconstants_p.h"
+#include "compilersupport_p.h"
+#include "extract_number_p.h"
+
+#include <assert.h>
+#include <string.h>
+
+#include "assert_p.h"       /* Always include last */
+
+#ifndef CBOR_PARSER_MAX_RECURSIONS
+#  define CBOR_PARSER_MAX_RECURSIONS 1024
+#endif
+
+/**
+ * \defgroup CborParsing Parsing CBOR streams
+ * \brief Group of functions used to parse CBOR streams.
+ *
+ * TinyCBOR provides functions for pull-based stream parsing of a CBOR-encoded
+ * payload. The main data type for the parsing is a CborValue, which behaves
+ * like an iterator and can be used to extract the encoded data. It is first
+ * initialized with a call to cbor_parser_init() and is usually used to extract
+ * exactly one item, most often an array or map.
+ *
+ * Nested CborValue objects can be parsed using cbor_value_enter_container().
+ * Each call to cbor_value_enter_container() must be matched by a call to
+ * cbor_value_leave_container(), with the exact same parameters.
+ *
+ * The example below initializes a CborParser object, begins the parsing with a
+ * CborValue and decodes a single integer:
+ *
+ * \code
+ * int extract_int(const uint8_t *buffer, size_t len)
+ * {
+ *     CborParser parser;
+ *     CborValue value;
+ *     int result;
+ *     cbor_parser_init(buffer, len, 0, &buffer, &value);
+ *     cbor_value_get_int(&value, &result);
+ *     return result;
+ * }
+ * \endcode
+ *
+ * The code above does no error checking, which means it assumes the data comes
+ * from a source trusted to send one properly-encoded integer. The following
+ * example does the exact same operation, but includes error parsing and
+ * returns 0 on parsing failure:
+ *
+ * \code
+ * int extract_int(const uint8_t *buffer, size_t len)
+ * {
+ *     CborParser parser;
+ *     CborValue value;
+ *     int result;
+ *     if (cbor_parser_init(buffer, len, 0, &buffer, &value) != CborNoError)
+ *         return 0;
+ *     if (!cbor_value_is_integer(&value) ||
+ *             cbor_value_get_int(&value, &result) != CborNoError)
+ *         return 0;
+ *     return result;
+ * }
+ * \endcode
+ *
+ * Note, in the example above, that one can't distinguish a parsing failure
+ * from an encoded value of zero. Reporting a parsing error is left as an
+ * exercise to the reader.
+ *
+ * The code above does not execute a range-check either: it is possible that
+ * the value decoded from the CBOR stream encodes a number larger than what can
+ * be represented in a variable of type \c{int}. If detecting that case is
+ * important, the code should call cbor_value_get_int_checked() instead.
+ *
+ * <h3 class="groupheader">Memory and parsing constraints</h3>
+ *
+ * TinyCBOR is designed to run with little memory and with minimal overhead.
+ * Except where otherwise noted, the parser functions always run on constant
+ * time (O(1)), do not recurse and never allocate memory (thus, stack usage is
+ * bounded and is O(1)).
+ *
+ * <h3 class="groupheader">Error handling and preconditions</h3>
+ *
+ * All functions operating on a CborValue return a CborError condition, with
+ * CborNoError standing for the normal situation in which no parsing error
+ * occurred. All functions may return parsing errors in case the stream cannot
+ * be decoded properly, be it due to corrupted data or due to reaching the end
+ * of the input buffer.
+ *
+ * Error conditions must not be ignored. All decoder functions have undefined
+ * behavior if called after an error has been reported, and may crash.
+ *
+ * Some functions are also documented to have preconditions, like
+ * cbor_value_get_int() requiring that the input be an integral value.
+ * Violation of preconditions also results in undefined behavior and the
+ * program may crash.
+ */
+
+/**
+ * \addtogroup CborParsing
+ * @{
+ */
+
+/**
+ * \struct CborValue
+ *
+ * This type contains one value parsed from the CBOR stream. Each CborValue
+ * behaves as an iterator in a StAX-style parser.
+ *
+ * \if privatedocs
+ * Implementation details: the CborValue contains these fields:
+ * \list
+ *   \li ptr: pointer to the actual data
+ *   \li flags: flags from the decoder
+ *   \li extra: partially decoded integer value (0, 1 or 2 bytes)
+ *   \li remaining: remaining items in this collection after this item or UINT32_MAX if length is unknown
+ * \endlist
+ * \endif
+ */
+
+static CborError extract_length(const CborParser *parser, const uint8_t **ptr, size_t *len)
+{
+    uint64_t v;
+    CborError err = extract_number(ptr, parser->end, &v);
+    if (err) {
+        *len = 0;
+        return err;
+    }
+
+    *len = v;
+    if (v != *len)
+        return CborErrorDataTooLarge;
+    return CborNoError;
+}
+
+static bool is_fixed_type(uint8_t type)
+{
+    return type != CborTextStringType && type != CborByteStringType && type != CborArrayType &&
+           type != CborMapType;
+}
+
+static CborError preparse_value(CborValue *it)
+{
+    const CborParser *parser = it->parser;
+    it->type = CborInvalidType;
+
+    /* are we at the end? */
+    if (it->ptr == parser->end)
+        return CborErrorUnexpectedEOF;
+
+    uint8_t descriptor = *it->ptr;
+    uint8_t type = descriptor & MajorTypeMask;
+    it->type = type;
+    it->flags = 0;
+    it->extra = (descriptor &= SmallValueMask);
+
+    if (descriptor > Value64Bit) {
+        if (unlikely(descriptor != IndefiniteLength))
+            return type == CborSimpleType ? CborErrorUnknownType : CborErrorIllegalNumber;
+        if (likely(!is_fixed_type(type))) {
+            /* special case */
+            it->flags |= CborIteratorFlag_UnknownLength;
+            it->type = type;
+            return CborNoError;
+        }
+        return type == CborSimpleType ? CborErrorUnexpectedBreak : CborErrorIllegalNumber;
+    }
+
+    size_t bytesNeeded = descriptor < Value8Bit ? 0 : (1 << (descriptor - Value8Bit));
+    if (bytesNeeded + 1 > (size_t)(parser->end - it->ptr))
+        return CborErrorUnexpectedEOF;
+
+    uint8_t majortype = type >> MajorTypeShift;
+    if (majortype == NegativeIntegerType) {
+        it->flags |= CborIteratorFlag_NegativeInteger;
+        it->type = CborIntegerType;
+    } else if (majortype == SimpleTypesType) {
+        switch (descriptor) {
+        case FalseValue:
+            it->extra = false;
+            it->type = CborBooleanType;
+            break;
+
+        case SinglePrecisionFloat:
+        case DoublePrecisionFloat:
+            it->flags |= CborIteratorFlag_IntegerValueTooLarge;
+            /* fall through */
+        case TrueValue:
+        case NullValue:
+        case UndefinedValue:
+        case HalfPrecisionFloat:
+            it->type = *it->ptr;
+            break;
+
+        case SimpleTypeInNextByte:
+            it->extra = (uint8_t)it->ptr[1];
+#ifndef CBOR_PARSER_NO_STRICT_CHECKS
+            if (unlikely(it->extra < 32)) {
+                it->type = CborInvalidType;
+                return CborErrorIllegalSimpleType;
+            }
+#endif
+            break;
+
+        case 28:
+        case 29:
+        case 30:
+        case Break:
+            assert(false);  /* these conditions can't be reached */
+            return CborErrorUnexpectedBreak;
+        }
+        return CborNoError;
+    }
+
+    /* try to decode up to 16 bits */
+    if (descriptor < Value8Bit)
+        return CborNoError;
+
+    if (descriptor == Value8Bit)
+        it->extra = (uint8_t)it->ptr[1];
+    else if (descriptor == Value16Bit)
+        it->extra = get16(it->ptr + 1);
+    else
+        it->flags |= CborIteratorFlag_IntegerValueTooLarge;     /* Value32Bit or Value64Bit */
+    return CborNoError;
+}
+
+static CborError preparse_next_value(CborValue *it)
+{
+    if (it->remaining != UINT32_MAX) {
+        /* don't decrement the item count if the current item is tag: they don't count */
+        if (it->type != CborTagType && !--it->remaining) {
+            it->type = CborInvalidType;
+            return CborNoError;
+        }
+    } else if (it->remaining == UINT32_MAX && it->ptr != it->parser->end && *it->ptr == (uint8_t)BreakByte) {
+        /* end of map or array */
+        ++it->ptr;
+        it->type = CborInvalidType;
+        it->remaining = 0;
+        return CborNoError;
+    }
+
+    return preparse_value(it);
+}
+
+static CborError advance_internal(CborValue *it)
+{
+    uint64_t length;
+    CborError err = extract_number(&it->ptr, it->parser->end, &length);
+    assert(err == CborNoError);
+
+    if (it->type == CborByteStringType || it->type == CborTextStringType) {
+        assert(length == (size_t)length);
+        assert((it->flags & CborIteratorFlag_UnknownLength) == 0);
+        it->ptr += length;
+    }
+
+    return preparse_next_value(it);
+}
+
+/** \internal
+ *
+ * Decodes the CBOR integer value when it is larger than the 16 bits available
+ * in value->extra. This function requires that value->flags have the
+ * CborIteratorFlag_IntegerValueTooLarge flag set.
+ *
+ * This function is also used to extract single- and double-precision floating
+ * point values (SinglePrecisionFloat == Value32Bit and DoublePrecisionFloat ==
+ * Value64Bit).
+ */
+uint64_t _cbor_value_decode_int64_internal(const CborValue *value)
+{
+    assert(value->flags & CborIteratorFlag_IntegerValueTooLarge ||
+           value->type == CborFloatType || value->type == CborDoubleType);
+
+    /* since the additional information can only be Value32Bit or Value64Bit,
+     * we just need to test for the one bit those two options differ */
+    assert((*value->ptr & SmallValueMask) == Value32Bit || (*value->ptr & SmallValueMask) == Value64Bit);
+    if ((*value->ptr & 1) == (Value32Bit & 1))
+        return get32(value->ptr + 1);
+
+    assert((*value->ptr & SmallValueMask) == Value64Bit);
+    return get64(value->ptr + 1);
+}
+
+/**
+ * Initializes the CBOR parser for parsing \a size bytes beginning at \a
+ * buffer. Parsing will use flags set in \a flags. The iterator to the first
+ * element is returned in \a it.
+ *
+ * The \a parser structure needs to remain valid throughout the decoding
+ * process. It is not thread-safe to share one CborParser among multiple
+ * threads iterating at the same time, but the object can be copied so multiple
+ * threads can iterate.
+ */
+CborError cbor_parser_init(const uint8_t *buffer, size_t size, int flags, CborParser *parser, CborValue *it)
+{
+    memset(parser, 0, sizeof(*parser));
+    parser->end = buffer + size;
+    parser->flags = flags;
+    it->parser = parser;
+    it->ptr = buffer;
+    it->remaining = 1;      /* there's one type altogether, usually an array or map */
+    return preparse_value(it);
+}
+
+/**
+ * \fn bool cbor_value_at_end(const CborValue *it)
+ *
+ * Returns true if \a it has reached the end of the iteration, usually when
+ * advancing after the last item in an array or map.
+ *
+ * In the case of the outermost CborValue object, this function returns true
+ * after decoding a single element. A pointer to the first byte of the
+ * remaining data (if any) can be obtained with cbor_value_get_next_byte().
+ *
+ * \sa cbor_value_advance(), cbor_value_is_valid(), cbor_value_get_next_byte()
+ */
+
+/**
+ * \fn const uint8_t *cbor_value_get_next_byte(const CborValue *it)
+ *
+ * Returns a pointer to the next byte that would be decoded if this CborValue
+ * object were advanced.
+ *
+ * This function is useful if cbor_value_at_end() returns true for the
+ * outermost CborValue: the pointer returned is the first byte of the data
+ * remaining in the buffer, if any. Code can decide whether to begin decoding a
+ * new CBOR data stream from this point, or parse some other data appended to
+ * the same buffer.
+ *
+ * This function may be used even after a parsing error. If that occurred,
+ * then this function returns a pointer to where the parsing error occurred.
+ * Note that the error recovery is not precise and the pointer may not indicate
+ * the exact byte containing bad data.
+ *
+ * \sa cbor_value_at_end()
+ */
+
+/**
+ * \fn bool cbor_value_is_valid(const CborValue *it)
+ *
+ * Returns true if the iterator \a it contains a valid value. Invalid iterators
+ * happen when iteration reaches the end of a container (see \ref
+ * cbor_value_at_end()) or when a search function resulted in no matches.
+ *
+ * \sa cbor_value_advance(), cbor_valie_at_end(), cbor_value_get_type()
+ */
+
+/**
+ * Advances the CBOR value \a it by one fixed-size position. Fixed-size types
+ * are: integers, tags, simple types (including boolean, null and undefined
+ * values) and floating point types.
+ *
+ * If the type is not of fixed size, this function has undefined behavior. Code
+ * must be sure that the current type is one of the fixed-size types before
+ * calling this function. This function is provided because it can guarantee
+ * that runs in constant time (O(1)).
+ *
+ * If the caller is not able to determine whether the type is fixed or not, code
+ * can use the cbor_value_advance() function instead.
+ *
+ * \sa cbor_value_at_end(), cbor_value_advance(), cbor_value_enter_container(), cbor_value_leave_container()
+ */
+CborError cbor_value_advance_fixed(CborValue *it)
+{
+    assert(it->type != CborInvalidType);
+    assert(is_fixed_type(it->type));
+    if (!it->remaining)
+        return CborErrorAdvancePastEOF;
+    return advance_internal(it);
+}
+
+static CborError advance_recursive(CborValue *it, int nestingLevel)
+{
+    if (is_fixed_type(it->type))
+        return advance_internal(it);
+
+    if (!cbor_value_is_container(it)) {
+        size_t len = SIZE_MAX;
+        return _cbor_value_copy_string(it, NULL, &len, it);
+    }
+
+    /* map or array */
+    if (nestingLevel == CBOR_PARSER_MAX_RECURSIONS)
+        return CborErrorNestingTooDeep;
+
+    CborError err;
+    CborValue recursed;
+    err = cbor_value_enter_container(it, &recursed);
+    if (err)
+        return err;
+    while (!cbor_value_at_end(&recursed)) {
+        err = advance_recursive(&recursed, nestingLevel + 1);
+        if (err)
+            return err;
+    }
+    return cbor_value_leave_container(it, &recursed);
+}
+
+
+/**
+ * Advances the CBOR value \a it by one element, skipping over containers.
+ * Unlike cbor_value_advance_fixed(), this function can be called on a CBOR
+ * value of any type. However, if the type is a container (map or array) or a
+ * string with a chunked payload, this function will not run in constant time
+ * and will recurse into itself (it will run on O(n) time for the number of
+ * elements or chunks and will use O(n) memory for the number of nested
+ * containers).
+ *
+ * \sa cbor_value_at_end(), cbor_value_advance_fixed(), cbor_value_enter_container(), cbor_value_leave_container()
+ */
+CborError cbor_value_advance(CborValue *it)
+{
+    assert(it->type != CborInvalidType);
+    if (!it->remaining)
+        return CborErrorAdvancePastEOF;
+    return advance_recursive(it, 0);
+}
+
+/**
+ * \fn bool cbor_value_is_tag(const CborValue *value)
+ *
+ * Returns true if the iterator \a value is valid and points to a CBOR tag.
+ *
+ * \sa cbor_value_get_tag(), cbor_value_skip_tag()
+ */
+
+/**
+ * \fn CborError cbor_value_get_tag(const CborValue *value, CborTag *result)
+ *
+ * Retrieves the CBOR tag value that \a value points to and stores it in \a
+ * result. If the iterator \a value does not point to a CBOR tag value, the
+ * behavior is undefined, so checking with \ref cbor_value_get_type or with
+ * \ref cbor_value_is_tag is recommended.
+ *
+ * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_tag()
+ */
+
+/**
+ * Advances the CBOR value \a it until it no longer points to a tag. If \a it is
+ * already not pointing to a tag, then this function returns it unchanged.
+ *
+ * This function does not run in constant time: it will run on O(n) for n being
+ * the number of tags. It does use constant memory (O(1) memory requirements).
+ *
+ * \sa cbor_value_advance_fixed(), cbor_value_advance()
+ */
+CborError cbor_value_skip_tag(CborValue *it)
+{
+    while (cbor_value_is_tag(it)) {
+        CborError err = cbor_value_advance_fixed(it);
+        if (err)
+            return err;
+    }
+    return CborNoError;
+}
+
+/**
+ * \fn bool cbor_value_is_container(const CborValue *it)
+ *
+ * Returns true if the \a it value is a container and requires recursion in
+ * order to decode (maps and arrays), false otherwise.
+ */
+
+/**
+ * Creates a CborValue iterator pointing to the first element of the container
+ * represented by \a it and saves it in \a recursed. The \a it container object
+ * needs to be kept and passed again to cbor_value_leave_container() in order
+ * to continue iterating past this container.
+ *
+ * The \a it CborValue iterator must point to a container.
+ *
+ * \sa cbor_value_is_container(), cbor_value_leave_container(), cbor_value_advance()
+ */
+CborError cbor_value_enter_container(const CborValue *it, CborValue *recursed)
+{
+    CborError err;
+    assert(cbor_value_is_container(it));
+    *recursed = *it;
+
+    if (it->flags & CborIteratorFlag_UnknownLength) {
+        recursed->remaining = UINT32_MAX;
+        ++recursed->ptr;
+        err = preparse_value(recursed);
+        if (err != CborErrorUnexpectedBreak)
+            return err;
+        /* actually, break was expected here
+         * it's just an empty container */
+        ++recursed->ptr;
+    } else {
+        uint64_t len;
+        err = extract_number(&recursed->ptr, recursed->parser->end, &len);
+        assert(err == CborNoError);
+
+        recursed->remaining = (uint32_t)len;
+        if (recursed->remaining != len || len == UINT32_MAX) {
+            /* back track the pointer to indicate where the error occurred */
+            recursed->ptr = it->ptr;
+            return CborErrorDataTooLarge;
+        }
+        if (recursed->type == CborMapType) {
+            /* maps have keys and values, so we need to multiply by 2 */
+            if (recursed->remaining > UINT32_MAX / 2) {
+                /* back track the pointer to indicate where the error occurred */
+                recursed->ptr = it->ptr;
+                return CborErrorDataTooLarge;
+            }
+            recursed->remaining *= 2;
+        }
+        if (len != 0)
+            return preparse_value(recursed);
+    }
+
+    /* the case of the empty container */
+    recursed->type = CborInvalidType;
+    recursed->remaining = 0;
+    return CborNoError;
+}
+
+/**
+ * Updates \a it to point to the next element after the container. The \a
+ * recursed object needs to point to the element obtained either by advancing
+ * the last element of the container (via cbor_value_advance(),
+ * cbor_value_advance_fixed(), a nested cbor_value_leave_container(), or the \c
+ * next pointer from cbor_value_copy_string() or cbor_value_dup_string()).
+ *
+ * The \a it and \a recursed parameters must be the exact same as passed to
+ * cbor_value_enter_container().
+ *
+ * \sa cbor_value_enter_container(), cbor_value_at_end()
+ */
+CborError cbor_value_leave_container(CborValue *it, const CborValue *recursed)
+{
+    assert(cbor_value_is_container(it));
+    assert(recursed->type == CborInvalidType);
+    it->ptr = recursed->ptr;
+    return preparse_next_value(it);
+}
+
+
+/**
+ * \fn CborType cbor_value_get_type(const CborValue *value)
+ *
+ * Returns the type of the CBOR value that the iterator \a value points to. If
+ * \a value does not point to a valid value, this function returns \ref
+ * CborInvalidType.
+ *
+ * TinyCBOR also provides functions to test directly if a given CborValue object
+ * is of a given type, like cbor_value_is_text_string() and cbor_value_is_null().
+ *
+ * \sa cbor_value_is_valid()
+ */
+
+/**
+ * \fn bool cbor_value_is_null(const CborValue *value)
+ *
+ * Returns true if the iterator \a value is valid and points to a CBOR null type.
+ *
+ * \sa cbor_value_is_valid(), cbor_value_is_undefined()
+ */
+
+/**
+ * \fn bool cbor_value_is_undefined(const CborValue *value)
+ *
+ * Returns true if the iterator \a value is valid and points to a CBOR undefined type.
+ *
+ * \sa cbor_value_is_valid(), cbor_value_is_null()
+ */
+
+/**
+ * \fn bool cbor_value_is_boolean(const CborValue *value)
+ *
+ * Returns true if the iterator \a value is valid and points to a CBOR boolean
+ * type (true or false).
+ *
+ * \sa cbor_value_is_valid(), cbor_value_get_boolean()
+ */
+
+/**
+ * \fn CborError cbor_value_get_boolean(const CborValue *value, bool *result)
+ *
+ * Retrieves the boolean value that \a value points to and stores it in \a
+ * result. If the iterator \a value does not point to a boolean value, the
+ * behavior is undefined, so checking with \ref cbor_value_get_type or with
+ * \ref cbor_value_is_boolean is recommended.
+ *
+ * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_boolean()
+ */
+
+/**
+ * \fn bool cbor_value_is_simple_type(const CborValue *value)
+ *
+ * Returns true if the iterator \a value is valid and points to a CBOR Simple Type
+ * type (other than true, false, null and undefined).
+ *
+ * \sa cbor_value_is_valid(), cbor_value_get_simple_type()
+ */
+
+/**
+ * \fn CborError cbor_value_get_simple_type(const CborValue *value, uint8_t *result)
+ *
+ * Retrieves the CBOR Simple Type value that \a value points to and stores it
+ * in \a result. If the iterator \a value does not point to a simple_type
+ * value, the behavior is undefined, so checking with \ref cbor_value_get_type
+ * or with \ref cbor_value_is_simple_type is recommended.
+ *
+ * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_simple_type()
+ */
+
+/**
+ * \fn bool cbor_value_is_integer(const CborValue *value)
+ *
+ * Returns true if the iterator \a value is valid and points to a CBOR integer
+ * type.
+ *
+ * \sa cbor_value_is_valid(), cbor_value_get_int, cbor_value_get_int64, cbor_value_get_uint64, cbor_value_get_raw_integer
+ */
+
+/**
+ * \fn bool cbor_value_is_unsigned_integer(const CborValue *value)
+ *
+ * Returns true if the iterator \a value is valid and points to a CBOR unsigned
+ * integer type (positive values or zero).
+ *
+ * \sa cbor_value_is_valid(), cbor_value_get_uint64()
+ */
+
+/**
+ * \fn bool cbor_value_is_negative_integer(const CborValue *value)
+ *
+ * Returns true if the iterator \a value is valid and points to a CBOR negative
+ * integer type.
+ *
+ * \sa cbor_value_is_valid(), cbor_value_get_int, cbor_value_get_int64, cbor_value_get_raw_integer
+ */
+
+/**
+ * \fn CborError cbor_value_get_int(const CborValue *value, int *result)
+ *
+ * Retrieves the CBOR integer value that \a value points to and stores it in \a
+ * result. If the iterator \a value does not point to an integer value, the
+ * behavior is undefined, so checking with \ref cbor_value_get_type or with
+ * \ref cbor_value_is_integer is recommended.
+ *
+ * Note that this function does not do range-checking: integral values that do
+ * not fit in a variable of type \c{int} are silently truncated to fit. Use
+ * cbor_value_get_int_checked() that is not acceptable.
+ *
+ * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_integer()
+ */
+
+/**
+ * \fn CborError cbor_value_get_int64(const CborValue *value, int64_t *result)
+ *
+ * Retrieves the CBOR integer value that \a value points to and stores it in \a
+ * result. If the iterator \a value does not point to an integer value, the
+ * behavior is undefined, so checking with \ref cbor_value_get_type or with
+ * \ref cbor_value_is_integer is recommended.
+ *
+ * Note that this function does not do range-checking: integral values that do
+ * not fit in a variable of type \c{int64_t} are silently truncated to fit. Use
+ * cbor_value_get_int64_checked() that is not acceptable.
+ *
+ * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_integer()
+ */
+
+/**
+ * \fn CborError cbor_value_get_uint64(const CborValue *value, uint64_t *result)
+ *
+ * Retrieves the CBOR integer value that \a value points to and stores it in \a
+ * result. If the iterator \a value does not point to an unsigned integer
+ * value, the behavior is undefined, so checking with \ref cbor_value_get_type
+ * or with \ref cbor_value_is_unsigned_integer is recommended.
+ *
+ * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_unsigned_integer()
+ */
+
+/**
+ * \fn CborError cbor_value_get_raw_integer(const CborValue *value, uint64_t *result)
+ *
+ * Retrieves the CBOR integer value that \a value points to and stores it in \a
+ * result. If the iterator \a value does not point to an integer value, the
+ * behavior is undefined, so checking with \ref cbor_value_get_type or with
+ * \ref cbor_value_is_integer is recommended.
+ *
+ * This function is provided because CBOR negative integers can assume values
+ * that cannot be represented with normal 64-bit integer variables.
+ *
+ * If the integer is unsigned (that is, if cbor_value_is_unsigned_integer()
+ * returns true), then \a result will contain the actual value. If the integer
+ * is negative, then \a result will contain the absolute value of that integer,
+ * minus one. That is, \c {actual = -result - 1}. On architectures using two's
+ * complement for representation of negative integers, it is equivalent to say
+ * that \a result will contain the bitwise negation of the actual value.
+ *
+ * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_integer()
+ */
+
+/**
+ * Retrieves the CBOR integer value that \a value points to and stores it in \a
+ * result. If the iterator \a value does not point to an integer value, the
+ * behavior is undefined, so checking with \ref cbor_value_get_type or with
+ * \ref cbor_value_is_integer is recommended.
+ *
+ * Unlike cbor_value_get_int64(), this function performs a check to see if the
+ * stored integer fits in \a result without data loss. If the number is outside
+ * the valid range for the data type, this function returns the recoverable
+ * error CborErrorDataTooLarge. In that case, use either
+ * cbor_value_get_uint64() (if the number is positive) or
+ * cbor_value_get_raw_integer().
+ *
+ * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_integer(), cbor_value_get_int64()
+ */
+CborError cbor_value_get_int64_checked(const CborValue *value, int64_t *result)
+{
+    assert(cbor_value_is_integer(value));
+    uint64_t v = _cbor_value_extract_int64_helper(value);
+
+    /* Check before converting, as the standard says (C11 6.3.1.3 paragraph 3):
+     * "[if] the new type is signed and the value cannot be represented in it; either the
+     *  result is implementation-defined or an implementation-defined signal is raised."
+     *
+     * The range for int64_t is -2^63 to 2^63-1 (int64_t is required to be
+     * two's complement, C11 7.20.1.1 paragraph 3), which in CBOR is
+     * represented the same way, differing only on the "sign bit" (the major
+     * type).
+     */
+
+    if (unlikely(v > (uint64_t)INT64_MAX))
+        return CborErrorDataTooLarge;
+
+    *result = v;
+    if (value->flags & CborIteratorFlag_NegativeInteger)
+        *result = -*result - 1;
+    return CborNoError;
+}
+
+/**
+ * Retrieves the CBOR integer value that \a value points to and stores it in \a
+ * result. If the iterator \a value does not point to an integer value, the
+ * behavior is undefined, so checking with \ref cbor_value_get_type or with
+ * \ref cbor_value_is_integer is recommended.
+ *
+ * Unlike cbor_value_get_int(), this function performs a check to see if the
+ * stored integer fits in \a result without data loss. If the number is outside
+ * the valid range for the data type, this function returns the recoverable
+ * error CborErrorDataTooLarge. In that case, use one of the other integer
+ * functions to obtain the value.
+ *
+ * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_integer(), cbor_value_get_int64(),
+ *     cbor_value_get_uint64(), cbor_value_get_int64_checked(), cbor_value_get_raw_integer()
+ */
+CborError cbor_value_get_int_checked(const CborValue *value, int *result)
+{
+    assert(cbor_value_is_integer(value));
+    uint64_t v = _cbor_value_extract_int64_helper(value);
+
+    /* Check before converting, as the standard says (C11 6.3.1.3 paragraph 3):
+     * "[if] the new type is signed and the value cannot be represented in it; either the
+     *  result is implementation-defined or an implementation-defined signal is raised."
+     *
+     * But we can convert from signed to unsigned without fault (paragraph 2).
+     *
+     * The range for int is implementation-defined and int is not guaranteed use
+     * two's complement representation (int32_t is).
+     */
+
+    if (value->flags & CborIteratorFlag_NegativeInteger) {
+        if (unlikely(v > (unsigned) -(INT_MIN + 1)))
+            return CborErrorDataTooLarge;
+
+        *result = v;
+        *result = -*result - 1;
+    } else {
+        if (unlikely(v > (uint64_t)INT_MAX))
+            return CborErrorDataTooLarge;
+
+        *result = v;
+    }
+    return CborNoError;
+
+}
+
+/**
+ * \fn bool cbor_value_is_length_known(const CborValue *value)
+ *
+ * Returns true if the length of this type is known without calculation. That
+ * is, if the length of this CBOR string, map or array is encoded in the data
+ * stream, this function returns true. If the length is not encoded, it returns
+ * false.
+ *
+ * If the length is known, code can call cbor_value_get_string_length(),
+ * cbor_value_get_array_length() or cbor_value_get_map_length() to obtain the
+ * length. If the length is not known but is necessary, code can use the
+ * cbor_value_calculate_string_length() function (no equivalent function is
+ * provided for maps and arrays).
+ */
+
+/**
+ * \fn bool cbor_value_is_text_string(const CborValue *value)
+ *
+ * Returns true if the iterator \a value is valid and points to a CBOR text
+ * string. CBOR text strings are UTF-8 encoded and usually contain
+ * human-readable text.
+ *
+ * \sa cbor_value_is_valid(), cbor_value_get_string_length(), cbor_value_calculate_string_length(),
+ *     cbor_value_copy_text_string(), cbor_value_dup_text_string()
+ */
+
+/**
+ * \fn bool cbor_value_is_byte_string(const CborValue *value)
+ *
+ * Returns true if the iterator \a value is valid and points to a CBOR text
+ * string. CBOR byte strings are binary data with no specified encoding or
+ * format.
+ *
+ * \sa cbor_value_is_valid(), cbor_value_get_string_length(), cbor_value_calculate_string_length(),
+ *     cbor_value_copy_byte_string(), cbor_value_dup_byte_string()
+ */
+
+/**
+ * \fn CborError cbor_value_get_string_length(const CborValue *value, size_t *length)
+ *
+ * Extracts the length of the byte or text string that \a value points to and
+ * stores it in \a result. If the iterator \a value does not point to a text
+ * string or a byte string, the behaviour is undefined, so checking with \ref
+ * cbor_value_get_type, with \ref cbor_value_is_text_string or \ref
+ * cbor_value_is_byte_string is recommended.
+ *
+ * If the length of this string is not encoded in the CBOR data stream, this
+ * function will return the recoverable error CborErrorUnknownLength. You may
+ * also check whether that is the case by using cbor_value_is_length_known().
+ *
+ * If the length of the string is required but the length was not encoded, use
+ * cbor_value_calculate_string_length(), but note that that function does not
+ * run in constant time.
+ *
+ * \note On 32-bit platforms, this function will return error condition of \ref
+ * CborErrorDataTooLarge if the stream indicates a length that is too big to
+ * fit in 32-bit.
+ *
+ * \sa cbor_value_is_valid(), cbor_value_is_length_known(), cbor_value_calculate_string_length()
+ */
+
+/**
+ * Calculates the length of the byte or text string that \a value points to and
+ * stores it in \a len. If the iterator \a value does not point to a text
+ * string or a byte string, the behaviour is undefined, so checking with \ref
+ * cbor_value_get_type, with \ref cbor_value_is_text_string or \ref
+ * cbor_value_is_byte_string is recommended.
+ *
+ * This function is different from cbor_value_get_string_length() in that it
+ * calculates the length even for strings sent in chunks. For that reason, this
+ * function may not run in constant time (it will run in O(n) time on the
+ * number of chunks). It does use constant memory (O(1)).
+ *
+ * \note On 32-bit platforms, this function will return error condition of \ref
+ * CborErrorDataTooLarge if the stream indicates a length that is too big to
+ * fit in 32-bit.
+ *
+ * \sa cbor_value_get_string_length(), cbor_value_copy_string(), cbor_value_is_length_known()
+ */
+CborError cbor_value_calculate_string_length(const CborValue *value, size_t *len)
+{
+    *len = SIZE_MAX;
+    return _cbor_value_copy_string(value, NULL, len, NULL);
+}
+
+/* We return uintptr_t so that we can pass memcpy directly as the iteration
+ * function. The choice is to optimize for memcpy, which is used in the base
+ * parser API (cbor_value_copy_string), while memcmp is used in convenience API
+ * only. */
+typedef uintptr_t (*IterateFunction)(char *, const uint8_t *, size_t);
+
+static uintptr_t iterate_noop(char *dest, const uint8_t *src, size_t len)
+{
+    (void)dest;
+    (void)src;
+    (void)len;
+    return true;
+}
+
+static uintptr_t iterate_memcmp(char *s1, const uint8_t *s2, size_t len)
+{
+    return memcmp(s1, (const char *)s2, len) == 0;
+}
+
+static CborError iterate_string_chunks(const CborValue *value, char *buffer, size_t *buflen,
+                                       bool *result, CborValue *next, IterateFunction func)
+{
+    assert(cbor_value_is_byte_string(value) || cbor_value_is_text_string(value));
+
+    size_t total;
+    CborError err;
+    const uint8_t *ptr = value->ptr;
+    if (cbor_value_is_length_known(value)) {
+        /* easy case: fixed length */
+        err = extract_length(value->parser, &ptr, &total);
+        if (err)
+            return err;
+        if (total > (size_t)(value->parser->end - ptr))
+            return CborErrorUnexpectedEOF;
+        if (total <= *buflen)
+            *result = !!func(buffer, ptr, total);
+        else
+            *result = false;
+        ptr += total;
+    } else {
+        /* chunked */
+        ++ptr;
+        total = 0;
+        *result = true;
+        while (true) {
+            size_t chunkLen;
+            size_t newTotal;
+
+            if (ptr == value->parser->end)
+                return CborErrorUnexpectedEOF;
+
+            if (*ptr == (uint8_t)BreakByte) {
+                ++ptr;
+                break;
+            }
+
+            /* is this the right type? */
+            if ((*ptr & MajorTypeMask) != value->type)
+                return CborErrorIllegalType;
+
+            err = extract_length(value->parser, &ptr, &chunkLen);
+            if (err)
+                return err;
+
+            if (unlikely(add_check_overflow(total, chunkLen, &newTotal)))
+                return CborErrorDataTooLarge;
+
+            if (chunkLen > (size_t)(value->parser->end - ptr))
+                return CborErrorUnexpectedEOF;
+
+            if (*result && *buflen >= newTotal)
+                *result = !!func(buffer + total, ptr, chunkLen);
+            else
+                *result = false;
+
+            ptr += chunkLen;
+            total = newTotal;
+        }
+    }
+
+    /* is there enough room for the ending NUL byte? */
+    if (*result && *buflen > total)
+        *result = !!func(buffer + total, (const uint8_t *)"", 1);
+    *buflen = total;
+
+    if (next) {
+        *next = *value;
+        next->ptr = ptr;
+        return preparse_next_value(next);
+    }
+    return CborNoError;
+}
+
+/**
+ * \fn CborError cbor_value_copy_text_string(const CborValue *value, char *buffer, size_t *buflen, CborValue *next)
+ *
+ * Copies the string pointed by \a value into the buffer provided at \a buffer
+ * of \a buflen bytes. If \a buffer is a NULL pointer, this function will not
+ * copy anything and will only update the \a next value.
+ *
+ * If the iterator \a value does not point to a text string, the behaviour is
+ * undefined, so checking with \ref cbor_value_get_type or \ref
+ * cbor_value_is_text_string is recommended.
+ *
+ * If the provided buffer length was too small, this function returns an error
+ * condition of \ref CborErrorOutOfMemory. If you need to calculate the length
+ * of the string in order to preallocate a buffer, use
+ * cbor_value_calculate_string_length().
+ *
+ * On success, this function sets the number of bytes copied to \c{*buflen}. If
+ * the buffer is large enough, this function will insert a null byte after the
+ * last copied byte, to facilitate manipulation of text strings. That byte is
+ * not included in the returned value of \c{*buflen}.
+ *
+ * The \a next pointer, if not null, will be updated to point to the next item
+ * after this string. If \a value points to the last item, then \a next will be
+ * invalid.
+ *
+ * This function may not run in constant time (it will run in O(n) time on the
+ * number of chunks). It requires constant memory (O(1)).
+ *
+ * \note This function does not perform UTF-8 validation on the incoming text
+ * string.
+ *
+ * \sa cbor_value_dup_text_string(), cbor_value_copy_byte_string(), cbor_value_get_string_length(), cbor_value_calculate_string_length()
+ */
+
+/**
+ * \fn CborError cbor_value_copy_byte_string(const CborValue *value, uint8_t *buffer, size_t *buflen, CborValue *next)
+ *
+ * Copies the string pointed by \a value into the buffer provided at \a buffer
+ * of \a buflen bytes. If \a buffer is a NULL pointer, this function will not
+ * copy anything and will only update the \a next value.
+ *
+ * If the iterator \a value does not point to a byte string, the behaviour is
+ * undefined, so checking with \ref cbor_value_get_type or \ref
+ * cbor_value_is_byte_string is recommended.
+ *
+ * If the provided buffer length was too small, this function returns an error
+ * condition of \ref CborErrorOutOfMemory. If you need to calculate the length
+ * of the string in order to preallocate a buffer, use
+ * cbor_value_calculate_string_length().
+ *
+ * On success, this function sets the number of bytes copied to \c{*buflen}. If
+ * the buffer is large enough, this function will insert a null byte after the
+ * last copied byte, to facilitate manipulation of null-terminated strings.
+ * That byte is not included in the returned value of \c{*buflen}.
+ *
+ * The \a next pointer, if not null, will be updated to point to the next item
+ * after this string. If \a value points to the last item, then \a next will be
+ * invalid.
+ *
+ * This function may not run in constant time (it will run in O(n) time on the
+ * number of chunks). It requires constant memory (O(1)).
+ *
+ * \sa cbor_value_dup_text_string(), cbor_value_copy_text_string(), cbor_value_get_string_length(), cbor_value_calculate_string_length()
+ */
+
+CborError _cbor_value_copy_string(const CborValue *value, void *buffer,
+                                 size_t *buflen, CborValue *next)
+{
+    bool copied_all;
+    CborError err = iterate_string_chunks(value, (char*)buffer, buflen, &copied_all, next,
+                                          buffer ? (IterateFunction)memcpy : iterate_noop);
+    return err ? err :
+                 copied_all ? CborNoError : CborErrorOutOfMemory;
+}
+
+/**
+ * Compares the entry \a value with the string \a string and store the result
+ * in \a result. If the value is different from \a string \a result will
+ * contain \c false.
+ *
+ * The entry at \a value may be a tagged string. If \a is not a string or a
+ * tagged string, the comparison result will be false.
+ *
+ * CBOR requires text strings to be encoded in UTF-8, but this function does
+ * not validate either the strings in the stream or the string \a string to be
+ * matched. Moreover, comparison is done on strict codepoint comparison,
+ * without any Unicode normalization.
+ *
+ * This function may not run in constant time (it will run in O(n) time on the
+ * number of chunks). It requires constant memory (O(1)).
+ *
+ * \sa cbor_value_skip_tag(), cbor_value_copy_text_string()
+ */
+CborError cbor_value_text_string_equals(const CborValue *value, const char *string, bool *result)
+{
+    CborValue copy = *value;
+    CborError err = cbor_value_skip_tag(&copy);
+    if (err)
+        return err;
+    if (!cbor_value_is_text_string(&copy)) {
+        *result = false;
+        return CborNoError;
+    }
+
+    size_t len = strlen(string);
+    return iterate_string_chunks(&copy, CONST_CAST(char *, string), &len, result, NULL, iterate_memcmp);
+}
+
+/**
+ * \fn bool cbor_value_is_array(const CborValue *value)
+ *
+ * Returns true if the iterator \a value is valid and points to a CBOR array.
+ *
+ * \sa cbor_value_is_valid(), cbor_value_is_map()
+ */
+
+/**
+ * \fn CborError cbor_value_get_array_length(const CborValue *value, size_t *length)
+ *
+ * Extracts the length of the CBOR array that \a value points to and stores it
+ * in \a result. If the iterator \a value does not point to a CBOR array, the
+ * behaviour is undefined, so checking with \ref cbor_value_get_type or \ref
+ * cbor_value_is_array is recommended.
+ *
+ * If the length of this array is not encoded in the CBOR data stream, this
+ * function will return the recoverable error CborErrorUnknownLength. You may
+ * also check whether that is the case by using cbor_value_is_length_known().
+ *
+ * \note On 32-bit platforms, this function will return error condition of \ref
+ * CborErrorDataTooLarge if the stream indicates a length that is too big to
+ * fit in 32-bit.
+ *
+ * \sa cbor_value_is_valid(), cbor_value_is_length_known()
+ */
+
+/**
+ * \fn bool cbor_value_is_map(const CborValue *value)
+ *
+ * Returns true if the iterator \a value is valid and points to a CBOR map.
+ *
+ * \sa cbor_value_is_valid(), cbor_value_is_array()
+ */
+
+/**
+ * \fn CborError cbor_value_get_map_length(const CborValue *value, size_t *length)
+ *
+ * Extracts the length of the CBOR map that \a value points to and stores it in
+ * \a result. If the iterator \a value does not point to a CBOR map, the
+ * behaviour is undefined, so checking with \ref cbor_value_get_type or \ref
+ * cbor_value_is_map is recommended.
+ *
+ * If the length of this map is not encoded in the CBOR data stream, this
+ * function will return the recoverable error CborErrorUnknownLength. You may
+ * also check whether that is the case by using cbor_value_is_length_known().
+ *
+ * \note On 32-bit platforms, this function will return error condition of \ref
+ * CborErrorDataTooLarge if the stream indicates a length that is too big to
+ * fit in 32-bit.
+ *
+ * \sa cbor_value_is_valid(), cbor_value_is_length_known()
+ */
+
+/**
+ * Attempts to find the value in map \a map that corresponds to the text string
+ * entry \a string. If the iterator \a value does not point to a CBOR map, the
+ * behaviour is undefined, so checking with \ref cbor_value_get_type or \ref
+ * cbor_value_is_map is recommended.
+ *
+ * If the item is found, it is stored in \a result. If no item is found
+ * matching the key, then \a result will contain an element of type \ref
+ * CborInvalidType. Matching is performed using
+ * cbor_value_text_string_equals(), so tagged strings will also match.
+ *
+ * This function has a time complexity of O(n) where n is the number of
+ * elements in the map to be searched. In addition, this function is has O(n)
+ * memory requirement based on the number of nested containers (maps or arrays)
+ * found as elements of this map.
+ *
+ * \sa cbor_value_is_valid(), cbor_value_text_string_equals(), cbor_value_advance()
+ */
+CborError cbor_value_map_find_value(const CborValue *map, const char *string, CborValue *element)
+{
+    assert(cbor_value_is_map(map));
+    size_t len = strlen(string);
+    CborError err = cbor_value_enter_container(map, element);
+    if (err)
+        goto error;
+
+    while (!cbor_value_at_end(element)) {
+        /* find the non-tag so we can compare */
+        err = cbor_value_skip_tag(element);
+        if (err)
+            goto error;
+        if (cbor_value_is_text_string(element)) {
+            bool equals;
+            size_t dummyLen = len;
+            err = iterate_string_chunks(element, CONST_CAST(char *, string), &dummyLen,
+                                        &equals, element, iterate_memcmp);
+            if (err)
+                goto error;
+            if (equals)
+                return preparse_value(element);
+        } else {
+            /* skip this key */
+            err = cbor_value_advance(element);
+            if (err)
+                goto error;
+        }
+
+        /* skip this value */
+        err = cbor_value_skip_tag(element);
+        if (err)
+            goto error;
+        err = cbor_value_advance(element);
+        if (err)
+            goto error;
+    }
+
+    /* not found */
+    element->type = CborInvalidType;
+    return CborNoError;
+
+error:
+    element->type = CborInvalidType;
+    return err;
+}
+
+/**
+ * \fn bool cbor_value_is_float(const CborValue *value)
+ *
+ * Returns true if the iterator \a value is valid and points to a CBOR
+ * single-precision floating point (32-bit).
+ *
+ * \sa cbor_value_is_valid(), cbor_value_is_double(), cbor_value_is_half_float()
+ */
+
+/**
+ * \fn CborError cbor_value_get_float(const CborValue *value, float *result)
+ *
+ * Retrieves the CBOR single-precision floating point (32-bit) value that \a
+ * value points to and stores it in \a result. If the iterator \a value does
+ * not point to a single-precision floating point value, the behavior is
+ * undefined, so checking with \ref cbor_value_get_type or with \ref
+ * cbor_value_is_float is recommended.
+ *
+ * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_float(), cbor_value_get_double()
+ */
+
+/**
+ * \fn bool cbor_value_is_double(const CborValue *value)
+ *
+ * Returns true if the iterator \a value is valid and points to a CBOR
+ * double-precision floating point (64-bit).
+ *
+ * \sa cbor_value_is_valid(), cbor_value_is_float(), cbor_value_is_half_float()
+ */
+
+/**
+ * \fn CborError cbor_value_get_double(const CborValue *value, float *result)
+ *
+ * Retrieves the CBOR double-precision floating point (64-bit) value that \a
+ * value points to and stores it in \a result. If the iterator \a value does
+ * not point to a double-precision floating point value, the behavior is
+ * undefined, so checking with \ref cbor_value_get_type or with \ref
+ * cbor_value_is_double is recommended.
+ *
+ * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_double(), cbor_value_get_float()
+ */
+
+/**
+ * \fn bool cbor_value_is_half_float(const CborValue *value)
+ *
+ * Returns true if the iterator \a value is valid and points to a CBOR
+ * single-precision floating point (16-bit).
+ *
+ * \sa cbor_value_is_valid(), cbor_value_is_double(), cbor_value_is_float()
+ */
+
+/**
+ * Retrieves the CBOR half-precision floating point (16-bit) value that \a
+ * value points to and stores it in \a result. If the iterator \a value does
+ * not point to a half-precision floating point value, the behavior is
+ * undefined, so checking with \ref cbor_value_get_type or with \ref
+ * cbor_value_is_half_float is recommended.
+ *
+ * Note: since the C language does not have a standard type for half-precision
+ * floating point, this function takes a \c{void *} as a parameter for the
+ * storage area, which must be at least 16 bits wide.
+ *
+ * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_half_float(), cbor_value_get_float()
+ */
+CborError cbor_value_get_half_float(const CborValue *value, void *result)
+{
+    assert(cbor_value_is_half_float(value));
+
+    /* size has been computed already */
+    uint16_t v = get16(value->ptr + 1);
+    memcpy(result, &v, sizeof(v));
+    return CborNoError;
+}
+
+/** @} */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/encoding/tinycbor/src/cborparser_dup_string.c
----------------------------------------------------------------------
diff --git a/encoding/tinycbor/src/cborparser_dup_string.c b/encoding/tinycbor/src/cborparser_dup_string.c
new file mode 100644
index 0000000..60dbdbe
--- /dev/null
+++ b/encoding/tinycbor/src/cborparser_dup_string.c
@@ -0,0 +1,113 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 Intel Corporation
+**
+** Permission is hereby granted, free of charge, to any person obtaining a copy
+** of this software and associated documentation files (the "Software"), to deal
+** in the Software without restriction, including without limitation the rights
+** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+** copies of the Software, and to permit persons to whom the Software is
+** furnished to do so, subject to the following conditions:
+**
+** The above copyright notice and this permission notice shall be included in
+** all copies or substantial portions of the Software.
+**
+** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+** THE SOFTWARE.
+**
+****************************************************************************/
+
+#define _BSD_SOURCE 1
+#define _DEFAULT_SOURCE 1
+#ifndef __STDC_LIMIT_MACROS
+#  define __STDC_LIMIT_MACROS 1
+#endif
+
+#include "cbor.h"
+#include <stdlib.h>
+
+/**
+ * \fn CborError cbor_value_dup_text_string(const CborValue *value, char **buffer, size_t *buflen, CborValue *next)
+ *
+ * Allocates memory for the string pointed by \a value and copies it into this
+ * buffer. The pointer to the buffer is stored in \a buffer and the number of
+ * bytes copied is stored in \a len (those variables must not be NULL).
+ *
+ * If the iterator \a value does not point to a text string, the behaviour is
+ * undefined, so checking with \ref cbor_value_get_type or \ref
+ * cbor_value_is_text_string is recommended.
+ *
+ * If \c malloc returns a NULL pointer, this function will return error
+ * condition \ref CborErrorOutOfMemory.
+ *
+ * On success, \c{*buffer} will contain a valid pointer that must be freed by
+ * calling \c{free()}. This is the case even for zero-length strings.
+ *
+ * The \a next pointer, if not null, will be updated to point to the next item
+ * after this string. If \a value points to the last item, then \a next will be
+ * invalid.
+ *
+ * This function may not run in constant time (it will run in O(n) time on the
+ * number of chunks). It requires constant memory (O(1)) in addition to the
+ * malloc'ed block.
+ *
+ * \note This function does not perform UTF-8 validation on the incoming text
+ * string.
+ *
+ * \sa cbor_value_copy_text_string(), cbor_value_dup_byte_string()
+ */
+
+/**
+ * \fn CborError cbor_value_dup_byte_string(const CborValue *value, uint8_t **buffer, size_t *buflen, CborValue *next)
+ *
+ * Allocates memory for the string pointed by \a value and copies it into this
+ * buffer. The pointer to the buffer is stored in \a buffer and the number of
+ * bytes copied is stored in \a len (those variables must not be NULL).
+ *
+ * If the iterator \a value does not point to a byte string, the behaviour is
+ * undefined, so checking with \ref cbor_value_get_type or \ref
+ * cbor_value_is_byte_string is recommended.
+ *
+ * If \c malloc returns a NULL pointer, this function will return error
+ * condition \ref CborErrorOutOfMemory.
+ *
+ * On success, \c{*buffer} will contain a valid pointer that must be freed by
+ * calling \c{free()}. This is the case even for zero-length strings.
+ *
+ * The \a next pointer, if not null, will be updated to point to the next item
+ * after this string. If \a value points to the last item, then \a next will be
+ * invalid.
+ *
+ * This function may not run in constant time (it will run in O(n) time on the
+ * number of chunks). It requires constant memory (O(1)) in addition to the
+ * malloc'ed block.
+ *
+ * \sa cbor_value_copy_byte_string(), cbor_value_dup_text_string()
+ */
+CborError _cbor_value_dup_string(const CborValue *value, void **buffer, size_t *buflen, CborValue *next)
+{
+    assert(buffer);
+    assert(buflen);
+    *buflen = SIZE_MAX;
+    CborError err = _cbor_value_copy_string(value, NULL, buflen, NULL);
+    if (err)
+        return err;
+
+    ++*buflen;
+    *buffer = malloc(*buflen);
+    if (!*buffer) {
+        /* out of memory */
+        return CborErrorOutOfMemory;
+    }
+    err = _cbor_value_copy_string(value, *buffer, buflen, next);
+    if (err) {
+        free(*buffer);
+        return err;
+    }
+    return CborNoError;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/encoding/tinycbor/src/cborpretty.c
----------------------------------------------------------------------
diff --git a/encoding/tinycbor/src/cborpretty.c b/encoding/tinycbor/src/cborpretty.c
new file mode 100644
index 0000000..e8e7316
--- /dev/null
+++ b/encoding/tinycbor/src/cborpretty.c
@@ -0,0 +1,470 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 Intel Corporation
+**
+** Permission is hereby granted, free of charge, to any person obtaining a copy
+** of this software and associated documentation files (the "Software"), to deal
+** in the Software without restriction, including without limitation the rights
+** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+** copies of the Software, and to permit persons to whom the Software is
+** furnished to do so, subject to the following conditions:
+**
+** The above copyright notice and this permission notice shall be included in
+** all copies or substantial portions of the Software.
+**
+** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+** THE SOFTWARE.
+**
+****************************************************************************/
+
+#define _BSD_SOURCE 1
+#define _DEFAULT_SOURCE 1
+#ifndef __STDC_LIMIT_MACROS
+#  define __STDC_LIMIT_MACROS 1
+#endif
+
+#include "cbor.h"
+#include "compilersupport_p.h"
+#include "math_support_p.h"
+
+#include <float.h>
+#include <inttypes.h>
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+/**
+ * \defgroup CborPretty Converting CBOR to text
+ * \brief Group of functions used to convert CBOR to text form.
+ *
+ * This group contains two functions that are can be used to convert one
+ * CborValue object to a text representation. This module attempts to follow
+ * the recommendations from RFC 7049 section 6 "Diagnostic Notation", though it
+ * has a few differences. They are noted below.
+ *
+ * TinyCBOR does not provide a way to convert from the text representation back
+ * to encoded form. To produce a text form meant to be parsed, CborToJson is
+ * recommended instead.
+ *
+ * Either of the functions in this section will attempt to convert exactly one
+ * CborValue object to text. Those functions may return any error documented
+ * for the functions for CborParsing. In addition, if the C standard library
+ * stream functions return with error, the text conversion will return with
+ * error CborErrorIO.
+ *
+ * These functions also perform UTF-8 validation in CBOR text strings. If they
+ * encounter a sequence of bytes that not permitted in UTF-8, they will return
+ * CborErrorInvalidUtf8TextString. That includes encoding of surrogate points
+ * in UTF-8.
+ *
+ * \warning The output type produced by these functions is not guaranteed to
+ * remain stable. A future update of TinyCBOR may produce different output for
+ * the same input and parsers may be unable to handle them.
+ *
+ * \sa CborParsing, CborToJson, cbor_parser_init()
+ */
+
+/**
+ * \addtogroup CborPretty
+ * @{
+ * <h2 class="groupheader">Text format</h2>
+ *
+ * As described in RFC 7049 section 6 "Diagnostic Notation", the format is
+ * largely borrowed from JSON, but modified to suit CBOR's different data
+ * types. TinyCBOR makes further modifications to distinguish different, but
+ * similar values.
+ *
+ * CBOR values are currently encoded as follows:
+ * \par Integrals (unsigned and negative)
+ *      Base-10 (decimal) text representation of the value
+ * \par Byte strings:
+ *      <tt>"h'"</tt> followed by the Base16 (hex) representation of the binary data, followed by an ending quote (')
+ * \par Text strings:
+ *      C-style escaped string in quotes, with C11/C++11 escaping of Unicode codepoints above U+007F.
+ * \par Tags:
+ *      Tag value, with the tagged value in parentheses. No special encoding of the tagged value is performed.
+ * \par Simple types:
+ *      <tt>"simple(nn)"</tt> where \c nn is the simple value
+ * \par Null:
+ *      \c null
+ * \par Undefined:
+ *      \c undefined
+ * \par Booleans:
+ *      \c true or \c false
+ * \par Floating point:
+ *      If NaN or infinite, the actual words \c NaN or \c infinite.
+ *      Otherwise, the decimal representation with as many digits as necessary to ensure no loss of information,
+ *      with float values suffixed by "f" and half-float values suffixed by "f16" (doubles have no suffix). A dot is always present.
+ * \par Arrays:
+ *      Comma-separated list of elements, enclosed in square brackets ("[" and "]").
+ *     If the array length is indeterminate, an underscore ("_") appears immediately after the opening bracket.
+ * \par Maps:
+ *      Comma-separated list of key-value pairs, with the key and value separated
+ *      by a colon (":"), enclosed in curly braces ("{" and "}").
+ *      If the map length is indeterminate, an underscore ("_") appears immediately after the opening brace.
+ */
+
+static int hexDump(FILE *out, const uint8_t *buffer, size_t n)
+{
+    while (n--) {
+        int r = fprintf(out, "%02" PRIx8, *buffer++);
+        if (r < 0)
+            return r;
+    }
+    return 0;   /* should be n * 2, but we don't have the original n anymore */
+}
+
+/* This function decodes buffer as UTF-8 and prints as escaped UTF-16.
+ * On UTF-8 decoding error, it returns CborErrorInvalidUtf8TextString */
+static int utf8EscapedDump(FILE *out, const char *buffer, size_t n)
+{
+    uint32_t uc;
+    while (n--) {
+        uc = (uint8_t)*buffer++;
+        if (uc < 0x80) {
+            /* single-byte UTF-8 */
+            if (uc < 0x7f && uc >= 0x20 && uc != '\\' && uc != '"') {
+                if (fprintf(out, "%c", (char)uc) < 0)
+                    return CborErrorIO;
+                continue;
+            }
+
+            /* print as an escape sequence */
+            char escaped = (char)uc;
+            switch (uc) {
+            case '"':
+            case '\\':
+                break;
+            case '\b':
+                escaped = 'b';
+                break;
+            case '\f':
+                escaped = 'f';
+                break;
+            case '\n':
+                escaped = 'n';
+                break;
+            case '\r':
+                escaped = 'r';
+                break;
+            case '\t':
+                escaped = 't';
+                break;
+            default:
+                goto print_utf16;
+            }
+            if (fprintf(out, "\\%c", escaped) < 0)
+                return CborErrorIO;
+            continue;
+        }
+
+        /* multi-byte UTF-8, decode it */
+        unsigned charsNeeded;
+        uint32_t min_uc;
+        if (unlikely(uc <= 0xC1))
+            return CborErrorInvalidUtf8TextString;
+        if (uc < 0xE0) {
+            /* two-byte UTF-8 */
+            charsNeeded = 2;
+            min_uc = 0x80;
+            uc &= 0x1f;
+        } else if (uc < 0xF0) {
+            /* three-byte UTF-8 */
+            charsNeeded = 3;
+            min_uc = 0x800;
+            uc &= 0x0f;
+        } else if (uc < 0xF5) {
+            /* four-byte UTF-8 */
+            charsNeeded = 4;
+            min_uc = 0x10000;
+            uc &= 0x07;
+        } else {
+            return CborErrorInvalidUtf8TextString;
+        }
+
+        if (n < charsNeeded - 1)
+            return CborErrorInvalidUtf8TextString;
+
+        /* first continuation character */
+        uint8_t b = (uint8_t)*buffer++;
+        if ((b & 0xc0) != 0x80)
+            return CborErrorInvalidUtf8TextString;
+        uc <<= 6;
+        uc |= b & 0x3f;
+
+        if (charsNeeded > 2) {
+            /* second continuation character */
+            b = (uint8_t)*buffer++;
+            if ((b & 0xc0) != 0x80)
+                return CborErrorInvalidUtf8TextString;
+            uc <<= 6;
+            uc |= b & 0x3f;
+
+            if (charsNeeded > 3) {
+                /* third continuation character */
+                b = (uint8_t)*buffer++;
+                if ((b & 0xc0) != 0x80)
+                    return CborErrorInvalidUtf8TextString;
+                uc <<= 6;
+                uc |= b & 0x3f;
+            }
+        }
+
+        /* overlong sequence? surrogate pair? out or range? */
+        if (uc < min_uc || uc - 0xd800U < 2048U || uc > 0x10ffff)
+            return CborErrorInvalidUtf8TextString;
+
+        /* now print the sequence */
+        if (charsNeeded > 3) {
+            /* needs surrogate pairs */
+            if (fprintf(out, "\\u%04" PRIX32 "\\u%04" PRIX32,
+                        (uc >> 10) + 0xd7c0,    /* high surrogate */
+                        (uc % 0x0400) + 0xdc00) < 0)
+                return CborErrorIO;
+        } else {
+print_utf16:
+            /* no surrogate pair needed */
+            if (fprintf(out, "\\u%04" PRIX32, uc) < 0)
+                return CborErrorIO;
+        }
+    }
+    return CborNoError;
+}
+
+static CborError value_to_pretty(FILE *out, CborValue *it);
+static CborError container_to_pretty(FILE *out, CborValue *it, CborType containerType)
+{
+    const char *comma = "";
+    while (!cbor_value_at_end(it)) {
+        if (fprintf(out, "%s", comma) < 0)
+            return CborErrorIO;
+        comma = ", ";
+
+        CborError err = value_to_pretty(out, it);
+        if (err)
+            return err;
+
+        if (containerType == CborArrayType)
+            continue;
+
+        /* map: that was the key, so get the value */
+        if (fprintf(out, ": ") < 0)
+            return CborErrorIO;
+        err = value_to_pretty(out, it);
+        if (err)
+            return err;
+    }
+    return CborNoError;
+}
+
+static CborError value_to_pretty(FILE *out, CborValue *it)
+{
+    CborError err;
+    CborType type = cbor_value_get_type(it);
+    switch (type) {
+    case CborArrayType:
+    case CborMapType: {
+        /* recursive type */
+        CborValue recursed;
+
+        if (fprintf(out, type == CborArrayType ? "[" : "{") < 0)
+            return CborErrorIO;
+        if (!cbor_value_is_length_known(it)) {
+            if (fprintf(out, "_ ") < 0)
+                return CborErrorIO;
+        }
+
+        err = cbor_value_enter_container(it, &recursed);
+        if (err) {
+            it->ptr = recursed.ptr;
+            return err;       /* parse error */
+        }
+        err = container_to_pretty(out, &recursed, type);
+        if (err) {
+            it->ptr = recursed.ptr;
+            return err;       /* parse error */
+        }
+        err = cbor_value_leave_container(it, &recursed);
+        if (err)
+            return err;       /* parse error */
+
+        if (fprintf(out, type == CborArrayType ? "]" : "}") < 0)
+            return CborErrorIO;
+        return CborNoError;
+    }
+
+    case CborIntegerType: {
+        uint64_t val;
+        cbor_value_get_raw_integer(it, &val);    /* can't fail */
+
+        if (cbor_value_is_unsigned_integer(it)) {
+            if (fprintf(out, "%" PRIu64, val) < 0)
+                return CborErrorIO;
+        } else {
+            /* CBOR stores the negative number X as -1 - X
+             * (that is, -1 is stored as 0, -2 as 1 and so forth) */
+            if (++val) {                /* unsigned overflow may happen */
+                if (fprintf(out, "-%" PRIu64, val) < 0)
+                    return CborErrorIO;
+            } else {
+                /* overflown
+                 *   0xffff`ffff`ffff`ffff + 1 =
+                 * 0x1`0000`0000`0000`0000 = 18446744073709551616 (2^64) */
+                if (fprintf(out, "-18446744073709551616") < 0)
+                    return CborErrorIO;
+            }
+        }
+        break;
+    }
+
+    case CborByteStringType:{
+        size_t n = 0;
+        uint8_t *buffer;
+        err = cbor_value_dup_byte_string(it, &buffer, &n, it);
+        if (err)
+            return err;
+
+        bool failed = fprintf(out, "h'") < 0 || hexDump(out, buffer, n) < 0 || fprintf(out, "'") < 0;
+        free(buffer);
+        return failed ? CborErrorIO : CborNoError;
+    }
+
+    case CborTextStringType: {
+        size_t n = 0;
+        char *buffer;
+        err = cbor_value_dup_text_string(it, &buffer, &n, it);
+        if (err)
+            return err;
+
+        err = CborNoError;
+        bool failed = fprintf(out, "\"") < 0
+                      || (err = utf8EscapedDump(out, buffer, n)) != CborNoError
+                      || fprintf(out, "\"") < 0;
+        free(buffer);
+        return err != CborNoError ? err :
+                                    failed ? CborErrorIO : CborNoError;
+    }
+
+    case CborTagType: {
+        CborTag tag;
+        cbor_value_get_tag(it, &tag);       /* can't fail */
+        if (fprintf(out, "%" PRIu64 "(", tag) < 0)
+            return CborErrorIO;
+        err = cbor_value_advance_fixed(it);
+        if (err)
+            return err;
+        err = value_to_pretty(out, it);
+        if (err)
+            return err;
+        if (fprintf(out, ")") < 0)
+            return CborErrorIO;
+        return CborNoError;
+    }
+
+    case CborSimpleType: {
+        uint8_t simple_type;
+        cbor_value_get_simple_type(it, &simple_type);  /* can't fail */
+        if (fprintf(out, "simple(%" PRIu8 ")", simple_type) < 0)
+            return CborErrorIO;
+        break;
+    }
+
+    case CborNullType:
+        if (fprintf(out, "null") < 0)
+            return CborErrorIO;
+        break;
+
+    case CborUndefinedType:
+        if (fprintf(out, "undefined") < 0)
+            return CborErrorIO;
+        break;
+
+    case CborBooleanType: {
+        bool val;
+        cbor_value_get_boolean(it, &val);       /* can't fail */
+        if (fprintf(out, val ? "true" : "false") < 0)
+            return CborErrorIO;
+        break;
+    }
+
+    case CborDoubleType: {
+        const char *suffix;
+        double val;
+        if (false) {
+            float f;
+    case CborFloatType:
+            cbor_value_get_float(it, &f);
+            val = f;
+            suffix = "f";
+        } else if (false) {
+            uint16_t f16;
+    case CborHalfFloatType:
+            cbor_value_get_half_float(it, &f16);
+            val = decode_half(f16);
+            suffix = "f16";
+        } else {
+            cbor_value_get_double(it, &val);
+            suffix = "";
+        }
+
+        int r = fpclassify(val);
+        if (r == FP_NAN || r == FP_INFINITE)
+            suffix = "";
+
+        uint64_t ival = (uint64_t)fabs(val);
+        if (ival == fabs(val)) {
+            /* this double value fits in a 64-bit integer, so show it as such
+             * (followed by a floating point suffix, to disambiguate) */
+            r = fprintf(out, "%s%" PRIu64 ".%s", val < 0 ? "-" : "", ival, suffix);
+        } else {
+            /* this number is definitely not a 64-bit integer */
+            r = fprintf(out, "%." DBL_DECIMAL_DIG_STR "g%s", val, suffix);
+        }
+        if (r < 0)
+            return CborErrorIO;
+        break;
+    }
+
+    case CborInvalidType:
+        if (fprintf(out, "invalid") < 0)
+            return CborErrorIO;
+        return CborErrorUnknownType;
+    }
+
+    err = cbor_value_advance_fixed(it);
+    return err;
+}
+
+/**
+ * \fn CborError cbor_value_to_pretty(FILE *out, const CborValue *value)
+ *
+ * Converts the current CBOR type pointed by \a value to its textual
+ * representation and writes it to the \a out stream. If an error occurs, this
+ * function returns an error code similar to CborParsing.
+ *
+ * \sa cbor_value_to_pretty_advance(), cbor_value_to_json_advance()
+ */
+
+/**
+ * Converts the current CBOR type pointed by \a value to its textual
+ * representation and writes it to the \a out stream. If an error occurs, this
+ * function returns an error code similar to CborParsing.
+ *
+ * If no error ocurred, this function advances \a value to the next element.
+ * Often, concatenating the text representation of multiple elements can be
+ * done by appending a comma to the output stream.
+ *
+ * \sa cbor_value_to_pretty(), cbor_value_to_json_advance()
+ */
+CborError cbor_value_to_pretty_advance(FILE *out, CborValue *value)
+{
+    return value_to_pretty(out, value);
+}
+
+/** @} */


[41/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/hw/cmsis-core/src/ext/core_cm0.h
----------------------------------------------------------------------
diff --git a/hw/cmsis-core/src/ext/core_cm0.h b/hw/cmsis-core/src/ext/core_cm0.h
new file mode 100644
index 0000000..dc821ba
--- /dev/null
+++ b/hw/cmsis-core/src/ext/core_cm0.h
@@ -0,0 +1,682 @@
+/**************************************************************************//**
+ * @file     core_cm0.h
+ * @brief    CMSIS Cortex-M0 Core Peripheral Access Layer Header File
+ * @version  V3.20
+ * @date     25. February 2013
+ *
+ * @note
+ *
+ ******************************************************************************/
+/* Copyright (c) 2009 - 2013 ARM LIMITED
+
+   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 ARM 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 COPYRIGHT HOLDERS AND CONTRIBUTORS BE
+   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+   POSSIBILITY OF SUCH DAMAGE.
+   ---------------------------------------------------------------------------*/
+
+
+#if defined ( __ICCARM__ )
+ #pragma system_include  /* treat file as system include file for MISRA check */
+#endif
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+#ifndef __CORE_CM0_H_GENERIC
+#define __CORE_CM0_H_GENERIC
+
+/** \page CMSIS_MISRA_Exceptions  MISRA-C:2004 Compliance Exceptions
+  CMSIS violates the following MISRA-C:2004 rules:
+
+   \li Required Rule 8.5, object/function definition in header file.<br>
+     Function definitions in header files are used to allow 'inlining'.
+
+   \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.<br>
+     Unions are used for effective representation of core registers.
+
+   \li Advisory Rule 19.7, Function-like macro defined.<br>
+     Function-like macros are used to allow more efficient code.
+ */
+
+
+/*******************************************************************************
+ *                 CMSIS definitions
+ ******************************************************************************/
+/** \ingroup Cortex_M0
+  @{
+ */
+
+/*  CMSIS CM0 definitions */
+#define __CM0_CMSIS_VERSION_MAIN  (0x03)                                   /*!< [31:16] CMSIS HAL main version   */
+#define __CM0_CMSIS_VERSION_SUB   (0x20)                                   /*!< [15:0]  CMSIS HAL sub version    */
+#define __CM0_CMSIS_VERSION       ((__CM0_CMSIS_VERSION_MAIN << 16) | \
+                                    __CM0_CMSIS_VERSION_SUB          )     /*!< CMSIS HAL version number         */
+
+#define __CORTEX_M                (0x00)                                   /*!< Cortex-M Core                    */
+
+
+#if   defined ( __CC_ARM )
+  #define __ASM            __asm                                      /*!< asm keyword for ARM Compiler          */
+  #define __INLINE         __inline                                   /*!< inline keyword for ARM Compiler       */
+  #define __STATIC_INLINE  static __inline
+
+#elif defined ( __ICCARM__ )
+  #define __ASM            __asm                                      /*!< asm keyword for IAR Compiler          */
+  #define __INLINE         inline                                     /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */
+  #define __STATIC_INLINE  static inline
+
+#elif defined ( __GNUC__ )
+  #define __ASM            __asm                                      /*!< asm keyword for GNU Compiler          */
+  #define __INLINE         inline                                     /*!< inline keyword for GNU Compiler       */
+  #define __STATIC_INLINE  static inline
+
+#elif defined ( __TASKING__ )
+  #define __ASM            __asm                                      /*!< asm keyword for TASKING Compiler      */
+  #define __INLINE         inline                                     /*!< inline keyword for TASKING Compiler   */
+  #define __STATIC_INLINE  static inline
+
+#endif
+
+/** __FPU_USED indicates whether an FPU is used or not. This core does not support an FPU at all
+*/
+#define __FPU_USED       0
+
+#if defined ( __CC_ARM )
+  #if defined __TARGET_FPU_VFP
+    #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
+  #endif
+
+#elif defined ( __ICCARM__ )
+  #if defined __ARMVFP__
+    #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
+  #endif
+
+#elif defined ( __GNUC__ )
+  #if defined (__VFP_FP__) && !defined(__SOFTFP__)
+    #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
+  #endif
+
+#elif defined ( __TASKING__ )
+  #if defined __FPU_VFP__
+    #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
+  #endif
+#endif
+
+#include <stdint.h>                      /* standard types definitions */
+#include <core_cmInstr.h>     /* Core Instruction Access */
+#include <core_cmFunc.h>     /* Core Function Access */
+
+#endif /* __CORE_CM0_H_GENERIC */
+
+#ifndef __CMSIS_GENERIC
+
+#ifndef __CORE_CM0_H_DEPENDANT
+#define __CORE_CM0_H_DEPENDANT
+
+/* check device defines and use defaults */
+#if defined __CHECK_DEVICE_DEFINES
+  #ifndef __CM0_REV
+    #define __CM0_REV               0x0000
+    #warning "__CM0_REV not defined in device header file; using default!"
+  #endif
+
+  #ifndef __NVIC_PRIO_BITS
+    #define __NVIC_PRIO_BITS          2
+    #warning "__NVIC_PRIO_BITS not defined in device header file; using default!"
+  #endif
+
+  #ifndef __Vendor_SysTickConfig
+    #define __Vendor_SysTickConfig    0
+    #warning "__Vendor_SysTickConfig not defined in device header file; using default!"
+  #endif
+#endif
+
+/* IO definitions (access restrictions to peripheral registers) */
+/**
+    \defgroup CMSIS_glob_defs CMSIS Global Defines
+
+    <strong>IO Type Qualifiers</strong> are used
+    \li to specify the access to peripheral variables.
+    \li for automatic generation of peripheral register debug information.
+*/
+#ifdef __cplusplus
+  #define   __I     volatile             /*!< Defines 'read only' permissions                 */
+#else
+  #define   __I     volatile const       /*!< Defines 'read only' permissions                 */
+#endif
+#define     __O     volatile             /*!< Defines 'write only' permissions                */
+#define     __IO    volatile             /*!< Defines 'read / write' permissions              */
+
+/*@} end of group Cortex_M0 */
+
+
+
+/*******************************************************************************
+ *                 Register Abstraction
+  Core Register contain:
+  - Core Register
+  - Core NVIC Register
+  - Core SCB Register
+  - Core SysTick Register
+ ******************************************************************************/
+/** \defgroup CMSIS_core_register Defines and Type Definitions
+    \brief Type definitions and defines for Cortex-M processor based devices.
+*/
+
+/** \ingroup    CMSIS_core_register
+    \defgroup   CMSIS_CORE  Status and Control Registers
+    \brief  Core Register type definitions.
+  @{
+ */
+
+/** \brief  Union type to access the Application Program Status Register (APSR).
+ */
+typedef union
+{
+  struct
+  {
+#if (__CORTEX_M != 0x04)
+    uint32_t _reserved0:27;              /*!< bit:  0..26  Reserved                           */
+#else
+    uint32_t _reserved0:16;              /*!< bit:  0..15  Reserved                           */
+    uint32_t GE:4;                       /*!< bit: 16..19  Greater than or Equal flags        */
+    uint32_t _reserved1:7;               /*!< bit: 20..26  Reserved                           */
+#endif
+    uint32_t Q:1;                        /*!< bit:     27  Saturation condition flag          */
+    uint32_t V:1;                        /*!< bit:     28  Overflow condition code flag       */
+    uint32_t C:1;                        /*!< bit:     29  Carry condition code flag          */
+    uint32_t Z:1;                        /*!< bit:     30  Zero condition code flag           */
+    uint32_t N:1;                        /*!< bit:     31  Negative condition code flag       */
+  } b;                                   /*!< Structure used for bit  access                  */
+  uint32_t w;                            /*!< Type      used for word access                  */
+} APSR_Type;
+
+
+/** \brief  Union type to access the Interrupt Program Status Register (IPSR).
+ */
+typedef union
+{
+  struct
+  {
+    uint32_t ISR:9;                      /*!< bit:  0.. 8  Exception number                   */
+    uint32_t _reserved0:23;              /*!< bit:  9..31  Reserved                           */
+  } b;                                   /*!< Structure used for bit  access                  */
+  uint32_t w;                            /*!< Type      used for word access                  */
+} IPSR_Type;
+
+
+/** \brief  Union type to access the Special-Purpose Program Status Registers (xPSR).
+ */
+typedef union
+{
+  struct
+  {
+    uint32_t ISR:9;                      /*!< bit:  0.. 8  Exception number                   */
+#if (__CORTEX_M != 0x04)
+    uint32_t _reserved0:15;              /*!< bit:  9..23  Reserved                           */
+#else
+    uint32_t _reserved0:7;               /*!< bit:  9..15  Reserved                           */
+    uint32_t GE:4;                       /*!< bit: 16..19  Greater than or Equal flags        */
+    uint32_t _reserved1:4;               /*!< bit: 20..23  Reserved                           */
+#endif
+    uint32_t T:1;                        /*!< bit:     24  Thumb bit        (read 0)          */
+    uint32_t IT:2;                       /*!< bit: 25..26  saved IT state   (read 0)          */
+    uint32_t Q:1;                        /*!< bit:     27  Saturation condition flag          */
+    uint32_t V:1;                        /*!< bit:     28  Overflow condition code flag       */
+    uint32_t C:1;                        /*!< bit:     29  Carry condition code flag          */
+    uint32_t Z:1;                        /*!< bit:     30  Zero condition code flag           */
+    uint32_t N:1;                        /*!< bit:     31  Negative condition code flag       */
+  } b;                                   /*!< Structure used for bit  access                  */
+  uint32_t w;                            /*!< Type      used for word access                  */
+} xPSR_Type;
+
+
+/** \brief  Union type to access the Control Registers (CONTROL).
+ */
+typedef union
+{
+  struct
+  {
+    uint32_t nPRIV:1;                    /*!< bit:      0  Execution privilege in Thread mode */
+    uint32_t SPSEL:1;                    /*!< bit:      1  Stack to be used                   */
+    uint32_t FPCA:1;                     /*!< bit:      2  FP extension active flag           */
+    uint32_t _reserved0:29;              /*!< bit:  3..31  Reserved                           */
+  } b;                                   /*!< Structure used for bit  access                  */
+  uint32_t w;                            /*!< Type      used for word access                  */
+} CONTROL_Type;
+
+/*@} end of group CMSIS_CORE */
+
+
+/** \ingroup    CMSIS_core_register
+    \defgroup   CMSIS_NVIC  Nested Vectored Interrupt Controller (NVIC)
+    \brief      Type definitions for the NVIC Registers
+  @{
+ */
+
+/** \brief  Structure type to access the Nested Vectored Interrupt Controller (NVIC).
+ */
+typedef struct
+{
+  __IO uint32_t ISER[1];                 /*!< Offset: 0x000 (R/W)  Interrupt Set Enable Register           */
+       uint32_t RESERVED0[31];
+  __IO uint32_t ICER[1];                 /*!< Offset: 0x080 (R/W)  Interrupt Clear Enable Register          */
+       uint32_t RSERVED1[31];
+  __IO uint32_t ISPR[1];                 /*!< Offset: 0x100 (R/W)  Interrupt Set Pending Register           */
+       uint32_t RESERVED2[31];
+  __IO uint32_t ICPR[1];                 /*!< Offset: 0x180 (R/W)  Interrupt Clear Pending Register         */
+       uint32_t RESERVED3[31];
+       uint32_t RESERVED4[64];
+  __IO uint32_t IP[8];                   /*!< Offset: 0x300 (R/W)  Interrupt Priority Register              */
+}  NVIC_Type;
+
+/*@} end of group CMSIS_NVIC */
+
+
+/** \ingroup  CMSIS_core_register
+    \defgroup CMSIS_SCB     System Control Block (SCB)
+    \brief      Type definitions for the System Control Block Registers
+  @{
+ */
+
+/** \brief  Structure type to access the System Control Block (SCB).
+ */
+typedef struct
+{
+  __I  uint32_t CPUID;                   /*!< Offset: 0x000 (R/ )  CPUID Base Register                                   */
+  __IO uint32_t ICSR;                    /*!< Offset: 0x004 (R/W)  Interrupt Control and State Register                  */
+       uint32_t RESERVED0;
+  __IO uint32_t AIRCR;                   /*!< Offset: 0x00C (R/W)  Application Interrupt and Reset Control Register      */
+  __IO uint32_t SCR;                     /*!< Offset: 0x010 (R/W)  System Control Register                               */
+  __IO uint32_t CCR;                     /*!< Offset: 0x014 (R/W)  Configuration Control Register                        */
+       uint32_t RESERVED1;
+  __IO uint32_t SHP[2];                  /*!< Offset: 0x01C (R/W)  System Handlers Priority Registers. [0] is RESERVED   */
+  __IO uint32_t SHCSR;                   /*!< Offset: 0x024 (R/W)  System Handler Control and State Register             */
+} SCB_Type;
+
+/* SCB CPUID Register Definitions */
+#define SCB_CPUID_IMPLEMENTER_Pos          24                                             /*!< SCB CPUID: IMPLEMENTER Position */
+#define SCB_CPUID_IMPLEMENTER_Msk          (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos)          /*!< SCB CPUID: IMPLEMENTER Mask */
+
+#define SCB_CPUID_VARIANT_Pos              20                                             /*!< SCB CPUID: VARIANT Position */
+#define SCB_CPUID_VARIANT_Msk              (0xFUL << SCB_CPUID_VARIANT_Pos)               /*!< SCB CPUID: VARIANT Mask */
+
+#define SCB_CPUID_ARCHITECTURE_Pos         16                                             /*!< SCB CPUID: ARCHITECTURE Position */
+#define SCB_CPUID_ARCHITECTURE_Msk         (0xFUL << SCB_CPUID_ARCHITECTURE_Pos)          /*!< SCB CPUID: ARCHITECTURE Mask */
+
+#define SCB_CPUID_PARTNO_Pos                4                                             /*!< SCB CPUID: PARTNO Position */
+#define SCB_CPUID_PARTNO_Msk               (0xFFFUL << SCB_CPUID_PARTNO_Pos)              /*!< SCB CPUID: PARTNO Mask */
+
+#define SCB_CPUID_REVISION_Pos              0                                             /*!< SCB CPUID: REVISION Position */
+#define SCB_CPUID_REVISION_Msk             (0xFUL << SCB_CPUID_REVISION_Pos)              /*!< SCB CPUID: REVISION Mask */
+
+/* SCB Interrupt Control State Register Definitions */
+#define SCB_ICSR_NMIPENDSET_Pos            31                                             /*!< SCB ICSR: NMIPENDSET Position */
+#define SCB_ICSR_NMIPENDSET_Msk            (1UL << SCB_ICSR_NMIPENDSET_Pos)               /*!< SCB ICSR: NMIPENDSET Mask */
+
+#define SCB_ICSR_PENDSVSET_Pos             28                                             /*!< SCB ICSR: PENDSVSET Position */
+#define SCB_ICSR_PENDSVSET_Msk             (1UL << SCB_ICSR_PENDSVSET_Pos)                /*!< SCB ICSR: PENDSVSET Mask */
+
+#define SCB_ICSR_PENDSVCLR_Pos             27                                             /*!< SCB ICSR: PENDSVCLR Position */
+#define SCB_ICSR_PENDSVCLR_Msk             (1UL << SCB_ICSR_PENDSVCLR_Pos)                /*!< SCB ICSR: PENDSVCLR Mask */
+
+#define SCB_ICSR_PENDSTSET_Pos             26                                             /*!< SCB ICSR: PENDSTSET Position */
+#define SCB_ICSR_PENDSTSET_Msk             (1UL << SCB_ICSR_PENDSTSET_Pos)                /*!< SCB ICSR: PENDSTSET Mask */
+
+#define SCB_ICSR_PENDSTCLR_Pos             25                                             /*!< SCB ICSR: PENDSTCLR Position */
+#define SCB_ICSR_PENDSTCLR_Msk             (1UL << SCB_ICSR_PENDSTCLR_Pos)                /*!< SCB ICSR: PENDSTCLR Mask */
+
+#define SCB_ICSR_ISRPREEMPT_Pos            23                                             /*!< SCB ICSR: ISRPREEMPT Position */
+#define SCB_ICSR_ISRPREEMPT_Msk            (1UL << SCB_ICSR_ISRPREEMPT_Pos)               /*!< SCB ICSR: ISRPREEMPT Mask */
+
+#define SCB_ICSR_ISRPENDING_Pos            22                                             /*!< SCB ICSR: ISRPENDING Position */
+#define SCB_ICSR_ISRPENDING_Msk            (1UL << SCB_ICSR_ISRPENDING_Pos)               /*!< SCB ICSR: ISRPENDING Mask */
+
+#define SCB_ICSR_VECTPENDING_Pos           12                                             /*!< SCB ICSR: VECTPENDING Position */
+#define SCB_ICSR_VECTPENDING_Msk           (0x1FFUL << SCB_ICSR_VECTPENDING_Pos)          /*!< SCB ICSR: VECTPENDING Mask */
+
+#define SCB_ICSR_VECTACTIVE_Pos             0                                             /*!< SCB ICSR: VECTACTIVE Position */
+#define SCB_ICSR_VECTACTIVE_Msk            (0x1FFUL << SCB_ICSR_VECTACTIVE_Pos)           /*!< SCB ICSR: VECTACTIVE Mask */
+
+/* SCB Application Interrupt and Reset Control Register Definitions */
+#define SCB_AIRCR_VECTKEY_Pos              16                                             /*!< SCB AIRCR: VECTKEY Position */
+#define SCB_AIRCR_VECTKEY_Msk              (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos)            /*!< SCB AIRCR: VECTKEY Mask */
+
+#define SCB_AIRCR_VECTKEYSTAT_Pos          16                                             /*!< SCB AIRCR: VECTKEYSTAT Position */
+#define SCB_AIRCR_VECTKEYSTAT_Msk          (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos)        /*!< SCB AIRCR: VECTKEYSTAT Mask */
+
+#define SCB_AIRCR_ENDIANESS_Pos            15                                             /*!< SCB AIRCR: ENDIANESS Position */
+#define SCB_AIRCR_ENDIANESS_Msk            (1UL << SCB_AIRCR_ENDIANESS_Pos)               /*!< SCB AIRCR: ENDIANESS Mask */
+
+#define SCB_AIRCR_SYSRESETREQ_Pos           2                                             /*!< SCB AIRCR: SYSRESETREQ Position */
+#define SCB_AIRCR_SYSRESETREQ_Msk          (1UL << SCB_AIRCR_SYSRESETREQ_Pos)             /*!< SCB AIRCR: SYSRESETREQ Mask */
+
+#define SCB_AIRCR_VECTCLRACTIVE_Pos         1                                             /*!< SCB AIRCR: VECTCLRACTIVE Position */
+#define SCB_AIRCR_VECTCLRACTIVE_Msk        (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos)           /*!< SCB AIRCR: VECTCLRACTIVE Mask */
+
+/* SCB System Control Register Definitions */
+#define SCB_SCR_SEVONPEND_Pos               4                                             /*!< SCB SCR: SEVONPEND Position */
+#define SCB_SCR_SEVONPEND_Msk              (1UL << SCB_SCR_SEVONPEND_Pos)                 /*!< SCB SCR: SEVONPEND Mask */
+
+#define SCB_SCR_SLEEPDEEP_Pos               2                                             /*!< SCB SCR: SLEEPDEEP Position */
+#define SCB_SCR_SLEEPDEEP_Msk              (1UL << SCB_SCR_SLEEPDEEP_Pos)                 /*!< SCB SCR: SLEEPDEEP Mask */
+
+#define SCB_SCR_SLEEPONEXIT_Pos             1                                             /*!< SCB SCR: SLEEPONEXIT Position */
+#define SCB_SCR_SLEEPONEXIT_Msk            (1UL << SCB_SCR_SLEEPONEXIT_Pos)               /*!< SCB SCR: SLEEPONEXIT Mask */
+
+/* SCB Configuration Control Register Definitions */
+#define SCB_CCR_STKALIGN_Pos                9                                             /*!< SCB CCR: STKALIGN Position */
+#define SCB_CCR_STKALIGN_Msk               (1UL << SCB_CCR_STKALIGN_Pos)                  /*!< SCB CCR: STKALIGN Mask */
+
+#define SCB_CCR_UNALIGN_TRP_Pos             3                                             /*!< SCB CCR: UNALIGN_TRP Position */
+#define SCB_CCR_UNALIGN_TRP_Msk            (1UL << SCB_CCR_UNALIGN_TRP_Pos)               /*!< SCB CCR: UNALIGN_TRP Mask */
+
+/* SCB System Handler Control and State Register Definitions */
+#define SCB_SHCSR_SVCALLPENDED_Pos         15                                             /*!< SCB SHCSR: SVCALLPENDED Position */
+#define SCB_SHCSR_SVCALLPENDED_Msk         (1UL << SCB_SHCSR_SVCALLPENDED_Pos)            /*!< SCB SHCSR: SVCALLPENDED Mask */
+
+/*@} end of group CMSIS_SCB */
+
+
+/** \ingroup  CMSIS_core_register
+    \defgroup CMSIS_SysTick     System Tick Timer (SysTick)
+    \brief      Type definitions for the System Timer Registers.
+  @{
+ */
+
+/** \brief  Structure type to access the System Timer (SysTick).
+ */
+typedef struct
+{
+  __IO uint32_t CTRL;                    /*!< Offset: 0x000 (R/W)  SysTick Control and Status Register */
+  __IO uint32_t LOAD;                    /*!< Offset: 0x004 (R/W)  SysTick Reload Value Register       */
+  __IO uint32_t VAL;                     /*!< Offset: 0x008 (R/W)  SysTick Current Value Register      */
+  __I  uint32_t CALIB;                   /*!< Offset: 0x00C (R/ )  SysTick Calibration Register        */
+} SysTick_Type;
+
+/* SysTick Control / Status Register Definitions */
+#define SysTick_CTRL_COUNTFLAG_Pos         16                                             /*!< SysTick CTRL: COUNTFLAG Position */
+#define SysTick_CTRL_COUNTFLAG_Msk         (1UL << SysTick_CTRL_COUNTFLAG_Pos)            /*!< SysTick CTRL: COUNTFLAG Mask */
+
+#define SysTick_CTRL_CLKSOURCE_Pos          2                                             /*!< SysTick CTRL: CLKSOURCE Position */
+#define SysTick_CTRL_CLKSOURCE_Msk         (1UL << SysTick_CTRL_CLKSOURCE_Pos)            /*!< SysTick CTRL: CLKSOURCE Mask */
+
+#define SysTick_CTRL_TICKINT_Pos            1                                             /*!< SysTick CTRL: TICKINT Position */
+#define SysTick_CTRL_TICKINT_Msk           (1UL << SysTick_CTRL_TICKINT_Pos)              /*!< SysTick CTRL: TICKINT Mask */
+
+#define SysTick_CTRL_ENABLE_Pos             0                                             /*!< SysTick CTRL: ENABLE Position */
+#define SysTick_CTRL_ENABLE_Msk            (1UL << SysTick_CTRL_ENABLE_Pos)               /*!< SysTick CTRL: ENABLE Mask */
+
+/* SysTick Reload Register Definitions */
+#define SysTick_LOAD_RELOAD_Pos             0                                             /*!< SysTick LOAD: RELOAD Position */
+#define SysTick_LOAD_RELOAD_Msk            (0xFFFFFFUL << SysTick_LOAD_RELOAD_Pos)        /*!< SysTick LOAD: RELOAD Mask */
+
+/* SysTick Current Register Definitions */
+#define SysTick_VAL_CURRENT_Pos             0                                             /*!< SysTick VAL: CURRENT Position */
+#define SysTick_VAL_CURRENT_Msk            (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos)        /*!< SysTick VAL: CURRENT Mask */
+
+/* SysTick Calibration Register Definitions */
+#define SysTick_CALIB_NOREF_Pos            31                                             /*!< SysTick CALIB: NOREF Position */
+#define SysTick_CALIB_NOREF_Msk            (1UL << SysTick_CALIB_NOREF_Pos)               /*!< SysTick CALIB: NOREF Mask */
+
+#define SysTick_CALIB_SKEW_Pos             30                                             /*!< SysTick CALIB: SKEW Position */
+#define SysTick_CALIB_SKEW_Msk             (1UL << SysTick_CALIB_SKEW_Pos)                /*!< SysTick CALIB: SKEW Mask */
+
+#define SysTick_CALIB_TENMS_Pos             0                                             /*!< SysTick CALIB: TENMS Position */
+#define SysTick_CALIB_TENMS_Msk            (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos)        /*!< SysTick CALIB: TENMS Mask */
+
+/*@} end of group CMSIS_SysTick */
+
+
+/** \ingroup  CMSIS_core_register
+    \defgroup CMSIS_CoreDebug       Core Debug Registers (CoreDebug)
+    \brief      Cortex-M0 Core Debug Registers (DCB registers, SHCSR, and DFSR)
+                are only accessible over DAP and not via processor. Therefore
+                they are not covered by the Cortex-M0 header file.
+  @{
+ */
+/*@} end of group CMSIS_CoreDebug */
+
+
+/** \ingroup    CMSIS_core_register
+    \defgroup   CMSIS_core_base     Core Definitions
+    \brief      Definitions for base addresses, unions, and structures.
+  @{
+ */
+
+/* Memory mapping of Cortex-M0 Hardware */
+#define SCS_BASE            (0xE000E000UL)                            /*!< System Control Space Base Address */
+#define SysTick_BASE        (SCS_BASE +  0x0010UL)                    /*!< SysTick Base Address              */
+#define NVIC_BASE           (SCS_BASE +  0x0100UL)                    /*!< NVIC Base Address                 */
+#define SCB_BASE            (SCS_BASE +  0x0D00UL)                    /*!< System Control Block Base Address */
+
+#define SCB                 ((SCB_Type       *)     SCB_BASE      )   /*!< SCB configuration struct           */
+#define SysTick             ((SysTick_Type   *)     SysTick_BASE  )   /*!< SysTick configuration struct       */
+#define NVIC                ((NVIC_Type      *)     NVIC_BASE     )   /*!< NVIC configuration struct          */
+
+
+/*@} */
+
+
+
+/*******************************************************************************
+ *                Hardware Abstraction Layer
+  Core Function Interface contains:
+  - Core NVIC Functions
+  - Core SysTick Functions
+  - Core Register Access Functions
+ ******************************************************************************/
+/** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference
+*/
+
+
+
+/* ##########################   NVIC functions  #################################### */
+/** \ingroup  CMSIS_Core_FunctionInterface
+    \defgroup CMSIS_Core_NVICFunctions NVIC Functions
+    \brief      Functions that manage interrupts and exceptions via the NVIC.
+    @{
+ */
+
+/* Interrupt Priorities are WORD accessible only under ARMv6M                   */
+/* The following MACROS handle generation of the register offset and byte masks */
+#define _BIT_SHIFT(IRQn)         (  (((uint32_t)(IRQn)       )    &  0x03) * 8 )
+#define _SHP_IDX(IRQn)           ( ((((uint32_t)(IRQn) & 0x0F)-8) >>    2)     )
+#define _IP_IDX(IRQn)            (   ((uint32_t)(IRQn)            >>    2)     )
+
+
+/** \brief  Enable External Interrupt
+
+    The function enables a device-specific interrupt in the NVIC interrupt controller.
+
+    \param [in]      IRQn  External interrupt number. Value cannot be negative.
+ */
+__STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn)
+{
+  NVIC->ISER[0] = (1 << ((uint32_t)(IRQn) & 0x1F));
+}
+
+
+/** \brief  Disable External Interrupt
+
+    The function disables a device-specific interrupt in the NVIC interrupt controller.
+
+    \param [in]      IRQn  External interrupt number. Value cannot be negative.
+ */
+__STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn)
+{
+  NVIC->ICER[0] = (1 << ((uint32_t)(IRQn) & 0x1F));
+}
+
+
+/** \brief  Get Pending Interrupt
+
+    The function reads the pending register in the NVIC and returns the pending bit
+    for the specified interrupt.
+
+    \param [in]      IRQn  Interrupt number.
+
+    \return             0  Interrupt status is not pending.
+    \return             1  Interrupt status is pending.
+ */
+__STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn)
+{
+  return((uint32_t) ((NVIC->ISPR[0] & (1 << ((uint32_t)(IRQn) & 0x1F)))?1:0));
+}
+
+
+/** \brief  Set Pending Interrupt
+
+    The function sets the pending bit of an external interrupt.
+
+    \param [in]      IRQn  Interrupt number. Value cannot be negative.
+ */
+__STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn)
+{
+  NVIC->ISPR[0] = (1 << ((uint32_t)(IRQn) & 0x1F));
+}
+
+
+/** \brief  Clear Pending Interrupt
+
+    The function clears the pending bit of an external interrupt.
+
+    \param [in]      IRQn  External interrupt number. Value cannot be negative.
+ */
+__STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn)
+{
+  NVIC->ICPR[0] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* Clear pending interrupt */
+}
+
+
+/** \brief  Set Interrupt Priority
+
+    The function sets the priority of an interrupt.
+
+    \note The priority cannot be set for every core interrupt.
+
+    \param [in]      IRQn  Interrupt number.
+    \param [in]  priority  Priority to set.
+ */
+__STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority)
+{
+  if(IRQn < 0) {
+    SCB->SHP[_SHP_IDX(IRQn)] = (SCB->SHP[_SHP_IDX(IRQn)] & ~(0xFF << _BIT_SHIFT(IRQn))) |
+        (((priority << (8 - __NVIC_PRIO_BITS)) & 0xFF) << _BIT_SHIFT(IRQn)); }
+  else {
+    NVIC->IP[_IP_IDX(IRQn)] = (NVIC->IP[_IP_IDX(IRQn)] & ~(0xFF << _BIT_SHIFT(IRQn))) |
+        (((priority << (8 - __NVIC_PRIO_BITS)) & 0xFF) << _BIT_SHIFT(IRQn)); }
+}
+
+
+/** \brief  Get Interrupt Priority
+
+    The function reads the priority of an interrupt. The interrupt
+    number can be positive to specify an external (device specific)
+    interrupt, or negative to specify an internal (core) interrupt.
+
+
+    \param [in]   IRQn  Interrupt number.
+    \return             Interrupt Priority. Value is aligned automatically to the implemented
+                        priority bits of the microcontroller.
+ */
+__STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn)
+{
+
+  if(IRQn < 0) {
+    return((uint32_t)(((SCB->SHP[_SHP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & 0xFF) >> (8 - __NVIC_PRIO_BITS)));  } /* get priority for Cortex-M0 system interrupts */
+  else {
+    return((uint32_t)(((NVIC->IP[ _IP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & 0xFF) >> (8 - __NVIC_PRIO_BITS)));  } /* get priority for device specific interrupts  */
+}
+
+
+/** \brief  System Reset
+
+    The function initiates a system reset request to reset the MCU.
+ */
+__STATIC_INLINE void NVIC_SystemReset(void)
+{
+  __DSB();                                                     /* Ensure all outstanding memory accesses included
+                                                                  buffered write are completed before reset */
+  SCB->AIRCR  = ((0x5FA << SCB_AIRCR_VECTKEY_Pos)      |
+                 SCB_AIRCR_SYSRESETREQ_Msk);
+  __DSB();                                                     /* Ensure completion of memory access */
+  while(1);                                                    /* wait until reset */
+}
+
+/*@} end of CMSIS_Core_NVICFunctions */
+
+
+
+/* ##################################    SysTick function  ############################################ */
+/** \ingroup  CMSIS_Core_FunctionInterface
+    \defgroup CMSIS_Core_SysTickFunctions SysTick Functions
+    \brief      Functions that configure the System.
+  @{
+ */
+
+#if (__Vendor_SysTickConfig == 0)
+
+/** \brief  System Tick Configuration
+
+    The function initializes the System Timer and its interrupt, and starts the System Tick Timer.
+    Counter is in free running mode to generate periodic interrupts.
+
+    \param [in]  ticks  Number of ticks between two interrupts.
+
+    \return          0  Function succeeded.
+    \return          1  Function failed.
+
+    \note     When the variable <b>__Vendor_SysTickConfig</b> is set to 1, then the
+    function <b>SysTick_Config</b> is not included. In this case, the file <b><i>device</i>.h</b>
+    must contain a vendor-specific implementation of this function.
+
+ */
+__STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks)
+{
+  if ((ticks - 1) > SysTick_LOAD_RELOAD_Msk)  return (1);      /* Reload value impossible */
+
+  SysTick->LOAD  = ticks - 1;                                  /* set reload register */
+  NVIC_SetPriority (SysTick_IRQn, (1<<__NVIC_PRIO_BITS) - 1);  /* set Priority for Systick Interrupt */
+  SysTick->VAL   = 0;                                          /* Load the SysTick Counter Value */
+  SysTick->CTRL  = SysTick_CTRL_CLKSOURCE_Msk |
+                   SysTick_CTRL_TICKINT_Msk   |
+                   SysTick_CTRL_ENABLE_Msk;                    /* Enable SysTick IRQ and SysTick Timer */
+  return (0);                                                  /* Function successful */
+}
+
+#endif
+
+/*@} end of CMSIS_Core_SysTickFunctions */
+
+
+
+
+#endif /* __CORE_CM0_H_DEPENDANT */
+
+#endif /* __CMSIS_GENERIC */
+
+#ifdef __cplusplus
+}
+#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/hw/cmsis-core/src/ext/core_cm0plus.h
----------------------------------------------------------------------
diff --git a/hw/cmsis-core/src/ext/core_cm0plus.h b/hw/cmsis-core/src/ext/core_cm0plus.h
new file mode 100644
index 0000000..5cea74e
--- /dev/null
+++ b/hw/cmsis-core/src/ext/core_cm0plus.h
@@ -0,0 +1,793 @@
+/**************************************************************************//**
+ * @file     core_cm0plus.h
+ * @brief    CMSIS Cortex-M0+ Core Peripheral Access Layer Header File
+ * @version  V3.20
+ * @date     25. February 2013
+ *
+ * @note
+ *
+ ******************************************************************************/
+/* Copyright (c) 2009 - 2013 ARM LIMITED
+
+   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 ARM 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 COPYRIGHT HOLDERS AND CONTRIBUTORS BE
+   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+   POSSIBILITY OF SUCH DAMAGE.
+   ---------------------------------------------------------------------------*/
+
+
+#if defined ( __ICCARM__ )
+ #pragma system_include  /* treat file as system include file for MISRA check */
+#endif
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+#ifndef __CORE_CM0PLUS_H_GENERIC
+#define __CORE_CM0PLUS_H_GENERIC
+
+/** \page CMSIS_MISRA_Exceptions  MISRA-C:2004 Compliance Exceptions
+  CMSIS violates the following MISRA-C:2004 rules:
+
+   \li Required Rule 8.5, object/function definition in header file.<br>
+     Function definitions in header files are used to allow 'inlining'.
+
+   \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.<br>
+     Unions are used for effective representation of core registers.
+
+   \li Advisory Rule 19.7, Function-like macro defined.<br>
+     Function-like macros are used to allow more efficient code.
+ */
+
+
+/*******************************************************************************
+ *                 CMSIS definitions
+ ******************************************************************************/
+/** \ingroup Cortex-M0+
+  @{
+ */
+
+/*  CMSIS CM0P definitions */
+#define __CM0PLUS_CMSIS_VERSION_MAIN (0x03)                                /*!< [31:16] CMSIS HAL main version   */
+#define __CM0PLUS_CMSIS_VERSION_SUB  (0x20)                                /*!< [15:0]  CMSIS HAL sub version    */
+#define __CM0PLUS_CMSIS_VERSION      ((__CM0PLUS_CMSIS_VERSION_MAIN << 16) | \
+                                       __CM0PLUS_CMSIS_VERSION_SUB)        /*!< CMSIS HAL version number         */
+
+#define __CORTEX_M                (0x00)                                   /*!< Cortex-M Core                    */
+
+
+#if   defined ( __CC_ARM )
+  #define __ASM            __asm                                      /*!< asm keyword for ARM Compiler          */
+  #define __INLINE         __inline                                   /*!< inline keyword for ARM Compiler       */
+  #define __STATIC_INLINE  static __inline
+
+#elif defined ( __ICCARM__ )
+  #define __ASM            __asm                                      /*!< asm keyword for IAR Compiler          */
+  #define __INLINE         inline                                     /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */
+  #define __STATIC_INLINE  static inline
+
+#elif defined ( __GNUC__ )
+  #define __ASM            __asm                                      /*!< asm keyword for GNU Compiler          */
+  #define __INLINE         inline                                     /*!< inline keyword for GNU Compiler       */
+  #define __STATIC_INLINE  static inline
+
+#elif defined ( __TASKING__ )
+  #define __ASM            __asm                                      /*!< asm keyword for TASKING Compiler      */
+  #define __INLINE         inline                                     /*!< inline keyword for TASKING Compiler   */
+  #define __STATIC_INLINE  static inline
+
+#endif
+
+/** __FPU_USED indicates whether an FPU is used or not. This core does not support an FPU at all
+*/
+#define __FPU_USED       0
+
+#if defined ( __CC_ARM )
+  #if defined __TARGET_FPU_VFP
+    #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
+  #endif
+
+#elif defined ( __ICCARM__ )
+  #if defined __ARMVFP__
+    #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
+  #endif
+
+#elif defined ( __GNUC__ )
+  #if defined (__VFP_FP__) && !defined(__SOFTFP__)
+    #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
+  #endif
+
+#elif defined ( __TASKING__ )
+  #if defined __FPU_VFP__
+    #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
+  #endif
+#endif
+
+#include <stdint.h>                      /* standard types definitions                      */
+#include <core_cmInstr.h>                /* Core Instruction Access                         */
+#include <core_cmFunc.h>                 /* Core Function Access                            */
+
+#endif /* __CORE_CM0PLUS_H_GENERIC */
+
+#ifndef __CMSIS_GENERIC
+
+#ifndef __CORE_CM0PLUS_H_DEPENDANT
+#define __CORE_CM0PLUS_H_DEPENDANT
+
+/* check device defines and use defaults */
+#if defined __CHECK_DEVICE_DEFINES
+  #ifndef __CM0PLUS_REV
+    #define __CM0PLUS_REV             0x0000
+    #warning "__CM0PLUS_REV not defined in device header file; using default!"
+  #endif
+
+  #ifndef __MPU_PRESENT
+    #define __MPU_PRESENT             0
+    #warning "__MPU_PRESENT not defined in device header file; using default!"
+  #endif
+
+  #ifndef __VTOR_PRESENT
+    #define __VTOR_PRESENT            0
+    #warning "__VTOR_PRESENT not defined in device header file; using default!"
+  #endif
+
+  #ifndef __NVIC_PRIO_BITS
+    #define __NVIC_PRIO_BITS          2
+    #warning "__NVIC_PRIO_BITS not defined in device header file; using default!"
+  #endif
+
+  #ifndef __Vendor_SysTickConfig
+    #define __Vendor_SysTickConfig    0
+    #warning "__Vendor_SysTickConfig not defined in device header file; using default!"
+  #endif
+#endif
+
+/* IO definitions (access restrictions to peripheral registers) */
+/**
+    \defgroup CMSIS_glob_defs CMSIS Global Defines
+
+    <strong>IO Type Qualifiers</strong> are used
+    \li to specify the access to peripheral variables.
+    \li for automatic generation of peripheral register debug information.
+*/
+#ifdef __cplusplus
+  #define   __I     volatile             /*!< Defines 'read only' permissions                 */
+#else
+  #define   __I     volatile const       /*!< Defines 'read only' permissions                 */
+#endif
+#define     __O     volatile             /*!< Defines 'write only' permissions                */
+#define     __IO    volatile             /*!< Defines 'read / write' permissions              */
+
+/*@} end of group Cortex-M0+ */
+
+
+
+/*******************************************************************************
+ *                 Register Abstraction
+  Core Register contain:
+  - Core Register
+  - Core NVIC Register
+  - Core SCB Register
+  - Core SysTick Register
+  - Core MPU Register
+ ******************************************************************************/
+/** \defgroup CMSIS_core_register Defines and Type Definitions
+    \brief Type definitions and defines for Cortex-M processor based devices.
+*/
+
+/** \ingroup    CMSIS_core_register
+    \defgroup   CMSIS_CORE  Status and Control Registers
+    \brief  Core Register type definitions.
+  @{
+ */
+
+/** \brief  Union type to access the Application Program Status Register (APSR).
+ */
+typedef union
+{
+  struct
+  {
+#if (__CORTEX_M != 0x04)
+    uint32_t _reserved0:27;              /*!< bit:  0..26  Reserved                           */
+#else
+    uint32_t _reserved0:16;              /*!< bit:  0..15  Reserved                           */
+    uint32_t GE:4;                       /*!< bit: 16..19  Greater than or Equal flags        */
+    uint32_t _reserved1:7;               /*!< bit: 20..26  Reserved                           */
+#endif
+    uint32_t Q:1;                        /*!< bit:     27  Saturation condition flag          */
+    uint32_t V:1;                        /*!< bit:     28  Overflow condition code flag       */
+    uint32_t C:1;                        /*!< bit:     29  Carry condition code flag          */
+    uint32_t Z:1;                        /*!< bit:     30  Zero condition code flag           */
+    uint32_t N:1;                        /*!< bit:     31  Negative condition code flag       */
+  } b;                                   /*!< Structure used for bit  access                  */
+  uint32_t w;                            /*!< Type      used for word access                  */
+} APSR_Type;
+
+
+/** \brief  Union type to access the Interrupt Program Status Register (IPSR).
+ */
+typedef union
+{
+  struct
+  {
+    uint32_t ISR:9;                      /*!< bit:  0.. 8  Exception number                   */
+    uint32_t _reserved0:23;              /*!< bit:  9..31  Reserved                           */
+  } b;                                   /*!< Structure used for bit  access                  */
+  uint32_t w;                            /*!< Type      used for word access                  */
+} IPSR_Type;
+
+
+/** \brief  Union type to access the Special-Purpose Program Status Registers (xPSR).
+ */
+typedef union
+{
+  struct
+  {
+    uint32_t ISR:9;                      /*!< bit:  0.. 8  Exception number                   */
+#if (__CORTEX_M != 0x04)
+    uint32_t _reserved0:15;              /*!< bit:  9..23  Reserved                           */
+#else
+    uint32_t _reserved0:7;               /*!< bit:  9..15  Reserved                           */
+    uint32_t GE:4;                       /*!< bit: 16..19  Greater than or Equal flags        */
+    uint32_t _reserved1:4;               /*!< bit: 20..23  Reserved                           */
+#endif
+    uint32_t T:1;                        /*!< bit:     24  Thumb bit        (read 0)          */
+    uint32_t IT:2;                       /*!< bit: 25..26  saved IT state   (read 0)          */
+    uint32_t Q:1;                        /*!< bit:     27  Saturation condition flag          */
+    uint32_t V:1;                        /*!< bit:     28  Overflow condition code flag       */
+    uint32_t C:1;                        /*!< bit:     29  Carry condition code flag          */
+    uint32_t Z:1;                        /*!< bit:     30  Zero condition code flag           */
+    uint32_t N:1;                        /*!< bit:     31  Negative condition code flag       */
+  } b;                                   /*!< Structure used for bit  access                  */
+  uint32_t w;                            /*!< Type      used for word access                  */
+} xPSR_Type;
+
+
+/** \brief  Union type to access the Control Registers (CONTROL).
+ */
+typedef union
+{
+  struct
+  {
+    uint32_t nPRIV:1;                    /*!< bit:      0  Execution privilege in Thread mode */
+    uint32_t SPSEL:1;                    /*!< bit:      1  Stack to be used                   */
+    uint32_t FPCA:1;                     /*!< bit:      2  FP extension active flag           */
+    uint32_t _reserved0:29;              /*!< bit:  3..31  Reserved                           */
+  } b;                                   /*!< Structure used for bit  access                  */
+  uint32_t w;                            /*!< Type      used for word access                  */
+} CONTROL_Type;
+
+/*@} end of group CMSIS_CORE */
+
+
+/** \ingroup    CMSIS_core_register
+    \defgroup   CMSIS_NVIC  Nested Vectored Interrupt Controller (NVIC)
+    \brief      Type definitions for the NVIC Registers
+  @{
+ */
+
+/** \brief  Structure type to access the Nested Vectored Interrupt Controller (NVIC).
+ */
+typedef struct
+{
+  __IO uint32_t ISER[1];                 /*!< Offset: 0x000 (R/W)  Interrupt Set Enable Register           */
+       uint32_t RESERVED0[31];
+  __IO uint32_t ICER[1];                 /*!< Offset: 0x080 (R/W)  Interrupt Clear Enable Register          */
+       uint32_t RSERVED1[31];
+  __IO uint32_t ISPR[1];                 /*!< Offset: 0x100 (R/W)  Interrupt Set Pending Register           */
+       uint32_t RESERVED2[31];
+  __IO uint32_t ICPR[1];                 /*!< Offset: 0x180 (R/W)  Interrupt Clear Pending Register         */
+       uint32_t RESERVED3[31];
+       uint32_t RESERVED4[64];
+  __IO uint32_t IP[8];                   /*!< Offset: 0x300 (R/W)  Interrupt Priority Register              */
+}  NVIC_Type;
+
+/*@} end of group CMSIS_NVIC */
+
+
+/** \ingroup  CMSIS_core_register
+    \defgroup CMSIS_SCB     System Control Block (SCB)
+    \brief      Type definitions for the System Control Block Registers
+  @{
+ */
+
+/** \brief  Structure type to access the System Control Block (SCB).
+ */
+typedef struct
+{
+  __I  uint32_t CPUID;                   /*!< Offset: 0x000 (R/ )  CPUID Base Register                                   */
+  __IO uint32_t ICSR;                    /*!< Offset: 0x004 (R/W)  Interrupt Control and State Register                  */
+#if (__VTOR_PRESENT == 1)
+  __IO uint32_t VTOR;                    /*!< Offset: 0x008 (R/W)  Vector Table Offset Register                          */
+#else
+       uint32_t RESERVED0;
+#endif
+  __IO uint32_t AIRCR;                   /*!< Offset: 0x00C (R/W)  Application Interrupt and Reset Control Register      */
+  __IO uint32_t SCR;                     /*!< Offset: 0x010 (R/W)  System Control Register                               */
+  __IO uint32_t CCR;                     /*!< Offset: 0x014 (R/W)  Configuration Control Register                        */
+       uint32_t RESERVED1;
+  __IO uint32_t SHP[2];                  /*!< Offset: 0x01C (R/W)  System Handlers Priority Registers. [0] is RESERVED   */
+  __IO uint32_t SHCSR;                   /*!< Offset: 0x024 (R/W)  System Handler Control and State Register             */
+} SCB_Type;
+
+/* SCB CPUID Register Definitions */
+#define SCB_CPUID_IMPLEMENTER_Pos          24                                             /*!< SCB CPUID: IMPLEMENTER Position */
+#define SCB_CPUID_IMPLEMENTER_Msk          (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos)          /*!< SCB CPUID: IMPLEMENTER Mask */
+
+#define SCB_CPUID_VARIANT_Pos              20                                             /*!< SCB CPUID: VARIANT Position */
+#define SCB_CPUID_VARIANT_Msk              (0xFUL << SCB_CPUID_VARIANT_Pos)               /*!< SCB CPUID: VARIANT Mask */
+
+#define SCB_CPUID_ARCHITECTURE_Pos         16                                             /*!< SCB CPUID: ARCHITECTURE Position */
+#define SCB_CPUID_ARCHITECTURE_Msk         (0xFUL << SCB_CPUID_ARCHITECTURE_Pos)          /*!< SCB CPUID: ARCHITECTURE Mask */
+
+#define SCB_CPUID_PARTNO_Pos                4                                             /*!< SCB CPUID: PARTNO Position */
+#define SCB_CPUID_PARTNO_Msk               (0xFFFUL << SCB_CPUID_PARTNO_Pos)              /*!< SCB CPUID: PARTNO Mask */
+
+#define SCB_CPUID_REVISION_Pos              0                                             /*!< SCB CPUID: REVISION Position */
+#define SCB_CPUID_REVISION_Msk             (0xFUL << SCB_CPUID_REVISION_Pos)              /*!< SCB CPUID: REVISION Mask */
+
+/* SCB Interrupt Control State Register Definitions */
+#define SCB_ICSR_NMIPENDSET_Pos            31                                             /*!< SCB ICSR: NMIPENDSET Position */
+#define SCB_ICSR_NMIPENDSET_Msk            (1UL << SCB_ICSR_NMIPENDSET_Pos)               /*!< SCB ICSR: NMIPENDSET Mask */
+
+#define SCB_ICSR_PENDSVSET_Pos             28                                             /*!< SCB ICSR: PENDSVSET Position */
+#define SCB_ICSR_PENDSVSET_Msk             (1UL << SCB_ICSR_PENDSVSET_Pos)                /*!< SCB ICSR: PENDSVSET Mask */
+
+#define SCB_ICSR_PENDSVCLR_Pos             27                                             /*!< SCB ICSR: PENDSVCLR Position */
+#define SCB_ICSR_PENDSVCLR_Msk             (1UL << SCB_ICSR_PENDSVCLR_Pos)                /*!< SCB ICSR: PENDSVCLR Mask */
+
+#define SCB_ICSR_PENDSTSET_Pos             26                                             /*!< SCB ICSR: PENDSTSET Position */
+#define SCB_ICSR_PENDSTSET_Msk             (1UL << SCB_ICSR_PENDSTSET_Pos)                /*!< SCB ICSR: PENDSTSET Mask */
+
+#define SCB_ICSR_PENDSTCLR_Pos             25                                             /*!< SCB ICSR: PENDSTCLR Position */
+#define SCB_ICSR_PENDSTCLR_Msk             (1UL << SCB_ICSR_PENDSTCLR_Pos)                /*!< SCB ICSR: PENDSTCLR Mask */
+
+#define SCB_ICSR_ISRPREEMPT_Pos            23                                             /*!< SCB ICSR: ISRPREEMPT Position */
+#define SCB_ICSR_ISRPREEMPT_Msk            (1UL << SCB_ICSR_ISRPREEMPT_Pos)               /*!< SCB ICSR: ISRPREEMPT Mask */
+
+#define SCB_ICSR_ISRPENDING_Pos            22                                             /*!< SCB ICSR: ISRPENDING Position */
+#define SCB_ICSR_ISRPENDING_Msk            (1UL << SCB_ICSR_ISRPENDING_Pos)               /*!< SCB ICSR: ISRPENDING Mask */
+
+#define SCB_ICSR_VECTPENDING_Pos           12                                             /*!< SCB ICSR: VECTPENDING Position */
+#define SCB_ICSR_VECTPENDING_Msk           (0x1FFUL << SCB_ICSR_VECTPENDING_Pos)          /*!< SCB ICSR: VECTPENDING Mask */
+
+#define SCB_ICSR_VECTACTIVE_Pos             0                                             /*!< SCB ICSR: VECTACTIVE Position */
+#define SCB_ICSR_VECTACTIVE_Msk            (0x1FFUL << SCB_ICSR_VECTACTIVE_Pos)           /*!< SCB ICSR: VECTACTIVE Mask */
+
+#if (__VTOR_PRESENT == 1)
+/* SCB Interrupt Control State Register Definitions */
+#define SCB_VTOR_TBLOFF_Pos                 8                                             /*!< SCB VTOR: TBLOFF Position */
+#define SCB_VTOR_TBLOFF_Msk                (0xFFFFFFUL << SCB_VTOR_TBLOFF_Pos)            /*!< SCB VTOR: TBLOFF Mask */
+#endif
+
+/* SCB Application Interrupt and Reset Control Register Definitions */
+#define SCB_AIRCR_VECTKEY_Pos              16                                             /*!< SCB AIRCR: VECTKEY Position */
+#define SCB_AIRCR_VECTKEY_Msk              (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos)            /*!< SCB AIRCR: VECTKEY Mask */
+
+#define SCB_AIRCR_VECTKEYSTAT_Pos          16                                             /*!< SCB AIRCR: VECTKEYSTAT Position */
+#define SCB_AIRCR_VECTKEYSTAT_Msk          (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos)        /*!< SCB AIRCR: VECTKEYSTAT Mask */
+
+#define SCB_AIRCR_ENDIANESS_Pos            15                                             /*!< SCB AIRCR: ENDIANESS Position */
+#define SCB_AIRCR_ENDIANESS_Msk            (1UL << SCB_AIRCR_ENDIANESS_Pos)               /*!< SCB AIRCR: ENDIANESS Mask */
+
+#define SCB_AIRCR_SYSRESETREQ_Pos           2                                             /*!< SCB AIRCR: SYSRESETREQ Position */
+#define SCB_AIRCR_SYSRESETREQ_Msk          (1UL << SCB_AIRCR_SYSRESETREQ_Pos)             /*!< SCB AIRCR: SYSRESETREQ Mask */
+
+#define SCB_AIRCR_VECTCLRACTIVE_Pos         1                                             /*!< SCB AIRCR: VECTCLRACTIVE Position */
+#define SCB_AIRCR_VECTCLRACTIVE_Msk        (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos)           /*!< SCB AIRCR: VECTCLRACTIVE Mask */
+
+/* SCB System Control Register Definitions */
+#define SCB_SCR_SEVONPEND_Pos               4                                             /*!< SCB SCR: SEVONPEND Position */
+#define SCB_SCR_SEVONPEND_Msk              (1UL << SCB_SCR_SEVONPEND_Pos)                 /*!< SCB SCR: SEVONPEND Mask */
+
+#define SCB_SCR_SLEEPDEEP_Pos               2                                             /*!< SCB SCR: SLEEPDEEP Position */
+#define SCB_SCR_SLEEPDEEP_Msk              (1UL << SCB_SCR_SLEEPDEEP_Pos)                 /*!< SCB SCR: SLEEPDEEP Mask */
+
+#define SCB_SCR_SLEEPONEXIT_Pos             1                                             /*!< SCB SCR: SLEEPONEXIT Position */
+#define SCB_SCR_SLEEPONEXIT_Msk            (1UL << SCB_SCR_SLEEPONEXIT_Pos)               /*!< SCB SCR: SLEEPONEXIT Mask */
+
+/* SCB Configuration Control Register Definitions */
+#define SCB_CCR_STKALIGN_Pos                9                                             /*!< SCB CCR: STKALIGN Position */
+#define SCB_CCR_STKALIGN_Msk               (1UL << SCB_CCR_STKALIGN_Pos)                  /*!< SCB CCR: STKALIGN Mask */
+
+#define SCB_CCR_UNALIGN_TRP_Pos             3                                             /*!< SCB CCR: UNALIGN_TRP Position */
+#define SCB_CCR_UNALIGN_TRP_Msk            (1UL << SCB_CCR_UNALIGN_TRP_Pos)               /*!< SCB CCR: UNALIGN_TRP Mask */
+
+/* SCB System Handler Control and State Register Definitions */
+#define SCB_SHCSR_SVCALLPENDED_Pos         15                                             /*!< SCB SHCSR: SVCALLPENDED Position */
+#define SCB_SHCSR_SVCALLPENDED_Msk         (1UL << SCB_SHCSR_SVCALLPENDED_Pos)            /*!< SCB SHCSR: SVCALLPENDED Mask */
+
+/*@} end of group CMSIS_SCB */
+
+
+/** \ingroup  CMSIS_core_register
+    \defgroup CMSIS_SysTick     System Tick Timer (SysTick)
+    \brief      Type definitions for the System Timer Registers.
+  @{
+ */
+
+/** \brief  Structure type to access the System Timer (SysTick).
+ */
+typedef struct
+{
+  __IO uint32_t CTRL;                    /*!< Offset: 0x000 (R/W)  SysTick Control and Status Register */
+  __IO uint32_t LOAD;                    /*!< Offset: 0x004 (R/W)  SysTick Reload Value Register       */
+  __IO uint32_t VAL;                     /*!< Offset: 0x008 (R/W)  SysTick Current Value Register      */
+  __I  uint32_t CALIB;                   /*!< Offset: 0x00C (R/ )  SysTick Calibration Register        */
+} SysTick_Type;
+
+/* SysTick Control / Status Register Definitions */
+#define SysTick_CTRL_COUNTFLAG_Pos         16                                             /*!< SysTick CTRL: COUNTFLAG Position */
+#define SysTick_CTRL_COUNTFLAG_Msk         (1UL << SysTick_CTRL_COUNTFLAG_Pos)            /*!< SysTick CTRL: COUNTFLAG Mask */
+
+#define SysTick_CTRL_CLKSOURCE_Pos          2                                             /*!< SysTick CTRL: CLKSOURCE Position */
+#define SysTick_CTRL_CLKSOURCE_Msk         (1UL << SysTick_CTRL_CLKSOURCE_Pos)            /*!< SysTick CTRL: CLKSOURCE Mask */
+
+#define SysTick_CTRL_TICKINT_Pos            1                                             /*!< SysTick CTRL: TICKINT Position */
+#define SysTick_CTRL_TICKINT_Msk           (1UL << SysTick_CTRL_TICKINT_Pos)              /*!< SysTick CTRL: TICKINT Mask */
+
+#define SysTick_CTRL_ENABLE_Pos             0                                             /*!< SysTick CTRL: ENABLE Position */
+#define SysTick_CTRL_ENABLE_Msk            (1UL << SysTick_CTRL_ENABLE_Pos)               /*!< SysTick CTRL: ENABLE Mask */
+
+/* SysTick Reload Register Definitions */
+#define SysTick_LOAD_RELOAD_Pos             0                                             /*!< SysTick LOAD: RELOAD Position */
+#define SysTick_LOAD_RELOAD_Msk            (0xFFFFFFUL << SysTick_LOAD_RELOAD_Pos)        /*!< SysTick LOAD: RELOAD Mask */
+
+/* SysTick Current Register Definitions */
+#define SysTick_VAL_CURRENT_Pos             0                                             /*!< SysTick VAL: CURRENT Position */
+#define SysTick_VAL_CURRENT_Msk            (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos)        /*!< SysTick VAL: CURRENT Mask */
+
+/* SysTick Calibration Register Definitions */
+#define SysTick_CALIB_NOREF_Pos            31                                             /*!< SysTick CALIB: NOREF Position */
+#define SysTick_CALIB_NOREF_Msk            (1UL << SysTick_CALIB_NOREF_Pos)               /*!< SysTick CALIB: NOREF Mask */
+
+#define SysTick_CALIB_SKEW_Pos             30                                             /*!< SysTick CALIB: SKEW Position */
+#define SysTick_CALIB_SKEW_Msk             (1UL << SysTick_CALIB_SKEW_Pos)                /*!< SysTick CALIB: SKEW Mask */
+
+#define SysTick_CALIB_TENMS_Pos             0                                             /*!< SysTick CALIB: TENMS Position */
+#define SysTick_CALIB_TENMS_Msk            (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos)        /*!< SysTick CALIB: TENMS Mask */
+
+/*@} end of group CMSIS_SysTick */
+
+#if (__MPU_PRESENT == 1)
+/** \ingroup  CMSIS_core_register
+    \defgroup CMSIS_MPU     Memory Protection Unit (MPU)
+    \brief      Type definitions for the Memory Protection Unit (MPU)
+  @{
+ */
+
+/** \brief  Structure type to access the Memory Protection Unit (MPU).
+ */
+typedef struct
+{
+  __I  uint32_t TYPE;                    /*!< Offset: 0x000 (R/ )  MPU Type Register                              */
+  __IO uint32_t CTRL;                    /*!< Offset: 0x004 (R/W)  MPU Control Register                           */
+  __IO uint32_t RNR;                     /*!< Offset: 0x008 (R/W)  MPU Region RNRber Register                     */
+  __IO uint32_t RBAR;                    /*!< Offset: 0x00C (R/W)  MPU Region Base Address Register               */
+  __IO uint32_t RASR;                    /*!< Offset: 0x010 (R/W)  MPU Region Attribute and Size Register         */
+} MPU_Type;
+
+/* MPU Type Register */
+#define MPU_TYPE_IREGION_Pos               16                                             /*!< MPU TYPE: IREGION Position */
+#define MPU_TYPE_IREGION_Msk               (0xFFUL << MPU_TYPE_IREGION_Pos)               /*!< MPU TYPE: IREGION Mask */
+
+#define MPU_TYPE_DREGION_Pos                8                                             /*!< MPU TYPE: DREGION Position */
+#define MPU_TYPE_DREGION_Msk               (0xFFUL << MPU_TYPE_DREGION_Pos)               /*!< MPU TYPE: DREGION Mask */
+
+#define MPU_TYPE_SEPARATE_Pos               0                                             /*!< MPU TYPE: SEPARATE Position */
+#define MPU_TYPE_SEPARATE_Msk              (1UL << MPU_TYPE_SEPARATE_Pos)                 /*!< MPU TYPE: SEPARATE Mask */
+
+/* MPU Control Register */
+#define MPU_CTRL_PRIVDEFENA_Pos             2                                             /*!< MPU CTRL: PRIVDEFENA Position */
+#define MPU_CTRL_PRIVDEFENA_Msk            (1UL << MPU_CTRL_PRIVDEFENA_Pos)               /*!< MPU CTRL: PRIVDEFENA Mask */
+
+#define MPU_CTRL_HFNMIENA_Pos               1                                             /*!< MPU CTRL: HFNMIENA Position */
+#define MPU_CTRL_HFNMIENA_Msk              (1UL << MPU_CTRL_HFNMIENA_Pos)                 /*!< MPU CTRL: HFNMIENA Mask */
+
+#define MPU_CTRL_ENABLE_Pos                 0                                             /*!< MPU CTRL: ENABLE Position */
+#define MPU_CTRL_ENABLE_Msk                (1UL << MPU_CTRL_ENABLE_Pos)                   /*!< MPU CTRL: ENABLE Mask */
+
+/* MPU Region Number Register */
+#define MPU_RNR_REGION_Pos                  0                                             /*!< MPU RNR: REGION Position */
+#define MPU_RNR_REGION_Msk                 (0xFFUL << MPU_RNR_REGION_Pos)                 /*!< MPU RNR: REGION Mask */
+
+/* MPU Region Base Address Register */
+#define MPU_RBAR_ADDR_Pos                   8                                             /*!< MPU RBAR: ADDR Position */
+#define MPU_RBAR_ADDR_Msk                  (0xFFFFFFUL << MPU_RBAR_ADDR_Pos)              /*!< MPU RBAR: ADDR Mask */
+
+#define MPU_RBAR_VALID_Pos                  4                                             /*!< MPU RBAR: VALID Position */
+#define MPU_RBAR_VALID_Msk                 (1UL << MPU_RBAR_VALID_Pos)                    /*!< MPU RBAR: VALID Mask */
+
+#define MPU_RBAR_REGION_Pos                 0                                             /*!< MPU RBAR: REGION Position */
+#define MPU_RBAR_REGION_Msk                (0xFUL << MPU_RBAR_REGION_Pos)                 /*!< MPU RBAR: REGION Mask */
+
+/* MPU Region Attribute and Size Register */
+#define MPU_RASR_ATTRS_Pos                 16                                             /*!< MPU RASR: MPU Region Attribute field Position */
+#define MPU_RASR_ATTRS_Msk                 (0xFFFFUL << MPU_RASR_ATTRS_Pos)               /*!< MPU RASR: MPU Region Attribute field Mask */
+
+#define MPU_RASR_XN_Pos                    28                                             /*!< MPU RASR: ATTRS.XN Position */
+#define MPU_RASR_XN_Msk                    (1UL << MPU_RASR_XN_Pos)                       /*!< MPU RASR: ATTRS.XN Mask */
+
+#define MPU_RASR_AP_Pos                    24                                             /*!< MPU RASR: ATTRS.AP Position */
+#define MPU_RASR_AP_Msk                    (0x7UL << MPU_RASR_AP_Pos)                     /*!< MPU RASR: ATTRS.AP Mask */
+
+#define MPU_RASR_TEX_Pos                   19                                             /*!< MPU RASR: ATTRS.TEX Position */
+#define MPU_RASR_TEX_Msk                   (0x7UL << MPU_RASR_TEX_Pos)                    /*!< MPU RASR: ATTRS.TEX Mask */
+
+#define MPU_RASR_S_Pos                     18                                             /*!< MPU RASR: ATTRS.S Position */
+#define MPU_RASR_S_Msk                     (1UL << MPU_RASR_S_Pos)                        /*!< MPU RASR: ATTRS.S Mask */
+
+#define MPU_RASR_C_Pos                     17                                             /*!< MPU RASR: ATTRS.C Position */
+#define MPU_RASR_C_Msk                     (1UL << MPU_RASR_C_Pos)                        /*!< MPU RASR: ATTRS.C Mask */
+
+#define MPU_RASR_B_Pos                     16                                             /*!< MPU RASR: ATTRS.B Position */
+#define MPU_RASR_B_Msk                     (1UL << MPU_RASR_B_Pos)                        /*!< MPU RASR: ATTRS.B Mask */
+
+#define MPU_RASR_SRD_Pos                    8                                             /*!< MPU RASR: Sub-Region Disable Position */
+#define MPU_RASR_SRD_Msk                   (0xFFUL << MPU_RASR_SRD_Pos)                   /*!< MPU RASR: Sub-Region Disable Mask */
+
+#define MPU_RASR_SIZE_Pos                   1                                             /*!< MPU RASR: Region Size Field Position */
+#define MPU_RASR_SIZE_Msk                  (0x1FUL << MPU_RASR_SIZE_Pos)                  /*!< MPU RASR: Region Size Field Mask */
+
+#define MPU_RASR_ENABLE_Pos                 0                                             /*!< MPU RASR: Region enable bit Position */
+#define MPU_RASR_ENABLE_Msk                (1UL << MPU_RASR_ENABLE_Pos)                   /*!< MPU RASR: Region enable bit Disable Mask */
+
+/*@} end of group CMSIS_MPU */
+#endif
+
+
+/** \ingroup  CMSIS_core_register
+    \defgroup CMSIS_CoreDebug       Core Debug Registers (CoreDebug)
+    \brief      Cortex-M0+ Core Debug Registers (DCB registers, SHCSR, and DFSR)
+                are only accessible over DAP and not via processor. Therefore
+                they are not covered by the Cortex-M0 header file.
+  @{
+ */
+/*@} end of group CMSIS_CoreDebug */
+
+
+/** \ingroup    CMSIS_core_register
+    \defgroup   CMSIS_core_base     Core Definitions
+    \brief      Definitions for base addresses, unions, and structures.
+  @{
+ */
+
+/* Memory mapping of Cortex-M0+ Hardware */
+#define SCS_BASE            (0xE000E000UL)                            /*!< System Control Space Base Address */
+#define SysTick_BASE        (SCS_BASE +  0x0010UL)                    /*!< SysTick Base Address              */
+#define NVIC_BASE           (SCS_BASE +  0x0100UL)                    /*!< NVIC Base Address                 */
+#define SCB_BASE            (SCS_BASE +  0x0D00UL)                    /*!< System Control Block Base Address */
+
+#define SCB                 ((SCB_Type       *)     SCB_BASE      )   /*!< SCB configuration struct           */
+#define SysTick             ((SysTick_Type   *)     SysTick_BASE  )   /*!< SysTick configuration struct       */
+#define NVIC                ((NVIC_Type      *)     NVIC_BASE     )   /*!< NVIC configuration struct          */
+
+#if (__MPU_PRESENT == 1)
+  #define MPU_BASE          (SCS_BASE +  0x0D90UL)                    /*!< Memory Protection Unit             */
+  #define MPU               ((MPU_Type       *)     MPU_BASE      )   /*!< Memory Protection Unit             */
+#endif
+
+/*@} */
+
+
+
+/*******************************************************************************
+ *                Hardware Abstraction Layer
+  Core Function Interface contains:
+  - Core NVIC Functions
+  - Core SysTick Functions
+  - Core Register Access Functions
+ ******************************************************************************/
+/** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference
+*/
+
+
+
+/* ##########################   NVIC functions  #################################### */
+/** \ingroup  CMSIS_Core_FunctionInterface
+    \defgroup CMSIS_Core_NVICFunctions NVIC Functions
+    \brief      Functions that manage interrupts and exceptions via the NVIC.
+    @{
+ */
+
+/* Interrupt Priorities are WORD accessible only under ARMv6M                   */
+/* The following MACROS handle generation of the register offset and byte masks */
+#define _BIT_SHIFT(IRQn)         (  (((uint32_t)(IRQn)       )    &  0x03) * 8 )
+#define _SHP_IDX(IRQn)           ( ((((uint32_t)(IRQn) & 0x0F)-8) >>    2)     )
+#define _IP_IDX(IRQn)            (   ((uint32_t)(IRQn)            >>    2)     )
+
+
+/** \brief  Enable External Interrupt
+
+    The function enables a device-specific interrupt in the NVIC interrupt controller.
+
+    \param [in]      IRQn  External interrupt number. Value cannot be negative.
+ */
+__STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn)
+{
+  NVIC->ISER[0] = (1 << ((uint32_t)(IRQn) & 0x1F));
+}
+
+
+/** \brief  Disable External Interrupt
+
+    The function disables a device-specific interrupt in the NVIC interrupt controller.
+
+    \param [in]      IRQn  External interrupt number. Value cannot be negative.
+ */
+__STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn)
+{
+  NVIC->ICER[0] = (1 << ((uint32_t)(IRQn) & 0x1F));
+}
+
+
+/** \brief  Get Pending Interrupt
+
+    The function reads the pending register in the NVIC and returns the pending bit
+    for the specified interrupt.
+
+    \param [in]      IRQn  Interrupt number.
+
+    \return             0  Interrupt status is not pending.
+    \return             1  Interrupt status is pending.
+ */
+__STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn)
+{
+  return((uint32_t) ((NVIC->ISPR[0] & (1 << ((uint32_t)(IRQn) & 0x1F)))?1:0));
+}
+
+
+/** \brief  Set Pending Interrupt
+
+    The function sets the pending bit of an external interrupt.
+
+    \param [in]      IRQn  Interrupt number. Value cannot be negative.
+ */
+__STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn)
+{
+  NVIC->ISPR[0] = (1 << ((uint32_t)(IRQn) & 0x1F));
+}
+
+
+/** \brief  Clear Pending Interrupt
+
+    The function clears the pending bit of an external interrupt.
+
+    \param [in]      IRQn  External interrupt number. Value cannot be negative.
+ */
+__STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn)
+{
+  NVIC->ICPR[0] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* Clear pending interrupt */
+}
+
+
+/** \brief  Set Interrupt Priority
+
+    The function sets the priority of an interrupt.
+
+    \note The priority cannot be set for every core interrupt.
+
+    \param [in]      IRQn  Interrupt number.
+    \param [in]  priority  Priority to set.
+ */
+__STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority)
+{
+  if(IRQn < 0) {
+    SCB->SHP[_SHP_IDX(IRQn)] = (SCB->SHP[_SHP_IDX(IRQn)] & ~(0xFF << _BIT_SHIFT(IRQn))) |
+        (((priority << (8 - __NVIC_PRIO_BITS)) & 0xFF) << _BIT_SHIFT(IRQn)); }
+  else {
+    NVIC->IP[_IP_IDX(IRQn)] = (NVIC->IP[_IP_IDX(IRQn)] & ~(0xFF << _BIT_SHIFT(IRQn))) |
+        (((priority << (8 - __NVIC_PRIO_BITS)) & 0xFF) << _BIT_SHIFT(IRQn)); }
+}
+
+
+/** \brief  Get Interrupt Priority
+
+    The function reads the priority of an interrupt. The interrupt
+    number can be positive to specify an external (device specific)
+    interrupt, or negative to specify an internal (core) interrupt.
+
+
+    \param [in]   IRQn  Interrupt number.
+    \return             Interrupt Priority. Value is aligned automatically to the implemented
+                        priority bits of the microcontroller.
+ */
+__STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn)
+{
+
+  if(IRQn < 0) {
+    return((uint32_t)(((SCB->SHP[_SHP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & 0xFF) >> (8 - __NVIC_PRIO_BITS)));  } /* get priority for Cortex-M0 system interrupts */
+  else {
+    return((uint32_t)(((NVIC->IP[ _IP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & 0xFF) >> (8 - __NVIC_PRIO_BITS)));  } /* get priority for device specific interrupts  */
+}
+
+
+/** \brief  System Reset
+
+    The function initiates a system reset request to reset the MCU.
+ */
+__STATIC_INLINE void NVIC_SystemReset(void)
+{
+  __DSB();                                                     /* Ensure all outstanding memory accesses included
+                                                                  buffered write are completed before reset */
+  SCB->AIRCR  = ((0x5FA << SCB_AIRCR_VECTKEY_Pos)      |
+                 SCB_AIRCR_SYSRESETREQ_Msk);
+  __DSB();                                                     /* Ensure completion of memory access */
+  while(1);                                                    /* wait until reset */
+}
+
+/*@} end of CMSIS_Core_NVICFunctions */
+
+
+
+/* ##################################    SysTick function  ############################################ */
+/** \ingroup  CMSIS_Core_FunctionInterface
+    \defgroup CMSIS_Core_SysTickFunctions SysTick Functions
+    \brief      Functions that configure the System.
+  @{
+ */
+
+#if (__Vendor_SysTickConfig == 0)
+
+/** \brief  System Tick Configuration
+
+    The function initializes the System Timer and its interrupt, and starts the System Tick Timer.
+    Counter is in free running mode to generate periodic interrupts.
+
+    \param [in]  ticks  Number of ticks between two interrupts.
+
+    \return          0  Function succeeded.
+    \return          1  Function failed.
+
+    \note     When the variable <b>__Vendor_SysTickConfig</b> is set to 1, then the
+    function <b>SysTick_Config</b> is not included. In this case, the file <b><i>device</i>.h</b>
+    must contain a vendor-specific implementation of this function.
+
+ */
+__STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks)
+{
+  if ((ticks - 1) > SysTick_LOAD_RELOAD_Msk)  return (1);      /* Reload value impossible */
+
+  SysTick->LOAD  = ticks - 1;                                  /* set reload register */
+  NVIC_SetPriority (SysTick_IRQn, (1<<__NVIC_PRIO_BITS) - 1);  /* set Priority for Systick Interrupt */
+  SysTick->VAL   = 0;                                          /* Load the SysTick Counter Value */
+  SysTick->CTRL  = SysTick_CTRL_CLKSOURCE_Msk |
+                   SysTick_CTRL_TICKINT_Msk   |
+                   SysTick_CTRL_ENABLE_Msk;                    /* Enable SysTick IRQ and SysTick Timer */
+  return (0);                                                  /* Function successful */
+}
+
+#endif
+
+/*@} end of CMSIS_Core_SysTickFunctions */
+
+
+
+
+#endif /* __CORE_CM0PLUS_H_DEPENDANT */
+
+#endif /* __CMSIS_GENERIC */
+
+#ifdef __cplusplus
+}
+#endif


[10/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/testutil/src/case.c
----------------------------------------------------------------------
diff --git a/libs/testutil/src/case.c b/libs/testutil/src/case.c
deleted file mode 100644
index 614b142..0000000
--- a/libs/testutil/src/case.c
+++ /dev/null
@@ -1,255 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include <assert.h>
-#include <stdio.h>
-#include <string.h>
-#include <stdarg.h>
-#include "testutil/testutil.h"
-#include "testutil_priv.h"
-
-jmp_buf tu_case_jb;
-int tu_case_reported;
-int tu_case_failed;
-int tu_case_idx;
-
-const char *tu_case_name;
-tu_post_test_fn_t *tu_case_post_test_cb;
-void *tu_case_post_test_cb_arg;
-
-#define TU_CASE_BUF_SZ      1024
-
-static char tu_case_buf[TU_CASE_BUF_SZ];
-static int tu_case_buf_len;
-
-void
-tu_case_abort(void)
-{
-    tu_case_write_pass_auto();
-    longjmp(tu_case_jb, 1);
-}
-
-static int
-tu_case_vappend_buf(const char *format, va_list ap)
-{
-    char *dst;
-    int maxlen;
-    int rc;
-
-    dst = tu_case_buf + tu_case_buf_len;
-    maxlen = TU_CASE_BUF_SZ - tu_case_buf_len;
-
-    rc = vsnprintf(dst, maxlen, format, ap);
-    tu_case_buf_len += rc;
-    if (tu_case_buf_len >= TU_CASE_BUF_SZ) {
-        tu_case_buf_len = TU_CASE_BUF_SZ - 1;
-        return -1;
-    }
-
-    return 0;
-}
-
-static int
-tu_case_append_buf(const char *format, ...)
-{
-    va_list ap;
-    int rc;
-
-    va_start(ap, format);
-    rc = tu_case_vappend_buf(format, ap);
-    va_end(ap);
-
-    return rc;
-}
-
-static void
-tu_case_set_name(const char *name)
-{
-    tu_case_name = name;
-}
-
-void
-tu_case_init(const char *name)
-{
-    tu_case_reported = 0;
-    tu_case_failed = 0;
-
-    tu_case_set_name(name);
-
-    if (tu_config.tc_case_init_cb != NULL) {
-        tu_config.tc_case_init_cb(tu_config.tc_case_init_arg);
-    }
-}
-
-void
-tu_case_complete(void)
-{
-    tu_case_idx++;
-}
-
-void
-tu_case_post_test(void)
-{
-    if (tu_case_post_test_cb != NULL) {
-        tu_case_post_test_cb(tu_case_post_test_cb_arg);
-    }
-}
-
-static void
-tu_case_write_fail_buf(void)
-{
-    tu_case_reported = 1;
-    tu_case_failed = 1;
-    tu_suite_failed = 1;
-    tu_any_failed = 1;
-
-    if (tu_config.tc_print_results) {
-        printf("[FAIL] %s/%s %s", tu_suite_name, tu_case_name, tu_case_buf);
-        fflush(stdout);
-    }
-
-    if (tu_config.tc_case_fail_cb != NULL) {
-        tu_config.tc_case_fail_cb(tu_case_buf, tu_case_buf_len,
-                                  tu_config.tc_case_fail_arg);
-    }
-}
-
-static void
-tu_case_append_file_info(const char *file, int line)
-{
-    int rc;
-
-    rc = tu_case_append_buf("|%s:%d| ", file, line);
-    assert(rc == 0);
-}
-
-static void
-tu_case_append_assert_msg(const char *expr)
-{
-    int rc;
-
-    rc = tu_case_append_buf("failed assertion: %s", expr);
-    assert(rc == 0);
-}
-
-static void
-tu_case_write_pass_buf(void)
-{
-    if (tu_config.tc_print_results) {
-        printf("[pass] %s/%s\n", tu_suite_name, tu_case_name);
-        if (tu_case_buf_len > 0) {
-            printf("%s", tu_case_buf);
-        }
-        fflush(stdout);
-    }
-
-    tu_case_reported = 1;
-
-    if (tu_config.tc_case_pass_cb != NULL) {
-        tu_config.tc_case_pass_cb(tu_case_buf, tu_case_buf_len,
-                                  tu_config.tc_case_pass_arg);
-    }
-}
-
-static void
-tu_case_append_manual_pass_msg(void)
-{
-    int rc;
-
-    rc = tu_case_append_buf("manual pass");
-    assert(rc == 0);
-}
-
-void
-tu_case_write_pass_auto(void)
-{
-    if (!tu_case_reported) {
-        tu_case_buf_len = 0;
-        tu_case_write_pass_buf();
-    }
-}
-
-void
-tu_case_fail_assert(int fatal, const char *file, int line,
-                    const char *expr, const char *format, ...)
-{
-    va_list ap;
-    int rc;
-
-    if (tu_config.tc_system_assert) {
-        assert(0);
-    }
-
-    tu_case_buf_len = 0;
-
-    tu_case_append_file_info(file, line);
-    tu_case_append_assert_msg(expr);
-
-    if (format != NULL) {
-        rc = tu_case_append_buf("\n");
-        assert(rc == 0);
-
-        va_start(ap, format);
-        rc = tu_case_vappend_buf(format, ap);
-        assert(rc == 0);
-        va_end(ap);
-    }
-
-    rc = tu_case_append_buf("\n");
-    assert(rc == 0);
-
-    tu_case_write_fail_buf();
-
-    if (fatal) {
-        tu_case_abort();
-    }
-}
-
-void
-tu_case_pass_manual(const char *file, int line, const char *format, ...)
-{
-    va_list ap;
-    int rc;
-
-    if (tu_case_reported) {
-        return;
-    }
-
-    tu_case_buf_len = 0;
-
-    tu_case_append_file_info(file, line);
-    tu_case_append_manual_pass_msg();
-
-    if (format != NULL) {
-        rc = tu_case_append_buf("\n");
-        assert(rc == 0);
-
-        va_start(ap, format);
-        rc = tu_case_vappend_buf(format, ap);
-        assert(rc == 0);
-        va_end(ap);
-    }
-
-    rc = tu_case_append_buf("\n");
-    assert(rc == 0);
-
-    tu_case_write_pass_buf();
-
-    tu_case_abort();
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/testutil/src/suite.c
----------------------------------------------------------------------
diff --git a/libs/testutil/src/suite.c b/libs/testutil/src/suite.c
deleted file mode 100644
index 93ca639..0000000
--- a/libs/testutil/src/suite.c
+++ /dev/null
@@ -1,67 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include <assert.h>
-#include "testutil/testutil.h"
-#include "testutil_priv.h"
-
-const char *tu_suite_name = 0;
-int tu_suite_failed = 0;
-
-static void
-tu_suite_set_name(const char *name)
-{
-    tu_suite_name = name;
-}
-
-/**
- * Configures a callback that gets executed at the end of each test case in the
- * current suite.  This is useful when there are some checks that should be
- * performed at the end of each test (e.g., verify no memory leaks).  This
- * callback is cleared when the current suite completes.
- *
- * @param cb                    The callback to execute at the end of each test
- *                                  case.
- * @param cb_arg                An optional argument that gets passed to the
- *                                  callback.
- */
-void
-tu_suite_set_post_test_cb(tu_post_test_fn_t *cb, void *cb_arg)
-{
-    tu_case_post_test_cb = cb;
-    tu_case_post_test_cb_arg = cb_arg;
-}
-
-void
-tu_suite_complete(void)
-{
-    tu_suite_set_post_test_cb(NULL, NULL);
-}
-
-void
-tu_suite_init(const char *name)
-{
-    tu_suite_failed = 0;
-
-    tu_suite_set_name(name);
-
-    if (tu_config.tc_suite_init_cb != NULL) {
-        tu_config.tc_suite_init_cb(tu_config.tc_suite_init_arg);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/testutil/src/testutil.c
----------------------------------------------------------------------
diff --git a/libs/testutil/src/testutil.c b/libs/testutil/src/testutil.c
deleted file mode 100644
index 032a32c..0000000
--- a/libs/testutil/src/testutil.c
+++ /dev/null
@@ -1,50 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include <assert.h>
-#include "os/os.h"
-#include "hal/hal_flash.h"
-#include "testutil/testutil.h"
-#include "testutil_priv.h"
-
-struct tu_config tu_config;
-int tu_any_failed;
-int tu_first_idx;
-
-int
-tu_init(void)
-{
-    os_init();
-
-    return 0;
-}
-
-void
-tu_restart(void)
-{
-    tu_case_write_pass_auto();
-
-    tu_first_idx = tu_case_idx + 1;
-
-    if (tu_config.tc_restart_cb != NULL) {
-        tu_config.tc_restart_cb(tu_config.tc_restart_arg);
-    }
-
-    tu_arch_restart();
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/testutil/src/testutil_priv.h
----------------------------------------------------------------------
diff --git a/libs/testutil/src/testutil_priv.h b/libs/testutil/src/testutil_priv.h
deleted file mode 100644
index 3f8cb2d..0000000
--- a/libs/testutil/src/testutil_priv.h
+++ /dev/null
@@ -1,34 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 H_TESTUTIL_PRIV_
-#define H_TESTUTIL_PRIV_
-
-#include <stddef.h>
-#include <inttypes.h>
-
-#include "testutil/testutil.h"
-
-void tu_arch_restart(void);
-void tu_case_abort(void);
-
-extern tu_post_test_fn_t *tu_case_post_test_cb;
-extern void *tu_case_post_test_cb_arg;
-
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/tinycbor/include/tinycbor/assert_p.h
----------------------------------------------------------------------
diff --git a/libs/tinycbor/include/tinycbor/assert_p.h b/libs/tinycbor/include/tinycbor/assert_p.h
deleted file mode 100644
index 994be06..0000000
--- a/libs/tinycbor/include/tinycbor/assert_p.h
+++ /dev/null
@@ -1,29 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 Intel Corporation
-**
-** Permission is hereby granted, free of charge, to any person obtaining a copy
-** of this software and associated documentation files (the "Software"), to deal
-** in the Software without restriction, including without limitation the rights
-** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-** copies of the Software, and to permit persons to whom the Software is
-** furnished to do so, subject to the following conditions:
-**
-** The above copyright notice and this permission notice shall be included in
-** all copies or substantial portions of the Software.
-**
-** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-** THE SOFTWARE.
-**
-****************************************************************************/
-
-#include <assert.h>
-#ifdef NDEBUG
-#  undef assert
-#  define assert(cond)      do { if (!(cond)) unreachable(); } while (0)
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/tinycbor/include/tinycbor/cbor.h
----------------------------------------------------------------------
diff --git a/libs/tinycbor/include/tinycbor/cbor.h b/libs/tinycbor/include/tinycbor/cbor.h
deleted file mode 100644
index f78e4af..0000000
--- a/libs/tinycbor/include/tinycbor/cbor.h
+++ /dev/null
@@ -1,479 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 Intel Corporation
-**
-** Permission is hereby granted, free of charge, to any person obtaining a copy
-** of this software and associated documentation files (the "Software"), to deal
-** in the Software without restriction, including without limitation the rights
-** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-** copies of the Software, and to permit persons to whom the Software is
-** furnished to do so, subject to the following conditions:
-**
-** The above copyright notice and this permission notice shall be included in
-** all copies or substantial portions of the Software.
-**
-** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-** THE SOFTWARE.
-**
-****************************************************************************/
-
-#ifndef CBOR_H
-#define CBOR_H
-
-#include <assert.h>
-#include <limits.h>
-#include <stddef.h>
-#include <stdint.h>
-#include <string.h>
-#include <stdio.h>
-
-#ifdef __cplusplus
-extern "C" {
-#else
-#include <stdbool.h>
-#endif
-
-#ifndef SIZE_MAX
-/* Some systems fail to define SIZE_MAX in <stdint.h>, even though C99 requires it...
- * Conversion from signed to unsigned is defined in 6.3.1.3 (Signed and unsigned integers) p2,
- * which says: "the value is converted by repeatedly adding or subtracting one more than the
- * maximum value that can be represented in the new type until the value is in the range of the
- * new type."
- * So -1 gets converted to size_t by adding SIZE_MAX + 1, which results in SIZE_MAX.
- */
-#  define SIZE_MAX ((size_t)-1)
-#endif
-
-#ifndef CBOR_API
-#  define CBOR_API
-#endif
-#ifndef CBOR_PRIVATE_API
-#  define CBOR_PRIVATE_API
-#endif
-#ifndef CBOR_INLINE_API
-#  if defined(__cplusplus)
-#    define CBOR_INLINE inline
-#    define CBOR_INLINE_API inline
-#  else
-#    define CBOR_INLINE_API static CBOR_INLINE
-#    if defined(_MSC_VER)
-#      define CBOR_INLINE __inline
-#    elif defined(__GNUC__)
-#      define CBOR_INLINE __inline__
-#    elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
-#      define CBOR_INLINE inline
-#    else
-#      define CBOR_INLINE
-#    endif
-#  endif
-#endif
-
-typedef enum CborType {
-    CborIntegerType     = 0x00,
-    CborByteStringType  = 0x40,
-    CborTextStringType  = 0x60,
-    CborArrayType       = 0x80,
-    CborMapType         = 0xa0,
-    CborTagType         = 0xc0,
-    CborSimpleType      = 0xe0,
-    CborBooleanType     = 0xf5,
-    CborNullType        = 0xf6,
-    CborUndefinedType   = 0xf7,
-    CborHalfFloatType   = 0xf9,
-    CborFloatType       = 0xfa,
-    CborDoubleType      = 0xfb,
-
-    CborInvalidType     = 0xff              /* equivalent to the break byte, so it will never be used */
-} CborType;
-
-typedef uint64_t CborTag;
-typedef enum CborKnownTags {
-    CborDateTimeStringTag          = 0,        /* RFC 3339 format: YYYY-MM-DD hh:mm:ss+zzzz */
-    CborUnixTime_tTag              = 1,
-    CborPositiveBignumTag          = 2,
-    CborNegativeBignumTag          = 3,
-    CborDecimalTag                 = 4,
-    CborBigfloatTag                = 5,
-    CborExpectedBase64urlTag       = 21,
-    CborExpectedBase64Tag          = 22,
-    CborExpectedBase16Tag          = 23,
-    CborUriTag                     = 32,
-    CborBase64urlTag               = 33,
-    CborBase64Tag                  = 34,
-    CborRegularExpressionTag       = 35,
-    CborMimeMessageTag             = 36,       /* RFC 2045-2047 */
-    CborSignatureTag               = 55799
-} CborKnownTags;
-
-/* Error API */
-
-typedef enum CborError {
-    CborNoError = 0,
-
-    /* errors in all modes */
-    CborUnknownError,
-    CborErrorUnknownLength,         /* request for length in array, map, or string with indeterminate length */
-    CborErrorAdvancePastEOF,
-    CborErrorIO,
-
-    /* parser errors streaming errors */
-    CborErrorGarbageAtEnd = 256,
-    CborErrorUnexpectedEOF,
-    CborErrorUnexpectedBreak,
-    CborErrorUnknownType,           /* can only heppen in major type 7 */
-    CborErrorIllegalType,           /* type not allowed here */
-    CborErrorIllegalNumber,
-    CborErrorIllegalSimpleType,     /* types of value less than 32 encoded in two bytes */
-
-    /* parser errors in strict mode parsing only */
-    CborErrorUnknownSimpleType = 512,
-    CborErrorUnknownTag,
-    CborErrorInappropriateTagForType,
-    CborErrorDuplicateObjectKeys,
-    CborErrorInvalidUtf8TextString,
-
-    /* encoder errors */
-    CborErrorTooManyItems = 768,
-    CborErrorTooFewItems,
-
-    /* internal implementation errors */
-    CborErrorDataTooLarge = 1024,
-    CborErrorNestingTooDeep,
-    CborErrorUnsupportedType,
-
-    /* errors in converting to JSON */
-    CborErrorJsonObjectKeyIsAggregate,
-    CborErrorJsonObjectKeyNotString,
-    CborErrorJsonNotImplemented,
-
-    CborErrorOutOfMemory = ~0U / 2 + 1,
-    CborErrorInternalError = ~0U
-} CborError;
-
-CBOR_API const char *cbor_error_string(CborError error);
-
-/* Encoder API */
-struct CborEncoder
-{
-    union {
-        uint8_t *ptr;
-        ptrdiff_t bytes_needed;
-    };
-    const uint8_t *end;
-    size_t added;
-    int flags;
-};
-typedef struct CborEncoder CborEncoder;
-
-static const size_t CborIndefiniteLength = SIZE_MAX;
-
-CBOR_API void cbor_encoder_init(CborEncoder *encoder, uint8_t *buffer, size_t size, int flags);
-CBOR_API CborError cbor_encode_uint(CborEncoder *encoder, uint64_t value);
-CBOR_API CborError cbor_encode_int(CborEncoder *encoder, int64_t value);
-CBOR_API CborError cbor_encode_negative_int(CborEncoder *encoder, uint64_t absolute_value);
-CBOR_API CborError cbor_encode_simple_value(CborEncoder *encoder, uint8_t value);
-CBOR_API CborError cbor_encode_tag(CborEncoder *encoder, CborTag tag);
-CBOR_API CborError cbor_encode_text_string(CborEncoder *encoder, const char *string, size_t length);
-CBOR_INLINE_API CborError cbor_encode_text_stringz(CborEncoder *encoder, const char *string)
-{ return cbor_encode_text_string(encoder, string, strlen(string)); }
-CBOR_API CborError cbor_encode_byte_string(CborEncoder *encoder, const uint8_t *string, size_t length);
-CBOR_API CborError cbor_encode_floating_point(CborEncoder *encoder, CborType fpType, const void *value);
-
-CBOR_INLINE_API CborError cbor_encode_boolean(CborEncoder *encoder, bool value)
-{ return cbor_encode_simple_value(encoder, (int)value - 1 + (CborBooleanType & 0x1f)); }
-CBOR_INLINE_API CborError cbor_encode_null(CborEncoder *encoder)
-{ return cbor_encode_simple_value(encoder, CborNullType & 0x1f); }
-CBOR_INLINE_API CborError cbor_encode_undefined(CborEncoder *encoder)
-{ return cbor_encode_simple_value(encoder, CborUndefinedType & 0x1f); }
-
-CBOR_INLINE_API CborError cbor_encode_half_float(CborEncoder *encoder, const void *value)
-{ return cbor_encode_floating_point(encoder, CborHalfFloatType, value); }
-CBOR_INLINE_API CborError cbor_encode_float(CborEncoder *encoder, float value)
-{ return cbor_encode_floating_point(encoder, CborFloatType, &value); }
-CBOR_INLINE_API CborError cbor_encode_double(CborEncoder *encoder, double value)
-{ return cbor_encode_floating_point(encoder, CborDoubleType, &value); }
-
-CBOR_API CborError cbor_encoder_create_array(CborEncoder *encoder, CborEncoder *arrayEncoder, size_t length);
-CBOR_API CborError cbor_encoder_create_map(CborEncoder *encoder, CborEncoder *mapEncoder, size_t length);
-CBOR_API CborError cbor_encoder_close_container(CborEncoder *encoder, const CborEncoder *containerEncoder);
-CBOR_API CborError cbor_encoder_close_container_checked(CborEncoder *encoder, const CborEncoder *containerEncoder);
-
-CBOR_INLINE_API size_t cbor_encoder_get_buffer_size(const CborEncoder *encoder, const uint8_t *buffer)
-{
-    return (size_t)(encoder->ptr - buffer);
-}
-
-CBOR_INLINE_API size_t cbor_encoder_get_extra_bytes_needed(const CborEncoder *encoder)
-{
-    return encoder->end ? 0 : (size_t)encoder->bytes_needed;
-}
-
-/* Parser API */
-
-enum CborParserIteratorFlags
-{
-    CborIteratorFlag_IntegerValueTooLarge   = 0x01,
-    CborIteratorFlag_NegativeInteger        = 0x02,
-    CborIteratorFlag_UnknownLength          = 0x04,
-    CborIteratorFlag_ContainerIsMap         = 0x20
-};
-
-struct CborParser
-{
-    const uint8_t *end;
-    int flags;
-};
-typedef struct CborParser CborParser;
-
-struct CborValue
-{
-    const CborParser *parser;
-    const uint8_t *ptr;
-    uint32_t remaining;
-    uint16_t extra;
-    uint8_t type;
-    uint8_t flags;
-};
-typedef struct CborValue CborValue;
-
-CBOR_API CborError cbor_parser_init(const uint8_t *buffer, size_t size, int flags, CborParser *parser, CborValue *it);
-
-CBOR_INLINE_API bool cbor_value_at_end(const CborValue *it)
-{ return it->remaining == 0; }
-CBOR_INLINE_API const uint8_t *cbor_value_get_next_byte(const CborValue *it)
-{ return it->ptr; }
-CBOR_API CborError cbor_value_advance_fixed(CborValue *it);
-CBOR_API CborError cbor_value_advance(CborValue *it);
-CBOR_INLINE_API bool cbor_value_is_container(const CborValue *it)
-{ return it->type == CborArrayType || it->type == CborMapType; }
-CBOR_API CborError cbor_value_enter_container(const CborValue *it, CborValue *recursed);
-CBOR_API CborError cbor_value_leave_container(CborValue *it, const CborValue *recursed);
-
-CBOR_PRIVATE_API uint64_t _cbor_value_decode_int64_internal(const CborValue *value);
-CBOR_INLINE_API uint64_t _cbor_value_extract_int64_helper(const CborValue *value)
-{
-    return value->flags & CborIteratorFlag_IntegerValueTooLarge ?
-                _cbor_value_decode_int64_internal(value) : value->extra;
-}
-
-CBOR_INLINE_API bool cbor_value_is_valid(const CborValue *value)
-{ return value && value->type != CborInvalidType; }
-CBOR_INLINE_API CborType cbor_value_get_type(const CborValue *value)
-{ return (CborType)value->type; }
-
-/* Null & undefined type */
-CBOR_INLINE_API bool cbor_value_is_null(const CborValue *value)
-{ return value->type == CborNullType; }
-CBOR_INLINE_API bool cbor_value_is_undefined(const CborValue *value)
-{ return value->type == CborUndefinedType; }
-
-/* Booleans */
-CBOR_INLINE_API bool cbor_value_is_boolean(const CborValue *value)
-{ return value->type == CborBooleanType; }
-CBOR_INLINE_API CborError cbor_value_get_boolean(const CborValue *value, bool *result)
-{
-    assert(cbor_value_is_boolean(value));
-    *result = !!value->extra;
-    return CborNoError;
-}
-
-/* Simple types */
-CBOR_INLINE_API bool cbor_value_is_simple_type(const CborValue *value)
-{ return value->type == CborSimpleType; }
-CBOR_INLINE_API CborError cbor_value_get_simple_type(const CborValue *value, uint8_t *result)
-{
-    assert(cbor_value_is_simple_type(value));
-    *result = (uint8_t)value->extra;
-    return CborNoError;
-}
-
-/* Integers */
-CBOR_INLINE_API bool cbor_value_is_integer(const CborValue *value)
-{ return value->type == CborIntegerType; }
-CBOR_INLINE_API bool cbor_value_is_unsigned_integer(const CborValue *value)
-{ return cbor_value_is_integer(value) && (value->flags & CborIteratorFlag_NegativeInteger) == 0; }
-CBOR_INLINE_API bool cbor_value_is_negative_integer(const CborValue *value)
-{ return cbor_value_is_integer(value) && (value->flags & CborIteratorFlag_NegativeInteger); }
-
-CBOR_INLINE_API CborError cbor_value_get_raw_integer(const CborValue *value, uint64_t *result)
-{
-    assert(cbor_value_is_integer(value));
-    *result = _cbor_value_extract_int64_helper(value);
-    return CborNoError;
-}
-
-CBOR_INLINE_API CborError cbor_value_get_uint64(const CborValue *value, uint64_t *result)
-{
-    assert(cbor_value_is_unsigned_integer(value));
-    *result = _cbor_value_extract_int64_helper(value);
-    return CborNoError;
-}
-
-CBOR_INLINE_API CborError cbor_value_get_int64(const CborValue *value, int64_t *result)
-{
-    assert(cbor_value_is_integer(value));
-    *result = (int64_t) _cbor_value_extract_int64_helper(value);
-    if (value->flags & CborIteratorFlag_NegativeInteger)
-        *result = -*result - 1;
-    return CborNoError;
-}
-
-CBOR_INLINE_API CborError cbor_value_get_int(const CborValue *value, int *result)
-{
-    assert(cbor_value_is_integer(value));
-    *result = (int) _cbor_value_extract_int64_helper(value);
-    if (value->flags & CborIteratorFlag_NegativeInteger)
-        *result = -*result - 1;
-    return CborNoError;
-}
-
-CBOR_API CborError cbor_value_get_int64_checked(const CborValue *value, int64_t *result);
-CBOR_API CborError cbor_value_get_int_checked(const CborValue *value, int *result);
-
-CBOR_INLINE_API bool cbor_value_is_length_known(const CborValue *value)
-{ return (value->flags & CborIteratorFlag_UnknownLength) == 0; }
-
-/* Tags */
-CBOR_INLINE_API bool cbor_value_is_tag(const CborValue *value)
-{ return value->type == CborTagType; }
-CBOR_INLINE_API CborError cbor_value_get_tag(const CborValue *value, CborTag *result)
-{
-    assert(cbor_value_is_tag(value));
-    *result = _cbor_value_extract_int64_helper(value);
-    return CborNoError;
-}
-CBOR_API CborError cbor_value_skip_tag(CborValue *it);
-
-/* Strings */
-CBOR_INLINE_API bool cbor_value_is_byte_string(const CborValue *value)
-{ return value->type == CborByteStringType; }
-CBOR_INLINE_API bool cbor_value_is_text_string(const CborValue *value)
-{ return value->type == CborTextStringType; }
-
-CBOR_INLINE_API CborError cbor_value_get_string_length(const CborValue *value, size_t *length)
-{
-    assert(cbor_value_is_byte_string(value) || cbor_value_is_text_string(value));
-    if (!cbor_value_is_length_known(value))
-        return CborErrorUnknownLength;
-    uint64_t v = _cbor_value_extract_int64_helper(value);
-    *length = v;
-    if (*length != v)
-        return CborErrorDataTooLarge;
-    return CborNoError;
-}
-
-CBOR_PRIVATE_API CborError _cbor_value_copy_string(const CborValue *value, void *buffer,
-                                                   size_t *buflen, CborValue *next);
-CBOR_PRIVATE_API CborError _cbor_value_dup_string(const CborValue *value, void **buffer,
-                                                  size_t *buflen, CborValue *next);
-
-CBOR_API CborError cbor_value_calculate_string_length(const CborValue *value, size_t *length);
-
-CBOR_INLINE_API CborError cbor_value_copy_text_string(const CborValue *value, char *buffer,
-                                                      size_t *buflen, CborValue *next)
-{
-    assert(cbor_value_is_text_string(value));
-    return _cbor_value_copy_string(value, buffer, buflen, next);
-}
-CBOR_INLINE_API CborError cbor_value_copy_byte_string(const CborValue *value, uint8_t *buffer,
-                                                      size_t *buflen, CborValue *next)
-{
-    assert(cbor_value_is_byte_string(value));
-    return _cbor_value_copy_string(value, buffer, buflen, next);
-}
-
-CBOR_INLINE_API CborError cbor_value_dup_text_string(const CborValue *value, char **buffer,
-                                                     size_t *buflen, CborValue *next)
-{
-    assert(cbor_value_is_text_string(value));
-    return _cbor_value_dup_string(value, (void **)buffer, buflen, next);
-}
-CBOR_INLINE_API CborError cbor_value_dup_byte_string(const CborValue *value, uint8_t **buffer,
-                                                     size_t *buflen, CborValue *next)
-{
-    assert(cbor_value_is_byte_string(value));
-    return _cbor_value_dup_string(value, (void **)buffer, buflen, next);
-}
-
-/* ### TBD: partial reading API */
-
-CBOR_API CborError cbor_value_text_string_equals(const CborValue *value, const char *string, bool *result);
-
-/* Maps and arrays */
-CBOR_INLINE_API bool cbor_value_is_array(const CborValue *value)
-{ return value->type == CborArrayType; }
-CBOR_INLINE_API bool cbor_value_is_map(const CborValue *value)
-{ return value->type == CborMapType; }
-
-CBOR_INLINE_API CborError cbor_value_get_array_length(const CborValue *value, size_t *length)
-{
-    assert(cbor_value_is_array(value));
-    if (!cbor_value_is_length_known(value))
-        return CborErrorUnknownLength;
-    uint64_t v = _cbor_value_extract_int64_helper(value);
-    *length = v;
-    if (*length != v)
-        return CborErrorDataTooLarge;
-    return CborNoError;
-}
-
-CBOR_INLINE_API CborError cbor_value_get_map_length(const CborValue *value, size_t *length)
-{
-    assert(cbor_value_is_map(value));
-    if (!cbor_value_is_length_known(value))
-        return CborErrorUnknownLength;
-    uint64_t v = _cbor_value_extract_int64_helper(value);
-    *length = v;
-    if (*length != v)
-        return CborErrorDataTooLarge;
-    return CborNoError;
-}
-
-CBOR_API CborError cbor_value_map_find_value(const CborValue *map, const char *string, CborValue *element);
-
-/* Floating point */
-CBOR_INLINE_API bool cbor_value_is_half_float(const CborValue *value)
-{ return value->type == CborHalfFloatType; }
-CBOR_API CborError cbor_value_get_half_float(const CborValue *value, void *result);
-
-CBOR_INLINE_API bool cbor_value_is_float(const CborValue *value)
-{ return value->type == CborFloatType; }
-CBOR_INLINE_API CborError cbor_value_get_float(const CborValue *value, float *result)
-{
-    assert(cbor_value_is_float(value));
-    assert(value->flags & CborIteratorFlag_IntegerValueTooLarge);
-    uint32_t data = (uint32_t)_cbor_value_decode_int64_internal(value);
-    memcpy(result, &data, sizeof(*result));
-    return CborNoError;
-}
-
-CBOR_INLINE_API bool cbor_value_is_double(const CborValue *value)
-{ return value->type == CborDoubleType; }
-CBOR_INLINE_API CborError cbor_value_get_double(const CborValue *value, double *result)
-{
-    assert(cbor_value_is_double(value));
-    assert(value->flags & CborIteratorFlag_IntegerValueTooLarge);
-    uint64_t data = _cbor_value_decode_int64_internal(value);
-    memcpy(result, &data, sizeof(*result));
-    return CborNoError;
-}
-
-/* Human-readable (dump) API */
-CBOR_API CborError cbor_value_to_pretty_advance(FILE *out, CborValue *value);
-CBOR_INLINE_API CborError cbor_value_to_pretty(FILE *out, const CborValue *value)
-{
-    CborValue copy = *value;
-    return cbor_value_to_pretty_advance(out, &copy);
-}
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* CBOR_H */
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/tinycbor/include/tinycbor/cborconstants_p.h
----------------------------------------------------------------------
diff --git a/libs/tinycbor/include/tinycbor/cborconstants_p.h b/libs/tinycbor/include/tinycbor/cborconstants_p.h
deleted file mode 100644
index d5808c3..0000000
--- a/libs/tinycbor/include/tinycbor/cborconstants_p.h
+++ /dev/null
@@ -1,52 +0,0 @@
-#ifndef CBORCONSTANTS_P_H
-#define CBORCONSTANTS_P_H
-
-/*
- * CBOR Major types
- * Encoded in the high 3 bits of the descriptor byte
- * See http://tools.ietf.org/html/rfc7049#section-2.1
- */
-typedef enum CborMajorTypes {
-    UnsignedIntegerType = 0U,
-    NegativeIntegerType = 1U,
-    ByteStringType = 2U,
-    TextStringType = 3U,
-    ArrayType = 4U,
-    MapType = 5U,           /* a.k.a. object */
-    TagType = 6U,
-    SimpleTypesType = 7U
-} CborMajorTypes;
-
-/*
- * CBOR simple and floating point types
- * Encoded in the low 8 bits of the descriptor byte when the
- * Major Type is 7.
- */
-typedef enum CborSimpleTypes {
-    FalseValue              = 20,
-    TrueValue               = 21,
-    NullValue               = 22,
-    UndefinedValue          = 23,
-    SimpleTypeInNextByte    = 24,   /* not really a simple type */
-    HalfPrecisionFloat      = 25,   /* ditto */
-    SinglePrecisionFloat    = 26,   /* ditto */
-    DoublePrecisionFloat    = 27,   /* ditto */
-    Break                   = 31
-} CborSimpleTypes;
-
-enum {
-    SmallValueBitLength     = 5U,
-    SmallValueMask          = (1U << SmallValueBitLength) - 1,      /* 31 */
-    Value8Bit               = 24U,
-    Value16Bit              = 25U,
-    Value32Bit              = 26U,
-    Value64Bit              = 27U,
-    IndefiniteLength        = 31U,
-
-    MajorTypeShift          = SmallValueBitLength,
-    MajorTypeMask           = ~0U << MajorTypeShift,
-
-    BreakByte               = (unsigned)Break | (SimpleTypesType << MajorTypeShift)
-};
-
-#endif /* CBORCONSTANTS_P_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/tinycbor/include/tinycbor/cborjson.h
----------------------------------------------------------------------
diff --git a/libs/tinycbor/include/tinycbor/cborjson.h b/libs/tinycbor/include/tinycbor/cborjson.h
deleted file mode 100644
index 8ff27b9..0000000
--- a/libs/tinycbor/include/tinycbor/cborjson.h
+++ /dev/null
@@ -1,62 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 Intel Corporation
-**
-** Permission is hereby granted, free of charge, to any person obtaining a copy
-** of this software and associated documentation files (the "Software"), to deal
-** in the Software without restriction, including without limitation the rights
-** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-** copies of the Software, and to permit persons to whom the Software is
-** furnished to do so, subject to the following conditions:
-**
-** The above copyright notice and this permission notice shall be included in
-** all copies or substantial portions of the Software.
-**
-** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-** THE SOFTWARE.
-**
-****************************************************************************/
-
-#ifndef CBORJSON_H
-#define CBORJSON_H
-
-#include "cbor.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* Conversion to JSON */
-enum CborToJsonFlags
-{
-    CborConvertAddMetadata = 1,
-    CborConvertTagsToObjects = 2,
-    CborConvertIgnoreTags = 0,
-
-    CborConvertObeyByteStringTags = 0,
-    CborConvertByteStringsToBase64Url = 4,
-
-    CborConvertRequireMapStringKeys = 0,
-    CborConvertStringifyMapKeys = 8,
-
-    CborConvertDefaultFlags = 0
-};
-
-CBOR_API CborError cbor_value_to_json_advance(FILE *out, CborValue *value, int flags);
-CBOR_INLINE_API CborError cbor_value_to_json(FILE *out, const CborValue *value, int flags)
-{
-    CborValue copy = *value;
-    return cbor_value_to_json_advance(out, &copy, flags);
-}
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* CBORJSON_H */
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/tinycbor/include/tinycbor/compilersupport_p.h
----------------------------------------------------------------------
diff --git a/libs/tinycbor/include/tinycbor/compilersupport_p.h b/libs/tinycbor/include/tinycbor/compilersupport_p.h
deleted file mode 100644
index 4e0dbe3..0000000
--- a/libs/tinycbor/include/tinycbor/compilersupport_p.h
+++ /dev/null
@@ -1,218 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 Intel Corporation
-**
-** Permission is hereby granted, free of charge, to any person obtaining a copy
-** of this software and associated documentation files (the "Software"), to deal
-** in the Software without restriction, including without limitation the rights
-** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-** copies of the Software, and to permit persons to whom the Software is
-** furnished to do so, subject to the following conditions:
-**
-** The above copyright notice and this permission notice shall be included in
-** all copies or substantial portions of the Software.
-**
-** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-** THE SOFTWARE.
-**
-****************************************************************************/
-
-#ifndef COMPILERSUPPORT_H
-#define COMPILERSUPPORT_H
-
-#include "cbor.h"
-
-#ifndef _BSD_SOURCE
-#  define _BSD_SOURCE
-#endif
-#ifndef _DEFAULT_SOURCE
-#  define _DEFAULT_SOURCE
-#endif
-#include <assert.h>
-#include <float.h>
-#include <stddef.h>
-#include <stdint.h>
-#include <string.h>
-
-#ifndef __cplusplus
-#  include <stdbool.h>
-#endif
-
-#ifdef __F16C__
-#  include <immintrin.h>
-#endif
-
-#if __STDC_VERSION__ >= 201112L || __cplusplus >= 201103L || __cpp_static_assert >= 200410
-#  define cbor_static_assert(x)         _Static_assert(x, #x)
-#elif !defined(__cplusplus) && defined(__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__ >= 406)
-#  define cbor_static_assert(x)         _Static_assert(x, #x)
-#else
-#  define cbor_static_assert(x)         ((void)sizeof(char[2*!!(x) - 1]))
-#endif
-#if __STDC_VERSION__ >= 199901L || defined(__cplusplus)
-/* inline is a keyword */
-#else
-/* use the definition from cbor.h */
-#  define inline    CBOR_INLINE
-#endif
-
-#define STRINGIFY(x)            STRINGIFY2(x)
-#define STRINGIFY2(x)           #x
-
-#if !defined(UINT32_MAX) || !defined(INT64_MAX)
-/* C89? We can define UINT32_MAX portably, but not INT64_MAX */
-#  error "Your system has stdint.h but that doesn't define UINT32_MAX or INT64_MAX"
-#endif
-
-#ifndef DBL_DECIMAL_DIG
-/* DBL_DECIMAL_DIG is C11 */
-#  define DBL_DECIMAL_DIG       17
-#endif
-#define DBL_DECIMAL_DIG_STR     STRINGIFY(DBL_DECIMAL_DIG)
-
-#ifndef __has_builtin
-#  define __has_builtin(x)  0
-#endif
-
-#if (defined(__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__ >= 403)) || \
-    (__has_builtin(__builtin_bswap64) && __has_builtin(__builtin_bswap32))
-#  if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
-#    define cbor_ntohll     __builtin_bswap64
-#    define cbor_htonll     __builtin_bswap64
-#    define cbor_ntohl      __builtin_bswap32
-#    define cbor_htonl      __builtin_bswap32
-#    ifdef __INTEL_COMPILER
-#      define cbor_ntohs    _bswap16
-#      define cbor_htons    _bswap16
-#    elif (__GNUC__ * 100 + __GNUC_MINOR__ >= 608) || __has_builtin(__builtin_bswap16)
-#      define cbor_ntohs    __builtin_bswap16
-#      define cbor_htons    __builtin_bswap16
-#    else
-#      define cbor_ntohs(x) (((uint16_t)x >> 8) | ((uint16_t)x << 8))
-#      define cbor_htons    cbor_ntohs
-#    endif
-#  else
-#    define cbor_ntohll
-#    define cbor_htonll
-#    define cbor_ntohl
-#    define cbor_htonl
-#    define cbor_ntohs
-#    define cbor_htons
-#  endif
-#elif defined(__sun)
-#  include <sys/byteorder.h>
-#elif defined(_MSC_VER)
-/* MSVC, which implies Windows, which implies little-endian and sizeof(long) == 4 */
-#  define cbor_ntohll       _byteswap_uint64
-#  define cbor_htonll       _byteswap_uint64
-#  define cbor_ntohl        _byteswap_ulong
-#  define cbor_htonl        _byteswap_ulong
-#  define cbor_ntohs        _byteswap_ushort
-#  define cbor_htons        _byteswap_ushort
-#endif
-#ifndef cbor_ntohs
-#  include <arpa/inet.h>
-#  define cbor_ntohs        ntohs
-#  define cbor_htons        htons
-#endif
-#ifndef cbor_ntohl
-#  include <arpa/inet.h>
-#  define cbor_ntohl        ntohl
-#  define cbor_htonl        htonl
-#endif
-#ifndef cbor_ntohll
-#  define cbor_ntohll       ntohll
-#  define cbor_htonll       htonll
-/* ntohll isn't usually defined */
-#  ifndef ntohll
-#    if defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
-#      define ntohll
-#      define htonll
-#    elif defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
-#      define ntohll(x)       ((ntohl((uint32_t)(x)) * UINT64_C(0x100000000)) + (ntohl((x) >> 32)))
-#      define htonll          ntohll
-#    else
-#      error "Unable to determine byte order!"
-#    endif
-#  endif
-#endif
-
-
-#ifdef __cplusplus
-#  define CONST_CAST(t, v)  const_cast<t>(v)
-#else
-/* C-style const_cast without triggering a warning with -Wcast-qual */
-#  define CONST_CAST(t, v)  (t)(uintptr_t)(v)
-#endif
-
-#ifdef __GNUC__
-#  define likely(x)     __builtin_expect(!!(x), 1)
-#  define unlikely(x)   __builtin_expect(!!(x), 0)
-#  define unreachable() __builtin_unreachable()
-#elif defined(_MSC_VER)
-#  define likely(x)     (x)
-#  define unlikely(x)   (x)
-#  define unreachable() __assume(0)
-#else
-#  define likely(x)     (x)
-#  define unlikely(x)   (x)
-#  define unreachable() do {} while (0)
-#endif
-
-#if defined(__GNUC__) && !defined(__INTEL_COMPILER) && !defined(__clang__) && \
-    (__GNUC__ * 100 + __GNUC_MINOR__ >= 404)
-#  pragma GCC optimize("-ffunction-sections")
-#endif
-
-static inline bool add_check_overflow(size_t v1, size_t v2, size_t *r)
-{
-#if ((defined(__GNUC__) && (__GNUC__ >= 5)) && !defined(__INTEL_COMPILER)) || __has_builtin(__builtin_add_overflow)
-    return __builtin_add_overflow(v1, v2, r);
-#else
-    /* unsigned additions are well-defined */
-    *r = v1 + v2;
-    return v1 > v1 + v2;
-#endif
-}
-
-static inline unsigned short encode_half(double val)
-{
-#ifdef __F16C__
-    return _cvtss_sh(val, 3);
-#else
-    uint64_t v;
-    memcpy(&v, &val, sizeof(v));
-    int sign = v >> 63 << 15;
-    int exp = (v >> 52) & 0x7ff;
-    int mant = v << 12 >> 12 >> (53-11);    /* keep only the 11 most significant bits of the mantissa */
-    exp -= 1023;
-    if (exp == 1024) {
-        /* infinity or NaN */
-        exp = 16;
-        mant >>= 1;
-    } else if (exp >= 16) {
-        /* overflow, as largest number */
-        exp = 15;
-        mant = 1023;
-    } else if (exp >= -14) {
-        /* regular normal */
-    } else if (exp >= -24) {
-        /* subnormal */
-        mant |= 1024;
-        mant >>= -(exp + 14);
-        exp = -15;
-    } else {
-        /* underflow, make zero */
-        return 0;
-    }
-    return sign | ((exp + 15) << 10) | mant;
-#endif
-}
-
-#endif /* COMPILERSUPPORT_H */
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/tinycbor/include/tinycbor/extract_number_p.h
----------------------------------------------------------------------
diff --git a/libs/tinycbor/include/tinycbor/extract_number_p.h b/libs/tinycbor/include/tinycbor/extract_number_p.h
deleted file mode 100644
index b65ca44..0000000
--- a/libs/tinycbor/include/tinycbor/extract_number_p.h
+++ /dev/null
@@ -1,78 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 Intel Corporation
-**
-** Permission is hereby granted, free of charge, to any person obtaining a copy
-** of this software and associated documentation files (the "Software"), to deal
-** in the Software without restriction, including without limitation the rights
-** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-** copies of the Software, and to permit persons to whom the Software is
-** furnished to do so, subject to the following conditions:
-**
-** The above copyright notice and this permission notice shall be included in
-** all copies or substantial portions of the Software.
-**
-** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-** THE SOFTWARE.
-**
-****************************************************************************/
-
-#define _BSD_SOURCE 1
-#define _DEFAULT_SOURCE 1
-#include "cbor.h"
-#include "cborconstants_p.h"
-#include "compilersupport_p.h"
-#include <stdlib.h>
-
-static inline uint16_t get16(const uint8_t *ptr)
-{
-    uint16_t result;
-    memcpy(&result, ptr, sizeof(result));
-    return cbor_ntohs(result);
-}
-
-static inline uint32_t get32(const uint8_t *ptr)
-{
-    uint32_t result;
-    memcpy(&result, ptr, sizeof(result));
-    return cbor_ntohl(result);
-}
-
-static inline uint64_t get64(const uint8_t *ptr)
-{
-    uint64_t result;
-    memcpy(&result, ptr, sizeof(result));
-    return cbor_ntohll(result);
-}
-
-static CborError extract_number(const uint8_t **ptr, const uint8_t *end, uint64_t *len)
-{
-    uint8_t additional_information = **ptr & SmallValueMask;
-    ++*ptr;
-    if (additional_information < Value8Bit) {
-        *len = additional_information;
-        return CborNoError;
-    }
-    if (unlikely(additional_information > Value64Bit))
-        return CborErrorIllegalNumber;
-
-    size_t bytesNeeded = (size_t)(1 << (additional_information - Value8Bit));
-    if (unlikely(bytesNeeded > (size_t)(end - *ptr))) {
-        return CborErrorUnexpectedEOF;
-    } else if (bytesNeeded == 1) {
-        *len = (uint8_t)(*ptr)[0];
-    } else if (bytesNeeded == 2) {
-        *len = get16(*ptr);
-    } else if (bytesNeeded == 4) {
-        *len = get32(*ptr);
-    } else {
-        *len = get64(*ptr);
-    }
-    *ptr += bytesNeeded;
-    return CborNoError;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/tinycbor/include/tinycbor/math_support_p.h
----------------------------------------------------------------------
diff --git a/libs/tinycbor/include/tinycbor/math_support_p.h b/libs/tinycbor/include/tinycbor/math_support_p.h
deleted file mode 100644
index 676f781..0000000
--- a/libs/tinycbor/include/tinycbor/math_support_p.h
+++ /dev/null
@@ -1,47 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 Intel Corporation
-**
-** Permission is hereby granted, free of charge, to any person obtaining a copy
-** of this software and associated documentation files (the "Software"), to deal
-** in the Software without restriction, including without limitation the rights
-** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-** copies of the Software, and to permit persons to whom the Software is
-** furnished to do so, subject to the following conditions:
-**
-** The above copyright notice and this permission notice shall be included in
-** all copies or substantial portions of the Software.
-**
-** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-** THE SOFTWARE.
-**
-****************************************************************************/
-
-#ifndef MATH_SUPPORT_H
-#define MATH_SUPPORT_H
-
-#include <math.h>
-
-/* this function was copied & adapted from RFC 7049 Appendix D */
-static inline double decode_half(unsigned short half)
-{
-#ifdef __F16C__
-    return _cvtsh_ss(half);
-#else
-    int exp = (half >> 10) & 0x1f;
-    int mant = half & 0x3ff;
-    double val;
-    if (exp == 0) val = ldexp(mant, -24);
-    else if (exp != 31) val = ldexp(mant + 1024, exp - 25);
-    else val = mant == 0 ? INFINITY : NAN;
-    return half & 0x8000 ? -val : val;
-#endif
-}
-
-#endif // MATH_SUPPORT_H
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/tinycbor/pkg.yml
----------------------------------------------------------------------
diff --git a/libs/tinycbor/pkg.yml b/libs/tinycbor/pkg.yml
deleted file mode 100644
index 3eb846d..0000000
--- a/libs/tinycbor/pkg.yml
+++ /dev/null
@@ -1,26 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you 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.
-#
-
-pkg.name: libs/tinycbor 
-pkg.description: CBOR encoding/decoding library 
-pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
-pkg.homepage: "http://mynewt.apache.org/"
-pkg.keywords:
-
-pkg.cflags: -DWITHOUT_OPEN_MEMSTREAM -I../include/tinycbor
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/tinycbor/src/cborencoder.c
----------------------------------------------------------------------
diff --git a/libs/tinycbor/src/cborencoder.c b/libs/tinycbor/src/cborencoder.c
deleted file mode 100644
index eef05cd..0000000
--- a/libs/tinycbor/src/cborencoder.c
+++ /dev/null
@@ -1,629 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 Intel Corporation
-**
-** Permission is hereby granted, free of charge, to any person obtaining a copy
-** of this software and associated documentation files (the "Software"), to deal
-** in the Software without restriction, including without limitation the rights
-** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-** copies of the Software, and to permit persons to whom the Software is
-** furnished to do so, subject to the following conditions:
-**
-** The above copyright notice and this permission notice shall be included in
-** all copies or substantial portions of the Software.
-**
-** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-** THE SOFTWARE.
-**
-****************************************************************************/
-
-#define _BSD_SOURCE 1
-#define _DEFAULT_SOURCE 1
-#ifndef __STDC_LIMIT_MACROS
-#  define __STDC_LIMIT_MACROS 1
-#endif
-
-#include "cbor.h"
-#include "cborconstants_p.h"
-#include "compilersupport_p.h"
-
-#include <assert.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include "assert_p.h"       /* Always include last */
-
-/**
- * \defgroup CborEncoding Encoding to CBOR
- * \brief Group of functions used to encode data to CBOR.
- *
- * CborEncoder is used to encode data into a CBOR stream. The outermost
- * CborEncoder is initialized by calling cbor_encoder_init(), with the buffer
- * where the CBOR stream will be stored. The outermost CborEncoder is usually
- * used to encode exactly one item, most often an array or map. It is possible
- * to encode more than one item, but care must then be taken on the decoder
- * side to ensure the state is reset after each item was decoded.
- *
- * Nested CborEncoder objects are created using cbor_encoder_create_array() and
- * cbor_encoder_create_map(), later closed with cbor_encoder_close_container()
- * or cbor_encoder_close_container_checked(). The pairs of creation and closing
- * must be exactly matched and their parameters are always the same.
- *
- * CborEncoder writes directly to the user-supplied buffer, without extra
- * buffering. CborEncoder does not allocate memory and CborEncoder objects are
- * usually created on the stack of the encoding functions.
- *
- * The example below initializes a CborEncoder object with a buffer and encodes
- * a single integer.
- *
- * \code
- *      uint8_t buf[16];
- *      CborEncoder encoder;
- *      cbor_encoder_init(&encoder, &buf, sizeof(buf), 0);
- *      cbor_encode_int(&encoder, some_value);
- * \endcode
- *
- * As explained before, usually the outermost CborEncoder object is used to add
- * one array or map, which in turn contains multiple elements. The example
- * below creates a CBOR map with one element: a key "foo" and a boolean value.
- *
- * \code
- *      uint8_t buf[16];
- *      CborEncoder encoder, mapEncoder;
- *      cbor_encoder_init(&encoder, &buf, sizeof(buf), 0);
- *      cbor_encoder_create_map(&encoder, &mapEncoder, 1);
- *      cbor_encode_text_stringz(&mapEncoder, "foo");
- *      cbor_encode_boolean(&mapEncoder, some_value);
- *      cbor_encoder_close_container(&encoder, &mapEncoder);
- * \endcode
- *
- * <h3 class="groupheader">Error checking and buffer size</h2>
- *
- * All functions operating on CborEncoder return a condition of type CborError.
- * If the encoding was successful, they return CborNoError. Some functions do
- * extra checking on the input provided and may return some other error
- * conditions (for example, cbor_encode_simple_value() checks that the type is
- * of the correct type).
- *
- * In addition, all functions check whether the buffer has enough bytes to
- * encode the item being appended. If that is not possible, they return
- * CborErrorOutOfMemory.
- *
- * It is possible to continue with the encoding of data past the first function
- * that returns CborErrorOutOfMemory. CborEncoder functions will not overrun
- * the buffer, but will instead count how many more bytes are needed to
- * complete the encoding. At the end, you can obtain that count by calling
- * cbor_encoder_get_extra_bytes_needed().
- *
- * \section1 Finalizing the encoding
- *
- * Once all items have been appended and the containers have all been properly
- * closed, the user-supplied buffer will contain the CBOR stream and may be
- * immediately used. To obtain the size of the buffer, call
- * cbor_encoder_get_buffer_size() with the original buffer pointer.
- *
- * The example below illustrates how one can encode an item with error checking
- * and then pass on the buffer for network sending.
- *
- * \code
- *      uint8_t buf[16];
- *      CborError err;
- *      CborEncoder encoder, mapEncoder;
- *      cbor_encoder_init(&encoder, &buf, sizeof(buf), 0);
- *      err = cbor_encoder_create_map(&encoder, &mapEncoder, 1);
- *      if (!err)
- *          return err;
- *      err = cbor_encode_text_stringz(&mapEncoder, "foo");
- *      if (!err)
- *          return err;
- *      err = cbor_encode_boolean(&mapEncoder, some_value);
- *      if (!err)
- *          return err;
- *      err = cbor_encoder_close_container_checked(&encoder, &mapEncoder);
- *      if (!err)
- *          return err;
- *
- *      size_t len = cbor_encoder_get_buffer_size(&encoder, buf);
- *      send_payload(buf, len);
- *      return CborNoError;
- * \endcode
- *
- * Finally, the example below illustrates expands on the one above and also
- * deals with dynamically growing the buffer if the initial allocation wasn't
- * big enough. Note the two places where the error checking was replaced with
- * an assertion, showing where the author assumes no error can occur.
- *
- * \code
- * uint8_t *encode_string_array(const char **strings, int n, size_t *bufsize)
- * {
- *     CborError err;
- *     CborEncoder encoder, arrayEncoder;
- *     size_t size = 256;
- *     uint8_t *buf = NULL;
- *
- *     while (1) {
- *         int i;
- *         size_t more_bytes;
- *         uint8_t *nbuf = realloc(buf, size);
- *         if (nbuf == NULL)
- *             goto error;
- *         buf = nbuf;
- *
- *         cbor_encoder_init(&encoder, &buf, size, 0);
- *         err = cbor_encoder_create_array(&encoder, &arrayEncoder, n);
- *         assert(err);         // can't fail, the buffer is always big enough
- *
- *         for (i = 0; i < n; ++i) {
- *             err = cbor_encode_text_stringz(&arrayEncoder, strings[i]);
- *             if (err && err != CborErrorOutOfMemory)
- *                 goto error;
- *         }
- *
- *         err = cbor_encoder_close_container_checked(&encoder, &arrayEncoder);
- *         assert(err);         // shouldn't fail!
- *
- *         more_bytes = cbor_encoder_get_extra_bytes_needed(encoder);
- *         if (more_size) {
- *             // buffer wasn't big enough, try again
- *             size += more_bytes;
- *             continue;
- *         }
- *
- *         *bufsize = cbor_encoder_get_buffer_size(encoder, buf);
- *         return buf;
- *     }
- *  error:
- *     free(buf);
- *     return NULL;
- *  }
- * \endcode
- */
-
-/**
- * \addtogroup CborEncoding
- * @{
- */
-
-/**
- * \struct CborEncoder
- * Structure used to encode to CBOR.
- */
-
-/**
- * Initializes a CborEncoder structure \a encoder by pointing it to buffer \a
- * buffer of size \a size. The \a flags field is currently unused and must be
- * zero.
- */
-void cbor_encoder_init(CborEncoder *encoder, uint8_t *buffer, size_t size, int flags)
-{
-    encoder->ptr = buffer;
-    encoder->end = buffer + size;
-    encoder->added = 0;
-    encoder->flags = flags;
-}
-
-static inline void put16(void *where, uint16_t v)
-{
-    v = cbor_htons(v);
-    memcpy(where, &v, sizeof(v));
-}
-
-/* Note: Since this is currently only used in situations where OOM is the only
- * valid error, we KNOW this to be true.  Thus, this function now returns just 'true',
- * but if in the future, any function starts returning a non-OOM error, this will need
- * to be changed to the test.  At the moment, this is done to prevent more branches
- * being created in the tinycbor output */
-static inline bool isOomError(CborError err)
-{
-    (void) err;
-    return true;
-}
-
-static inline void put32(void *where, uint32_t v)
-{
-    v = cbor_htonl(v);
-    memcpy(where, &v, sizeof(v));
-}
-
-static inline void put64(void *where, uint64_t v)
-{
-    v = cbor_htonll(v);
-    memcpy(where, &v, sizeof(v));
-}
-
-static inline bool would_overflow(CborEncoder *encoder, size_t len)
-{
-    ptrdiff_t remaining = (ptrdiff_t)encoder->end;
-    remaining -= remaining ? (ptrdiff_t)encoder->ptr : encoder->bytes_needed;
-    remaining -= (ptrdiff_t)len;
-    return unlikely(remaining < 0);
-}
-
-static inline void advance_ptr(CborEncoder *encoder, size_t n)
-{
-    if (encoder->end)
-        encoder->ptr += n;
-    else
-        encoder->bytes_needed += n;
-}
-
-static inline CborError append_to_buffer(CborEncoder *encoder, const void *data, size_t len)
-{
-    if (would_overflow(encoder, len)) {
-        if (encoder->end != NULL) {
-            len -= encoder->end - encoder->ptr;
-            encoder->end = NULL;
-            encoder->bytes_needed = 0;
-        }
-
-        advance_ptr(encoder, len);
-        return CborErrorOutOfMemory;
-    }
-
-    memcpy(encoder->ptr, data, len);
-    encoder->ptr += len;
-    return CborNoError;
-}
-
-static inline CborError append_byte_to_buffer(CborEncoder *encoder, uint8_t byte)
-{
-    return append_to_buffer(encoder, &byte, 1);
-}
-
-static inline CborError encode_number_no_update(CborEncoder *encoder, uint64_t ui, uint8_t shiftedMajorType)
-{
-    /* Little-endian would have been so much more convenient here:
-     * We could just write at the beginning of buf but append_to_buffer
-     * only the necessary bytes.
-     * Since it has to be big endian, do it the other way around:
-     * write from the end. */
-    uint64_t buf[2];
-    uint8_t *const bufend = (uint8_t *)buf + sizeof(buf);
-    uint8_t *bufstart = bufend - 1;
-    put64(buf + 1, ui);     /* we probably have a bunch of zeros in the beginning */
-
-    if (ui < Value8Bit) {
-        *bufstart += shiftedMajorType;
-    } else {
-        unsigned more = 0;
-        if (ui > 0xffU)
-            ++more;
-        if (ui > 0xffffU)
-            ++more;
-        if (ui > 0xffffffffU)
-            ++more;
-        bufstart -= (size_t)1 << more;
-        *bufstart = shiftedMajorType + Value8Bit + more;
-    }
-
-    return append_to_buffer(encoder, bufstart, bufend - bufstart);
-}
-
-static inline CborError encode_number(CborEncoder *encoder, uint64_t ui, uint8_t shiftedMajorType)
-{
-    ++encoder->added;
-    return encode_number_no_update(encoder, ui, shiftedMajorType);
-}
-
-/**
- * Appends the unsigned 64-bit integer \a value to the CBOR stream provided by
- * \a encoder.
- *
- * \sa cbor_encode_negative_int, cbor_encode_int
- */
-CborError cbor_encode_uint(CborEncoder *encoder, uint64_t value)
-{
-    return encode_number(encoder, value, UnsignedIntegerType << MajorTypeShift);
-}
-
-/**
- * Appends the negative 64-bit integer whose absolute value is \a
- * absolute_value to the CBOR stream provided by \a encoder.
- *
- * \sa cbor_encode_uint, cbor_encode_int
- */
-CborError cbor_encode_negative_int(CborEncoder *encoder, uint64_t absolute_value)
-{
-    return encode_number(encoder, absolute_value, NegativeIntegerType << MajorTypeShift);
-}
-
-/**
- * Appends the signed 64-bit integer \a value to the CBOR stream provided by
- * \a encoder.
- *
- * \sa cbor_encode_negative_int, cbor_encode_uint
- */
-CborError cbor_encode_int(CborEncoder *encoder, int64_t value)
-{
-    /* adapted from code in RFC 7049 appendix C (pseudocode) */
-    uint64_t ui = value >> 63;              /* extend sign to whole length */
-    uint8_t majorType = ui & 0x20;          /* extract major type */
-    ui ^= value;                            /* complement negatives */
-    return encode_number(encoder, ui, majorType);
-}
-
-/**
- * Appends the CBOR Simple Type of value \a value to the CBOR stream provided by
- * \a encoder.
- *
- * This function may return error CborErrorIllegalSimpleType if the \a value
- * variable contains a number that is not a valid simple type.
- */
-CborError cbor_encode_simple_value(CborEncoder *encoder, uint8_t value)
-{
-#ifndef CBOR_ENCODER_NO_CHECK_USER
-    /* check if this is a valid simple type */
-    if (value >= HalfPrecisionFloat && value <= Break)
-        return CborErrorIllegalSimpleType;
-#endif
-    return encode_number(encoder, value, SimpleTypesType << MajorTypeShift);
-}
-
-/**
- * Appends the floating-point value of type \a fpType and pointed to by \a
- * value to the CBOR stream provided by \a encoder. The value of \a fpType must
- * be one of CborHalfFloatType, CborFloatType or CborDoubleType, otherwise the
- * behavior of this function is undefined.
- *
- * This function is useful for code that needs to pass through floating point
- * values but does not wish to have the actual floating-point code.
- *
- * \sa cbor_encode_half_float, cbor_encode_float, cbor_encode_double
- */
-CborError cbor_encode_floating_point(CborEncoder *encoder, CborType fpType, const void *value)
-{
-    uint8_t buf[1 + sizeof(uint64_t)];
-    assert(fpType == CborHalfFloatType || fpType == CborFloatType || fpType == CborDoubleType);
-    buf[0] = fpType;
-
-    unsigned size = 2U << (fpType - CborHalfFloatType);
-    if (size == 8)
-        put64(buf + 1, *(const uint64_t*)value);
-    else if (size == 4)
-        put32(buf + 1, *(const uint32_t*)value);
-    else
-        put16(buf + 1, *(const uint16_t*)value);
-    ++encoder->added;
-    return append_to_buffer(encoder, buf, size + 1);
-}
-
-/**
- * Appends the CBOR tag \a tag to the CBOR stream provided by \a encoder.
- *
- * \sa CborTag
- */
-CborError cbor_encode_tag(CborEncoder *encoder, CborTag tag)
-{
-    /* tags don't count towards the number of elements in an array or map */
-    return encode_number_no_update(encoder, tag, TagType << MajorTypeShift);
-}
-
-static CborError encode_string(CborEncoder *encoder, size_t length, uint8_t shiftedMajorType, const void *string)
-{
-    CborError err = encode_number(encoder, length, shiftedMajorType);
-    if (err && !isOomError(err))
-        return err;
-    return append_to_buffer(encoder, string, length);
-}
-
-/**
- * \fn CborError cbor_encode_text_stringz(CborEncoder *encoder, const char *string)
- *
- * Appends the null-terminated text string \a string to the CBOR stream
- * provided by \a encoder. CBOR requires that \a string be valid UTF-8, but
- * TinyCBOR makes no verification of correctness. The terminating null is not
- * included in the stream.
- *
- * \sa cbor_encode_text_string, cbor_encode_byte_string
- */
-
-/**
- * Appends the text string \a string of length \a length to the CBOR stream
- * provided by \a encoder. CBOR requires that \a string be valid UTF-8, but
- * TinyCBOR makes no verification of correctness.
- *
- * \sa CborError cbor_encode_text_stringz, cbor_encode_byte_string
- */
-CborError cbor_encode_byte_string(CborEncoder *encoder, const uint8_t *string, size_t length)
-{
-    return encode_string(encoder, length, ByteStringType << MajorTypeShift, string);
-}
-
-/**
- * Appends the byte string \a string of length \a length to the CBOR stream
- * provided by \a encoder. CBOR byte strings are arbitrary raw data.
- *
- * \sa cbor_encode_text_stringz, cbor_encode_text_string
- */
-CborError cbor_encode_text_string(CborEncoder *encoder, const char *string, size_t length)
-{
-    return encode_string(encoder, length, TextStringType << MajorTypeShift, string);
-}
-
-#ifdef __GNUC__
-__attribute__((noinline))
-#endif
-static CborError create_container(CborEncoder *encoder, CborEncoder *container, size_t length, uint8_t shiftedMajorType)
-{
-    CborError err;
-    container->ptr = encoder->ptr;
-    container->end = encoder->end;
-    ++encoder->added;
-    container->added = 0;
-
-    cbor_static_assert(((MapType << MajorTypeShift) & CborIteratorFlag_ContainerIsMap) == CborIteratorFlag_ContainerIsMap);
-    cbor_static_assert(((ArrayType << MajorTypeShift) & CborIteratorFlag_ContainerIsMap) == 0);
-    container->flags = shiftedMajorType & CborIteratorFlag_ContainerIsMap;
-
-    if (length == CborIndefiniteLength) {
-        container->flags |= CborIteratorFlag_UnknownLength;
-        err = append_byte_to_buffer(container, shiftedMajorType + IndefiniteLength);
-    } else {
-        err = encode_number_no_update(container, length, shiftedMajorType);
-    }
-    if (err && !isOomError(err))
-        return err;
-
-    return CborNoError;
-}
-
-/**
- * Creates a CBOR array in the CBOR stream provided by \a encoder and
- * initializes \a arrayEncoder so that items can be added to the array using
- * the CborEncoder functions. The array must be terminated by calling either
- * cbor_encoder_close_container() or cbor_encoder_close_container_checked()
- * with the same \a encoder and \a arrayEncoder parameters.
- *
- * The number of items inserted into the array must be exactly \a length items,
- * otherwise the stream is invalid. If the number of items is not known when
- * creating the array, the constant \ref CborIndefiniteLength may be passed as
- * length instead.
- *
- * \sa cbor_encoder_create_map
- */
-CborError cbor_encoder_create_array(CborEncoder *encoder, CborEncoder *arrayEncoder, size_t length)
-{
-    return create_container(encoder, arrayEncoder, length, ArrayType << MajorTypeShift);
-}
-
-/**
- * Creates a CBOR map in the CBOR stream provided by \a encoder and
- * initializes \a mapEncoder so that items can be added to the map using
- * the CborEncoder functions. The map must be terminated by calling either
- * cbor_encoder_close_container() or cbor_encoder_close_container_checked()
- * with the same \a encoder and \a mapEncoder parameters.
- *
- * The number of pair of items inserted into the map must be exactly \a length
- * items, otherwise the stream is invalid. If the number of items is not known
- * when creating the map, the constant \ref CborIndefiniteLength may be passed as
- * length instead.
- *
- * \b{Implementation limitation:} TinyCBOR cannot encode more than SIZE_MAX/2
- * key-value pairs in the stream. If the length \a length is larger than this
- * value, this function returns error CborErrorDataTooLarge.
- *
- * \sa cbor_encoder_create_array
- */
-CborError cbor_encoder_create_map(CborEncoder *encoder, CborEncoder *mapEncoder, size_t length)
-{
-    if (length != CborIndefiniteLength && length > SIZE_MAX / 2)
-        return CborErrorDataTooLarge;
-    return create_container(encoder, mapEncoder, length, MapType << MajorTypeShift);
-}
-
-/**
- * Closes the CBOR container (array or map) provided by \a containerEncoder and
- * updates the CBOR stream provided by \a encoder. Both parameters must be the
- * same as were passed to cbor_encoder_create_array() or
- * cbor_encoder_create_map().
- *
- * This function does not verify that the number of items (or pair of items, in
- * the case of a map) was correct. To execute that verification, call
- * cbor_encoder_close_container_checked() instead.
- *
- * \sa cbor_encoder_create_array(), cbor_encoder_create_map()
- */
-CborError cbor_encoder_close_container(CborEncoder *encoder, const CborEncoder *containerEncoder)
-{
-    if (encoder->end)
-        encoder->ptr = containerEncoder->ptr;
-    else
-        encoder->bytes_needed = containerEncoder->bytes_needed;
-    encoder->end = containerEncoder->end;
-    if (containerEncoder->flags & CborIteratorFlag_UnknownLength)
-        return append_byte_to_buffer(encoder, BreakByte);
-    return CborNoError;
-}
-
-/**
- * \fn CborError cbor_encode_boolean(CborEncoder *encoder, bool value)
- *
- * Appends the boolean value \a value to the CBOR stream provided by \a encoder.
- */
-
-/**
- * \fn CborError cbor_encode_null(CborEncoder *encoder)
- *
- * Appends the CBOR type representing a null value to the CBOR stream provided
- * by \a encoder.
- *
- * \sa cbor_encode_undefined()
- */
-
-/**
- * \fn CborError cbor_encode_undefined(CborEncoder *encoder)
- *
- * Appends the CBOR type representing an undefined value to the CBOR stream
- * provided by \a encoder.
- *
- * \sa cbor_encode_null()
- */
-
-/**
- * \fn CborError cbor_encode_half_float(CborEncoder *encoder, const void *value)
- *
- * Appends the IEEE 754 half-precision (16-bit) floating point value pointed to
- * by \a value to the CBOR stream provided by \a encoder.
- *
- * \sa cbor_encode_floating_point(), cbor_encode_float(), cbor_encode_double()
- */
-
-/**
- * \fn CborError cbor_encode_float(CborEncoder *encoder, float value)
- *
- * Appends the IEEE 754 single-precision (32-bit) floating point value \a value
- * to the CBOR stream provided by \a encoder.
- *
- * \sa cbor_encode_floating_point(), cbor_encode_half_float(), cbor_encode_double()
- */
-
-/**
- * \fn CborError cbor_encode_double(CborEncoder *encoder, double value)
- *
- * Appends the IEEE 754 double-precision (64-bit) floating point value \a value
- * to the CBOR stream provided by \a encoder.
- *
- * \sa cbor_encode_floating_point(), cbor_encode_half_float(), cbor_encode_float()
- */
-
-/**
- * \fn size_t cbor_encoder_get_buffer_size(const CborEncoder *encoder, const uint8_t *buffer)
- *
- * Returns the total size of the buffer starting at \a buffer after the
- * encoding finished without errors. The \a encoder and \a buffer arguments
- * must be the same as supplied to cbor_encoder_init().
- *
- * If the encoding process had errors, the return value of this function is
- * meaningless. If the only errors were CborErrorOutOfMemory, instead use
- * cbor_encoder_get_extra_bytes_needed() to find out by how much to grow the
- * buffer before encoding again.
- *
- * See \ref CborEncoding for an example of using this function.
- *
- * \sa cbor_encoder_init(), cbor_encoder_get_extra_bytes_needed(), CborEncoding
- */
-
-/**
- * \fn size_t cbor_encoder_get_extra_bytes_needed(const CborEncoder *encoder)
- *
- * Returns how many more bytes the original buffer supplied to
- * cbor_encoder_init() needs to be extended by so that no CborErrorOutOfMemory
- * condition will happen for the encoding. If the buffer was big enough, this
- * function returns 0. The \a encoder must be the original argument as passed
- * to cbor_encoder_init().
- *
- * This function is usually called after an encoding sequence ended with one or
- * more CborErrorOutOfMemory errors, but no other error. If any other error
- * happened, the return value of this function is meaningless.
- *
- * See \ref CborEncoding for an example of using this function.
- *
- * \sa cbor_encoder_init(), cbor_encoder_get_buffer_size(), CborEncoding
- */
-
-/** @} */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/tinycbor/src/cborencoder_close_container_checked.c
----------------------------------------------------------------------
diff --git a/libs/tinycbor/src/cborencoder_close_container_checked.c b/libs/tinycbor/src/cborencoder_close_container_checked.c
deleted file mode 100644
index cad8335..0000000
--- a/libs/tinycbor/src/cborencoder_close_container_checked.c
+++ /dev/null
@@ -1,82 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 Intel Corporation
-**
-** Permission is hereby granted, free of charge, to any person obtaining a copy
-** of this software and associated documentation files (the "Software"), to deal
-** in the Software without restriction, including without limitation the rights
-** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-** copies of the Software, and to permit persons to whom the Software is
-** furnished to do so, subject to the following conditions:
-**
-** The above copyright notice and this permission notice shall be included in
-** all copies or substantial portions of the Software.
-**
-** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-** THE SOFTWARE.
-**
-****************************************************************************/
-
-#define _BSD_SOURCE 1
-#define _DEFAULT_SOURCE 1
-#ifndef __STDC_LIMIT_MACROS
-#  define __STDC_LIMIT_MACROS 1
-#endif
-
-#include "cbor.h"
-#include "cborconstants_p.h"
-#include "compilersupport_p.h"
-#include "extract_number_p.h"
-
-#include <assert.h>
-
-#include "assert_p.h"       /* Always include last */
-
-/**
- * \addtogroup CborEncoding
- * @{
- */
-
-/**
- *
- * Closes the CBOR container (array or map) provided by \a containerEncoder and
- * updates the CBOR stream provided by \a encoder. Both parameters must be the
- * same as were passed to cbor_encoder_create_array() or
- * cbor_encoder_create_map().
- *
- * Unlike cbor_encoder_close_container(), this function checks that the number
- * of items (or pair of items, in the case of a map) was correct. If the number
- * of items inserted does not match the length originally passed to
- * cbor_encoder_create_array() or cbor_encoder_create_map(), this function
- * returns either CborErrorTooFewItems or CborErrorTooManyItems.
- *
- * \sa cbor_encoder_create_array(), cbor_encoder_create_map()
- */
-CborError cbor_encoder_close_container_checked(CborEncoder *encoder, const CborEncoder *containerEncoder)
-{
-    const uint8_t *ptr = encoder->ptr;
-    CborError err = cbor_encoder_close_container(encoder, containerEncoder);
-    if (containerEncoder->flags & CborIteratorFlag_UnknownLength || encoder->end == NULL)
-        return err;
-
-    /* check what the original length was */
-    uint64_t actually_added;
-    err = extract_number(&ptr, encoder->ptr, &actually_added);
-    if (err)
-        return err;
-
-    if (containerEncoder->flags & CborIteratorFlag_ContainerIsMap) {
-        if (actually_added > SIZE_MAX / 2)
-            return CborErrorDataTooLarge;
-        actually_added *= 2;
-    }
-    return actually_added == containerEncoder->added ? CborNoError :
-           actually_added < containerEncoder->added ? CborErrorTooManyItems : CborErrorTooFewItems;
-}
-
-/** @} */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/tinycbor/src/cborerrorstrings.c
----------------------------------------------------------------------
diff --git a/libs/tinycbor/src/cborerrorstrings.c b/libs/tinycbor/src/cborerrorstrings.c
deleted file mode 100644
index d2fe42f..0000000
--- a/libs/tinycbor/src/cborerrorstrings.c
+++ /dev/null
@@ -1,165 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 Intel Corporation
-**
-** Permission is hereby granted, free of charge, to any person obtaining a copy
-** of this software and associated documentation files (the "Software"), to deal
-** in the Software without restriction, including without limitation the rights
-** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-** copies of the Software, and to permit persons to whom the Software is
-** furnished to do so, subject to the following conditions:
-**
-** The above copyright notice and this permission notice shall be included in
-** all copies or substantial portions of the Software.
-**
-** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-** THE SOFTWARE.
-**
-****************************************************************************/
-
-#include "cbor.h"
-
-#ifndef _
-#  define _(msg)    msg
-#endif
-
-/**
- * \enum CborError
- * \ingroup CborGlobals
- * The CborError enum contains the possible error values used by the CBOR encoder and decoder.
- *
- * TinyCBOR functions report success by returning CborNoError, or one error
- * condition by returning one of the values below. One exception is the
- * out-of-memory condition (CborErrorOutOfMemory), which the functions for \ref
- * CborEncoding may report in bit-wise OR with other conditions.
- *
- * This technique allows code to determine whether the only error condition was
- * a lack of buffer space, which may not be a fatal condition if the buffer can
- * be resized. Additionally, the functions for \ref CborEncoding may continue
- * to be used even after CborErrorOutOfMemory is returned, and instead they
- * will simply calculate the extra space needed.
- *
- * \value CborNoError                   No error occurred
- * \omitvalue CborUnknownError
- * \value CborErrorUnknownLength        Request for the length of an array, map or string whose length is not provided in the CBOR stream
- * \value CborErrorAdvancePastEOF       Not enough data in the stream to decode item (decoding would advance past end of stream)
- * \value CborErrorIO                   An I/O error occurred, probably due to an out-of-memory situation
- * \value CborErrorGarbageAtEnd         Bytes exist past the end of the CBOR stream
- * \value CborErrorUnexpectedEOF        End of stream reached unexpectedly
- * \value CborErrorUnexpectedBreak      A CBOR break byte was found where not expected
- * \value CborErrorUnknownType          An unknown type (future extension to CBOR) was found in the stream
- * \value CborErrorIllegalType          An invalid type was found while parsing a chunked CBOR string
- * \value CborErrorIllegalNumber        An illegal initial byte (encoding unspecified additional information) was found
- * \value CborErrorIllegalSimpleType    An illegal encoding of a CBOR Simple Type of value less than 32 was found
- * \omitvalue CborErrorUnknownSimpleType
- * \omitvalue CborErrorUnknownTag
- * \omitvalue CborErrorInappropriateTagForType
- * \omitvalue CborErrorDuplicateObjectKeys
- * \value CborErrorInvalidUtf8TextString Illegal UTF-8 encoding found while parsing CBOR Text String
- * \value CborErrorTooManyItems         Too many items were added to CBOR map or array of pre-determined length
- * \value CborErrorTooFewItems          Too few items were added to CBOR map or array of pre-determeined length
- * \value CborErrorDataTooLarge         Data item size exceeds TinyCBOR's implementation limits
- * \value CborErrorNestingTooDeep       Data item nesting exceeds TinyCBOR's implementation limits
- * \omitvalue CborErrorUnsupportedType
- * \value CborErrorJsonObjectKeyIsAggregate Conversion to JSON failed because the key in a map is a CBOR map or array
- * \value CborErrorJsonObjectKeyNotString Conversion to JSON failed because the key in a map is not a text string
- * \value CborErrorOutOfMemory          During CBOR encoding, the buffer provided is insufficient for encoding the data item;
- *                                      in other situations, TinyCBOR failed to allocate memory
- * \value CborErrorInternalError        An internal error occurred in TinyCBOR
- */
-
-/**
- * \ingroup CborGlobals
- * Returns the error string corresponding to the CBOR error condition \a error.
- */
-const char *cbor_error_string(CborError error)
-{
-    switch (error) {
-    case CborNoError:
-        return "";
-
-    case CborUnknownError:
-        return _("unknown error");
-
-    case CborErrorOutOfMemory:
-        return _("out of memory/need more memory");
-
-    case CborErrorUnknownLength:
-        return _("unknown length (attempted to get the length of a map/array/string of indeterminate length");
-
-    case CborErrorAdvancePastEOF:
-        return _("attempted to advance past EOF");
-
-    case CborErrorIO:
-        return _("I/O error");
-
-    case CborErrorGarbageAtEnd:
-        return _("garbage after the end of the content");
-
-    case CborErrorUnexpectedEOF:
-        return _("unexpected end of data");
-
-    case CborErrorUnexpectedBreak:
-        return _("unexpected 'break' byte");
-
-    case CborErrorUnknownType:
-        return _("illegal byte (encodes future extension type)");
-
-    case CborErrorIllegalType:
-        return _("mismatched string type in chunked string");
-
-    case CborErrorIllegalNumber:
-        return _("illegal initial byte (encodes unspecified additional information)");
-
-    case CborErrorIllegalSimpleType:
-        return _("illegal encoding of simple type smaller than 32");
-
-    case CborErrorUnknownSimpleType:
-        return _("unknown simple type");
-
-    case CborErrorUnknownTag:
-        return _("unknown tag");
-
-    case CborErrorInappropriateTagForType:
-        return _("inappropriate tag for type");
-
-    case CborErrorDuplicateObjectKeys:
-        return _("duplicate keys in object");
-
-    case CborErrorInvalidUtf8TextString:
-        return _("invalid UTF-8 content in string");
-
-    case CborErrorTooManyItems:
-        return _("too many items added to encoder");
-
-    case CborErrorTooFewItems:
-        return _("too few items added to encoder");
-
-    case CborErrorDataTooLarge:
-        return _("internal error: data too large");
-
-    case CborErrorNestingTooDeep:
-        return _("internal error: too many nested containers found in recursive function");
-
-    case CborErrorUnsupportedType:
-        return _("unsupported type");
-
-    case CborErrorJsonObjectKeyIsAggregate:
-        return _("conversion to JSON failed: key in object is an array or map");
-
-    case CborErrorJsonObjectKeyNotString:
-        return _("conversion to JSON failed: key in object is not a string");
-
-    case CborErrorJsonNotImplemented:
-        return _("conversion to JSON failed: open_memstream unavailable");
-
-    case CborErrorInternalError:
-        return _("internal error");
-    }
-    return cbor_error_string(CborUnknownError);
-}


[09/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/tinycbor/src/cborparser.c
----------------------------------------------------------------------
diff --git a/libs/tinycbor/src/cborparser.c b/libs/tinycbor/src/cborparser.c
deleted file mode 100644
index 1d81091..0000000
--- a/libs/tinycbor/src/cborparser.c
+++ /dev/null
@@ -1,1293 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 Intel Corporation
-**
-** Permission is hereby granted, free of charge, to any person obtaining a copy
-** of this software and associated documentation files (the "Software"), to deal
-** in the Software without restriction, including without limitation the rights
-** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-** copies of the Software, and to permit persons to whom the Software is
-** furnished to do so, subject to the following conditions:
-**
-** The above copyright notice and this permission notice shall be included in
-** all copies or substantial portions of the Software.
-**
-** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-** THE SOFTWARE.
-**
-****************************************************************************/
-
-#define _BSD_SOURCE 1
-#define _DEFAULT_SOURCE 1
-#ifndef __STDC_LIMIT_MACROS
-#  define __STDC_LIMIT_MACROS 1
-#endif
-
-#include "cbor.h"
-#include "cborconstants_p.h"
-#include "compilersupport_p.h"
-#include "extract_number_p.h"
-
-#include <assert.h>
-#include <string.h>
-
-#include "assert_p.h"       /* Always include last */
-
-#ifndef CBOR_PARSER_MAX_RECURSIONS
-#  define CBOR_PARSER_MAX_RECURSIONS 1024
-#endif
-
-/**
- * \defgroup CborParsing Parsing CBOR streams
- * \brief Group of functions used to parse CBOR streams.
- *
- * TinyCBOR provides functions for pull-based stream parsing of a CBOR-encoded
- * payload. The main data type for the parsing is a CborValue, which behaves
- * like an iterator and can be used to extract the encoded data. It is first
- * initialized with a call to cbor_parser_init() and is usually used to extract
- * exactly one item, most often an array or map.
- *
- * Nested CborValue objects can be parsed using cbor_value_enter_container().
- * Each call to cbor_value_enter_container() must be matched by a call to
- * cbor_value_leave_container(), with the exact same parameters.
- *
- * The example below initializes a CborParser object, begins the parsing with a
- * CborValue and decodes a single integer:
- *
- * \code
- * int extract_int(const uint8_t *buffer, size_t len)
- * {
- *     CborParser parser;
- *     CborValue value;
- *     int result;
- *     cbor_parser_init(buffer, len, 0, &buffer, &value);
- *     cbor_value_get_int(&value, &result);
- *     return result;
- * }
- * \endcode
- *
- * The code above does no error checking, which means it assumes the data comes
- * from a source trusted to send one properly-encoded integer. The following
- * example does the exact same operation, but includes error parsing and
- * returns 0 on parsing failure:
- *
- * \code
- * int extract_int(const uint8_t *buffer, size_t len)
- * {
- *     CborParser parser;
- *     CborValue value;
- *     int result;
- *     if (cbor_parser_init(buffer, len, 0, &buffer, &value) != CborNoError)
- *         return 0;
- *     if (!cbor_value_is_integer(&value) ||
- *             cbor_value_get_int(&value, &result) != CborNoError)
- *         return 0;
- *     return result;
- * }
- * \endcode
- *
- * Note, in the example above, that one can't distinguish a parsing failure
- * from an encoded value of zero. Reporting a parsing error is left as an
- * exercise to the reader.
- *
- * The code above does not execute a range-check either: it is possible that
- * the value decoded from the CBOR stream encodes a number larger than what can
- * be represented in a variable of type \c{int}. If detecting that case is
- * important, the code should call cbor_value_get_int_checked() instead.
- *
- * <h3 class="groupheader">Memory and parsing constraints</h3>
- *
- * TinyCBOR is designed to run with little memory and with minimal overhead.
- * Except where otherwise noted, the parser functions always run on constant
- * time (O(1)), do not recurse and never allocate memory (thus, stack usage is
- * bounded and is O(1)).
- *
- * <h3 class="groupheader">Error handling and preconditions</h3>
- *
- * All functions operating on a CborValue return a CborError condition, with
- * CborNoError standing for the normal situation in which no parsing error
- * occurred. All functions may return parsing errors in case the stream cannot
- * be decoded properly, be it due to corrupted data or due to reaching the end
- * of the input buffer.
- *
- * Error conditions must not be ignored. All decoder functions have undefined
- * behavior if called after an error has been reported, and may crash.
- *
- * Some functions are also documented to have preconditions, like
- * cbor_value_get_int() requiring that the input be an integral value.
- * Violation of preconditions also results in undefined behavior and the
- * program may crash.
- */
-
-/**
- * \addtogroup CborParsing
- * @{
- */
-
-/**
- * \struct CborValue
- *
- * This type contains one value parsed from the CBOR stream. Each CborValue
- * behaves as an iterator in a StAX-style parser.
- *
- * \if privatedocs
- * Implementation details: the CborValue contains these fields:
- * \list
- *   \li ptr: pointer to the actual data
- *   \li flags: flags from the decoder
- *   \li extra: partially decoded integer value (0, 1 or 2 bytes)
- *   \li remaining: remaining items in this collection after this item or UINT32_MAX if length is unknown
- * \endlist
- * \endif
- */
-
-static CborError extract_length(const CborParser *parser, const uint8_t **ptr, size_t *len)
-{
-    uint64_t v;
-    CborError err = extract_number(ptr, parser->end, &v);
-    if (err) {
-        *len = 0;
-        return err;
-    }
-
-    *len = v;
-    if (v != *len)
-        return CborErrorDataTooLarge;
-    return CborNoError;
-}
-
-static bool is_fixed_type(uint8_t type)
-{
-    return type != CborTextStringType && type != CborByteStringType && type != CborArrayType &&
-           type != CborMapType;
-}
-
-static CborError preparse_value(CborValue *it)
-{
-    const CborParser *parser = it->parser;
-    it->type = CborInvalidType;
-
-    /* are we at the end? */
-    if (it->ptr == parser->end)
-        return CborErrorUnexpectedEOF;
-
-    uint8_t descriptor = *it->ptr;
-    uint8_t type = descriptor & MajorTypeMask;
-    it->type = type;
-    it->flags = 0;
-    it->extra = (descriptor &= SmallValueMask);
-
-    if (descriptor > Value64Bit) {
-        if (unlikely(descriptor != IndefiniteLength))
-            return type == CborSimpleType ? CborErrorUnknownType : CborErrorIllegalNumber;
-        if (likely(!is_fixed_type(type))) {
-            /* special case */
-            it->flags |= CborIteratorFlag_UnknownLength;
-            it->type = type;
-            return CborNoError;
-        }
-        return type == CborSimpleType ? CborErrorUnexpectedBreak : CborErrorIllegalNumber;
-    }
-
-    size_t bytesNeeded = descriptor < Value8Bit ? 0 : (1 << (descriptor - Value8Bit));
-    if (bytesNeeded + 1 > (size_t)(parser->end - it->ptr))
-        return CborErrorUnexpectedEOF;
-
-    uint8_t majortype = type >> MajorTypeShift;
-    if (majortype == NegativeIntegerType) {
-        it->flags |= CborIteratorFlag_NegativeInteger;
-        it->type = CborIntegerType;
-    } else if (majortype == SimpleTypesType) {
-        switch (descriptor) {
-        case FalseValue:
-            it->extra = false;
-            it->type = CborBooleanType;
-            break;
-
-        case SinglePrecisionFloat:
-        case DoublePrecisionFloat:
-            it->flags |= CborIteratorFlag_IntegerValueTooLarge;
-            /* fall through */
-        case TrueValue:
-        case NullValue:
-        case UndefinedValue:
-        case HalfPrecisionFloat:
-            it->type = *it->ptr;
-            break;
-
-        case SimpleTypeInNextByte:
-            it->extra = (uint8_t)it->ptr[1];
-#ifndef CBOR_PARSER_NO_STRICT_CHECKS
-            if (unlikely(it->extra < 32)) {
-                it->type = CborInvalidType;
-                return CborErrorIllegalSimpleType;
-            }
-#endif
-            break;
-
-        case 28:
-        case 29:
-        case 30:
-        case Break:
-            assert(false);  /* these conditions can't be reached */
-            return CborErrorUnexpectedBreak;
-        }
-        return CborNoError;
-    }
-
-    /* try to decode up to 16 bits */
-    if (descriptor < Value8Bit)
-        return CborNoError;
-
-    if (descriptor == Value8Bit)
-        it->extra = (uint8_t)it->ptr[1];
-    else if (descriptor == Value16Bit)
-        it->extra = get16(it->ptr + 1);
-    else
-        it->flags |= CborIteratorFlag_IntegerValueTooLarge;     /* Value32Bit or Value64Bit */
-    return CborNoError;
-}
-
-static CborError preparse_next_value(CborValue *it)
-{
-    if (it->remaining != UINT32_MAX) {
-        /* don't decrement the item count if the current item is tag: they don't count */
-        if (it->type != CborTagType && !--it->remaining) {
-            it->type = CborInvalidType;
-            return CborNoError;
-        }
-    } else if (it->remaining == UINT32_MAX && it->ptr != it->parser->end && *it->ptr == (uint8_t)BreakByte) {
-        /* end of map or array */
-        ++it->ptr;
-        it->type = CborInvalidType;
-        it->remaining = 0;
-        return CborNoError;
-    }
-
-    return preparse_value(it);
-}
-
-static CborError advance_internal(CborValue *it)
-{
-    uint64_t length;
-    CborError err = extract_number(&it->ptr, it->parser->end, &length);
-    assert(err == CborNoError);
-
-    if (it->type == CborByteStringType || it->type == CborTextStringType) {
-        assert(length == (size_t)length);
-        assert((it->flags & CborIteratorFlag_UnknownLength) == 0);
-        it->ptr += length;
-    }
-
-    return preparse_next_value(it);
-}
-
-/** \internal
- *
- * Decodes the CBOR integer value when it is larger than the 16 bits available
- * in value->extra. This function requires that value->flags have the
- * CborIteratorFlag_IntegerValueTooLarge flag set.
- *
- * This function is also used to extract single- and double-precision floating
- * point values (SinglePrecisionFloat == Value32Bit and DoublePrecisionFloat ==
- * Value64Bit).
- */
-uint64_t _cbor_value_decode_int64_internal(const CborValue *value)
-{
-    assert(value->flags & CborIteratorFlag_IntegerValueTooLarge ||
-           value->type == CborFloatType || value->type == CborDoubleType);
-
-    /* since the additional information can only be Value32Bit or Value64Bit,
-     * we just need to test for the one bit those two options differ */
-    assert((*value->ptr & SmallValueMask) == Value32Bit || (*value->ptr & SmallValueMask) == Value64Bit);
-    if ((*value->ptr & 1) == (Value32Bit & 1))
-        return get32(value->ptr + 1);
-
-    assert((*value->ptr & SmallValueMask) == Value64Bit);
-    return get64(value->ptr + 1);
-}
-
-/**
- * Initializes the CBOR parser for parsing \a size bytes beginning at \a
- * buffer. Parsing will use flags set in \a flags. The iterator to the first
- * element is returned in \a it.
- *
- * The \a parser structure needs to remain valid throughout the decoding
- * process. It is not thread-safe to share one CborParser among multiple
- * threads iterating at the same time, but the object can be copied so multiple
- * threads can iterate.
- */
-CborError cbor_parser_init(const uint8_t *buffer, size_t size, int flags, CborParser *parser, CborValue *it)
-{
-    memset(parser, 0, sizeof(*parser));
-    parser->end = buffer + size;
-    parser->flags = flags;
-    it->parser = parser;
-    it->ptr = buffer;
-    it->remaining = 1;      /* there's one type altogether, usually an array or map */
-    return preparse_value(it);
-}
-
-/**
- * \fn bool cbor_value_at_end(const CborValue *it)
- *
- * Returns true if \a it has reached the end of the iteration, usually when
- * advancing after the last item in an array or map.
- *
- * In the case of the outermost CborValue object, this function returns true
- * after decoding a single element. A pointer to the first byte of the
- * remaining data (if any) can be obtained with cbor_value_get_next_byte().
- *
- * \sa cbor_value_advance(), cbor_value_is_valid(), cbor_value_get_next_byte()
- */
-
-/**
- * \fn const uint8_t *cbor_value_get_next_byte(const CborValue *it)
- *
- * Returns a pointer to the next byte that would be decoded if this CborValue
- * object were advanced.
- *
- * This function is useful if cbor_value_at_end() returns true for the
- * outermost CborValue: the pointer returned is the first byte of the data
- * remaining in the buffer, if any. Code can decide whether to begin decoding a
- * new CBOR data stream from this point, or parse some other data appended to
- * the same buffer.
- *
- * This function may be used even after a parsing error. If that occurred,
- * then this function returns a pointer to where the parsing error occurred.
- * Note that the error recovery is not precise and the pointer may not indicate
- * the exact byte containing bad data.
- *
- * \sa cbor_value_at_end()
- */
-
-/**
- * \fn bool cbor_value_is_valid(const CborValue *it)
- *
- * Returns true if the iterator \a it contains a valid value. Invalid iterators
- * happen when iteration reaches the end of a container (see \ref
- * cbor_value_at_end()) or when a search function resulted in no matches.
- *
- * \sa cbor_value_advance(), cbor_valie_at_end(), cbor_value_get_type()
- */
-
-/**
- * Advances the CBOR value \a it by one fixed-size position. Fixed-size types
- * are: integers, tags, simple types (including boolean, null and undefined
- * values) and floating point types.
- *
- * If the type is not of fixed size, this function has undefined behavior. Code
- * must be sure that the current type is one of the fixed-size types before
- * calling this function. This function is provided because it can guarantee
- * that runs in constant time (O(1)).
- *
- * If the caller is not able to determine whether the type is fixed or not, code
- * can use the cbor_value_advance() function instead.
- *
- * \sa cbor_value_at_end(), cbor_value_advance(), cbor_value_enter_container(), cbor_value_leave_container()
- */
-CborError cbor_value_advance_fixed(CborValue *it)
-{
-    assert(it->type != CborInvalidType);
-    assert(is_fixed_type(it->type));
-    if (!it->remaining)
-        return CborErrorAdvancePastEOF;
-    return advance_internal(it);
-}
-
-static CborError advance_recursive(CborValue *it, int nestingLevel)
-{
-    if (is_fixed_type(it->type))
-        return advance_internal(it);
-
-    if (!cbor_value_is_container(it)) {
-        size_t len = SIZE_MAX;
-        return _cbor_value_copy_string(it, NULL, &len, it);
-    }
-
-    /* map or array */
-    if (nestingLevel == CBOR_PARSER_MAX_RECURSIONS)
-        return CborErrorNestingTooDeep;
-
-    CborError err;
-    CborValue recursed;
-    err = cbor_value_enter_container(it, &recursed);
-    if (err)
-        return err;
-    while (!cbor_value_at_end(&recursed)) {
-        err = advance_recursive(&recursed, nestingLevel + 1);
-        if (err)
-            return err;
-    }
-    return cbor_value_leave_container(it, &recursed);
-}
-
-
-/**
- * Advances the CBOR value \a it by one element, skipping over containers.
- * Unlike cbor_value_advance_fixed(), this function can be called on a CBOR
- * value of any type. However, if the type is a container (map or array) or a
- * string with a chunked payload, this function will not run in constant time
- * and will recurse into itself (it will run on O(n) time for the number of
- * elements or chunks and will use O(n) memory for the number of nested
- * containers).
- *
- * \sa cbor_value_at_end(), cbor_value_advance_fixed(), cbor_value_enter_container(), cbor_value_leave_container()
- */
-CborError cbor_value_advance(CborValue *it)
-{
-    assert(it->type != CborInvalidType);
-    if (!it->remaining)
-        return CborErrorAdvancePastEOF;
-    return advance_recursive(it, 0);
-}
-
-/**
- * \fn bool cbor_value_is_tag(const CborValue *value)
- *
- * Returns true if the iterator \a value is valid and points to a CBOR tag.
- *
- * \sa cbor_value_get_tag(), cbor_value_skip_tag()
- */
-
-/**
- * \fn CborError cbor_value_get_tag(const CborValue *value, CborTag *result)
- *
- * Retrieves the CBOR tag value that \a value points to and stores it in \a
- * result. If the iterator \a value does not point to a CBOR tag value, the
- * behavior is undefined, so checking with \ref cbor_value_get_type or with
- * \ref cbor_value_is_tag is recommended.
- *
- * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_tag()
- */
-
-/**
- * Advances the CBOR value \a it until it no longer points to a tag. If \a it is
- * already not pointing to a tag, then this function returns it unchanged.
- *
- * This function does not run in constant time: it will run on O(n) for n being
- * the number of tags. It does use constant memory (O(1) memory requirements).
- *
- * \sa cbor_value_advance_fixed(), cbor_value_advance()
- */
-CborError cbor_value_skip_tag(CborValue *it)
-{
-    while (cbor_value_is_tag(it)) {
-        CborError err = cbor_value_advance_fixed(it);
-        if (err)
-            return err;
-    }
-    return CborNoError;
-}
-
-/**
- * \fn bool cbor_value_is_container(const CborValue *it)
- *
- * Returns true if the \a it value is a container and requires recursion in
- * order to decode (maps and arrays), false otherwise.
- */
-
-/**
- * Creates a CborValue iterator pointing to the first element of the container
- * represented by \a it and saves it in \a recursed. The \a it container object
- * needs to be kept and passed again to cbor_value_leave_container() in order
- * to continue iterating past this container.
- *
- * The \a it CborValue iterator must point to a container.
- *
- * \sa cbor_value_is_container(), cbor_value_leave_container(), cbor_value_advance()
- */
-CborError cbor_value_enter_container(const CborValue *it, CborValue *recursed)
-{
-    CborError err;
-    assert(cbor_value_is_container(it));
-    *recursed = *it;
-
-    if (it->flags & CborIteratorFlag_UnknownLength) {
-        recursed->remaining = UINT32_MAX;
-        ++recursed->ptr;
-        err = preparse_value(recursed);
-        if (err != CborErrorUnexpectedBreak)
-            return err;
-        /* actually, break was expected here
-         * it's just an empty container */
-        ++recursed->ptr;
-    } else {
-        uint64_t len;
-        err = extract_number(&recursed->ptr, recursed->parser->end, &len);
-        assert(err == CborNoError);
-
-        recursed->remaining = (uint32_t)len;
-        if (recursed->remaining != len || len == UINT32_MAX) {
-            /* back track the pointer to indicate where the error occurred */
-            recursed->ptr = it->ptr;
-            return CborErrorDataTooLarge;
-        }
-        if (recursed->type == CborMapType) {
-            /* maps have keys and values, so we need to multiply by 2 */
-            if (recursed->remaining > UINT32_MAX / 2) {
-                /* back track the pointer to indicate where the error occurred */
-                recursed->ptr = it->ptr;
-                return CborErrorDataTooLarge;
-            }
-            recursed->remaining *= 2;
-        }
-        if (len != 0)
-            return preparse_value(recursed);
-    }
-
-    /* the case of the empty container */
-    recursed->type = CborInvalidType;
-    recursed->remaining = 0;
-    return CborNoError;
-}
-
-/**
- * Updates \a it to point to the next element after the container. The \a
- * recursed object needs to point to the element obtained either by advancing
- * the last element of the container (via cbor_value_advance(),
- * cbor_value_advance_fixed(), a nested cbor_value_leave_container(), or the \c
- * next pointer from cbor_value_copy_string() or cbor_value_dup_string()).
- *
- * The \a it and \a recursed parameters must be the exact same as passed to
- * cbor_value_enter_container().
- *
- * \sa cbor_value_enter_container(), cbor_value_at_end()
- */
-CborError cbor_value_leave_container(CborValue *it, const CborValue *recursed)
-{
-    assert(cbor_value_is_container(it));
-    assert(recursed->type == CborInvalidType);
-    it->ptr = recursed->ptr;
-    return preparse_next_value(it);
-}
-
-
-/**
- * \fn CborType cbor_value_get_type(const CborValue *value)
- *
- * Returns the type of the CBOR value that the iterator \a value points to. If
- * \a value does not point to a valid value, this function returns \ref
- * CborInvalidType.
- *
- * TinyCBOR also provides functions to test directly if a given CborValue object
- * is of a given type, like cbor_value_is_text_string() and cbor_value_is_null().
- *
- * \sa cbor_value_is_valid()
- */
-
-/**
- * \fn bool cbor_value_is_null(const CborValue *value)
- *
- * Returns true if the iterator \a value is valid and points to a CBOR null type.
- *
- * \sa cbor_value_is_valid(), cbor_value_is_undefined()
- */
-
-/**
- * \fn bool cbor_value_is_undefined(const CborValue *value)
- *
- * Returns true if the iterator \a value is valid and points to a CBOR undefined type.
- *
- * \sa cbor_value_is_valid(), cbor_value_is_null()
- */
-
-/**
- * \fn bool cbor_value_is_boolean(const CborValue *value)
- *
- * Returns true if the iterator \a value is valid and points to a CBOR boolean
- * type (true or false).
- *
- * \sa cbor_value_is_valid(), cbor_value_get_boolean()
- */
-
-/**
- * \fn CborError cbor_value_get_boolean(const CborValue *value, bool *result)
- *
- * Retrieves the boolean value that \a value points to and stores it in \a
- * result. If the iterator \a value does not point to a boolean value, the
- * behavior is undefined, so checking with \ref cbor_value_get_type or with
- * \ref cbor_value_is_boolean is recommended.
- *
- * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_boolean()
- */
-
-/**
- * \fn bool cbor_value_is_simple_type(const CborValue *value)
- *
- * Returns true if the iterator \a value is valid and points to a CBOR Simple Type
- * type (other than true, false, null and undefined).
- *
- * \sa cbor_value_is_valid(), cbor_value_get_simple_type()
- */
-
-/**
- * \fn CborError cbor_value_get_simple_type(const CborValue *value, uint8_t *result)
- *
- * Retrieves the CBOR Simple Type value that \a value points to and stores it
- * in \a result. If the iterator \a value does not point to a simple_type
- * value, the behavior is undefined, so checking with \ref cbor_value_get_type
- * or with \ref cbor_value_is_simple_type is recommended.
- *
- * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_simple_type()
- */
-
-/**
- * \fn bool cbor_value_is_integer(const CborValue *value)
- *
- * Returns true if the iterator \a value is valid and points to a CBOR integer
- * type.
- *
- * \sa cbor_value_is_valid(), cbor_value_get_int, cbor_value_get_int64, cbor_value_get_uint64, cbor_value_get_raw_integer
- */
-
-/**
- * \fn bool cbor_value_is_unsigned_integer(const CborValue *value)
- *
- * Returns true if the iterator \a value is valid and points to a CBOR unsigned
- * integer type (positive values or zero).
- *
- * \sa cbor_value_is_valid(), cbor_value_get_uint64()
- */
-
-/**
- * \fn bool cbor_value_is_negative_integer(const CborValue *value)
- *
- * Returns true if the iterator \a value is valid and points to a CBOR negative
- * integer type.
- *
- * \sa cbor_value_is_valid(), cbor_value_get_int, cbor_value_get_int64, cbor_value_get_raw_integer
- */
-
-/**
- * \fn CborError cbor_value_get_int(const CborValue *value, int *result)
- *
- * Retrieves the CBOR integer value that \a value points to and stores it in \a
- * result. If the iterator \a value does not point to an integer value, the
- * behavior is undefined, so checking with \ref cbor_value_get_type or with
- * \ref cbor_value_is_integer is recommended.
- *
- * Note that this function does not do range-checking: integral values that do
- * not fit in a variable of type \c{int} are silently truncated to fit. Use
- * cbor_value_get_int_checked() that is not acceptable.
- *
- * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_integer()
- */
-
-/**
- * \fn CborError cbor_value_get_int64(const CborValue *value, int64_t *result)
- *
- * Retrieves the CBOR integer value that \a value points to and stores it in \a
- * result. If the iterator \a value does not point to an integer value, the
- * behavior is undefined, so checking with \ref cbor_value_get_type or with
- * \ref cbor_value_is_integer is recommended.
- *
- * Note that this function does not do range-checking: integral values that do
- * not fit in a variable of type \c{int64_t} are silently truncated to fit. Use
- * cbor_value_get_int64_checked() that is not acceptable.
- *
- * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_integer()
- */
-
-/**
- * \fn CborError cbor_value_get_uint64(const CborValue *value, uint64_t *result)
- *
- * Retrieves the CBOR integer value that \a value points to and stores it in \a
- * result. If the iterator \a value does not point to an unsigned integer
- * value, the behavior is undefined, so checking with \ref cbor_value_get_type
- * or with \ref cbor_value_is_unsigned_integer is recommended.
- *
- * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_unsigned_integer()
- */
-
-/**
- * \fn CborError cbor_value_get_raw_integer(const CborValue *value, uint64_t *result)
- *
- * Retrieves the CBOR integer value that \a value points to and stores it in \a
- * result. If the iterator \a value does not point to an integer value, the
- * behavior is undefined, so checking with \ref cbor_value_get_type or with
- * \ref cbor_value_is_integer is recommended.
- *
- * This function is provided because CBOR negative integers can assume values
- * that cannot be represented with normal 64-bit integer variables.
- *
- * If the integer is unsigned (that is, if cbor_value_is_unsigned_integer()
- * returns true), then \a result will contain the actual value. If the integer
- * is negative, then \a result will contain the absolute value of that integer,
- * minus one. That is, \c {actual = -result - 1}. On architectures using two's
- * complement for representation of negative integers, it is equivalent to say
- * that \a result will contain the bitwise negation of the actual value.
- *
- * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_integer()
- */
-
-/**
- * Retrieves the CBOR integer value that \a value points to and stores it in \a
- * result. If the iterator \a value does not point to an integer value, the
- * behavior is undefined, so checking with \ref cbor_value_get_type or with
- * \ref cbor_value_is_integer is recommended.
- *
- * Unlike cbor_value_get_int64(), this function performs a check to see if the
- * stored integer fits in \a result without data loss. If the number is outside
- * the valid range for the data type, this function returns the recoverable
- * error CborErrorDataTooLarge. In that case, use either
- * cbor_value_get_uint64() (if the number is positive) or
- * cbor_value_get_raw_integer().
- *
- * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_integer(), cbor_value_get_int64()
- */
-CborError cbor_value_get_int64_checked(const CborValue *value, int64_t *result)
-{
-    assert(cbor_value_is_integer(value));
-    uint64_t v = _cbor_value_extract_int64_helper(value);
-
-    /* Check before converting, as the standard says (C11 6.3.1.3 paragraph 3):
-     * "[if] the new type is signed and the value cannot be represented in it; either the
-     *  result is implementation-defined or an implementation-defined signal is raised."
-     *
-     * The range for int64_t is -2^63 to 2^63-1 (int64_t is required to be
-     * two's complement, C11 7.20.1.1 paragraph 3), which in CBOR is
-     * represented the same way, differing only on the "sign bit" (the major
-     * type).
-     */
-
-    if (unlikely(v > (uint64_t)INT64_MAX))
-        return CborErrorDataTooLarge;
-
-    *result = v;
-    if (value->flags & CborIteratorFlag_NegativeInteger)
-        *result = -*result - 1;
-    return CborNoError;
-}
-
-/**
- * Retrieves the CBOR integer value that \a value points to and stores it in \a
- * result. If the iterator \a value does not point to an integer value, the
- * behavior is undefined, so checking with \ref cbor_value_get_type or with
- * \ref cbor_value_is_integer is recommended.
- *
- * Unlike cbor_value_get_int(), this function performs a check to see if the
- * stored integer fits in \a result without data loss. If the number is outside
- * the valid range for the data type, this function returns the recoverable
- * error CborErrorDataTooLarge. In that case, use one of the other integer
- * functions to obtain the value.
- *
- * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_integer(), cbor_value_get_int64(),
- *     cbor_value_get_uint64(), cbor_value_get_int64_checked(), cbor_value_get_raw_integer()
- */
-CborError cbor_value_get_int_checked(const CborValue *value, int *result)
-{
-    assert(cbor_value_is_integer(value));
-    uint64_t v = _cbor_value_extract_int64_helper(value);
-
-    /* Check before converting, as the standard says (C11 6.3.1.3 paragraph 3):
-     * "[if] the new type is signed and the value cannot be represented in it; either the
-     *  result is implementation-defined or an implementation-defined signal is raised."
-     *
-     * But we can convert from signed to unsigned without fault (paragraph 2).
-     *
-     * The range for int is implementation-defined and int is not guaranteed use
-     * two's complement representation (int32_t is).
-     */
-
-    if (value->flags & CborIteratorFlag_NegativeInteger) {
-        if (unlikely(v > (unsigned) -(INT_MIN + 1)))
-            return CborErrorDataTooLarge;
-
-        *result = v;
-        *result = -*result - 1;
-    } else {
-        if (unlikely(v > (uint64_t)INT_MAX))
-            return CborErrorDataTooLarge;
-
-        *result = v;
-    }
-    return CborNoError;
-
-}
-
-/**
- * \fn bool cbor_value_is_length_known(const CborValue *value)
- *
- * Returns true if the length of this type is known without calculation. That
- * is, if the length of this CBOR string, map or array is encoded in the data
- * stream, this function returns true. If the length is not encoded, it returns
- * false.
- *
- * If the length is known, code can call cbor_value_get_string_length(),
- * cbor_value_get_array_length() or cbor_value_get_map_length() to obtain the
- * length. If the length is not known but is necessary, code can use the
- * cbor_value_calculate_string_length() function (no equivalent function is
- * provided for maps and arrays).
- */
-
-/**
- * \fn bool cbor_value_is_text_string(const CborValue *value)
- *
- * Returns true if the iterator \a value is valid and points to a CBOR text
- * string. CBOR text strings are UTF-8 encoded and usually contain
- * human-readable text.
- *
- * \sa cbor_value_is_valid(), cbor_value_get_string_length(), cbor_value_calculate_string_length(),
- *     cbor_value_copy_text_string(), cbor_value_dup_text_string()
- */
-
-/**
- * \fn bool cbor_value_is_byte_string(const CborValue *value)
- *
- * Returns true if the iterator \a value is valid and points to a CBOR text
- * string. CBOR byte strings are binary data with no specified encoding or
- * format.
- *
- * \sa cbor_value_is_valid(), cbor_value_get_string_length(), cbor_value_calculate_string_length(),
- *     cbor_value_copy_byte_string(), cbor_value_dup_byte_string()
- */
-
-/**
- * \fn CborError cbor_value_get_string_length(const CborValue *value, size_t *length)
- *
- * Extracts the length of the byte or text string that \a value points to and
- * stores it in \a result. If the iterator \a value does not point to a text
- * string or a byte string, the behaviour is undefined, so checking with \ref
- * cbor_value_get_type, with \ref cbor_value_is_text_string or \ref
- * cbor_value_is_byte_string is recommended.
- *
- * If the length of this string is not encoded in the CBOR data stream, this
- * function will return the recoverable error CborErrorUnknownLength. You may
- * also check whether that is the case by using cbor_value_is_length_known().
- *
- * If the length of the string is required but the length was not encoded, use
- * cbor_value_calculate_string_length(), but note that that function does not
- * run in constant time.
- *
- * \note On 32-bit platforms, this function will return error condition of \ref
- * CborErrorDataTooLarge if the stream indicates a length that is too big to
- * fit in 32-bit.
- *
- * \sa cbor_value_is_valid(), cbor_value_is_length_known(), cbor_value_calculate_string_length()
- */
-
-/**
- * Calculates the length of the byte or text string that \a value points to and
- * stores it in \a len. If the iterator \a value does not point to a text
- * string or a byte string, the behaviour is undefined, so checking with \ref
- * cbor_value_get_type, with \ref cbor_value_is_text_string or \ref
- * cbor_value_is_byte_string is recommended.
- *
- * This function is different from cbor_value_get_string_length() in that it
- * calculates the length even for strings sent in chunks. For that reason, this
- * function may not run in constant time (it will run in O(n) time on the
- * number of chunks). It does use constant memory (O(1)).
- *
- * \note On 32-bit platforms, this function will return error condition of \ref
- * CborErrorDataTooLarge if the stream indicates a length that is too big to
- * fit in 32-bit.
- *
- * \sa cbor_value_get_string_length(), cbor_value_copy_string(), cbor_value_is_length_known()
- */
-CborError cbor_value_calculate_string_length(const CborValue *value, size_t *len)
-{
-    *len = SIZE_MAX;
-    return _cbor_value_copy_string(value, NULL, len, NULL);
-}
-
-/* We return uintptr_t so that we can pass memcpy directly as the iteration
- * function. The choice is to optimize for memcpy, which is used in the base
- * parser API (cbor_value_copy_string), while memcmp is used in convenience API
- * only. */
-typedef uintptr_t (*IterateFunction)(char *, const uint8_t *, size_t);
-
-static uintptr_t iterate_noop(char *dest, const uint8_t *src, size_t len)
-{
-    (void)dest;
-    (void)src;
-    (void)len;
-    return true;
-}
-
-static uintptr_t iterate_memcmp(char *s1, const uint8_t *s2, size_t len)
-{
-    return memcmp(s1, (const char *)s2, len) == 0;
-}
-
-static CborError iterate_string_chunks(const CborValue *value, char *buffer, size_t *buflen,
-                                       bool *result, CborValue *next, IterateFunction func)
-{
-    assert(cbor_value_is_byte_string(value) || cbor_value_is_text_string(value));
-
-    size_t total;
-    CborError err;
-    const uint8_t *ptr = value->ptr;
-    if (cbor_value_is_length_known(value)) {
-        /* easy case: fixed length */
-        err = extract_length(value->parser, &ptr, &total);
-        if (err)
-            return err;
-        if (total > (size_t)(value->parser->end - ptr))
-            return CborErrorUnexpectedEOF;
-        if (total <= *buflen)
-            *result = !!func(buffer, ptr, total);
-        else
-            *result = false;
-        ptr += total;
-    } else {
-        /* chunked */
-        ++ptr;
-        total = 0;
-        *result = true;
-        while (true) {
-            size_t chunkLen;
-            size_t newTotal;
-
-            if (ptr == value->parser->end)
-                return CborErrorUnexpectedEOF;
-
-            if (*ptr == (uint8_t)BreakByte) {
-                ++ptr;
-                break;
-            }
-
-            /* is this the right type? */
-            if ((*ptr & MajorTypeMask) != value->type)
-                return CborErrorIllegalType;
-
-            err = extract_length(value->parser, &ptr, &chunkLen);
-            if (err)
-                return err;
-
-            if (unlikely(add_check_overflow(total, chunkLen, &newTotal)))
-                return CborErrorDataTooLarge;
-
-            if (chunkLen > (size_t)(value->parser->end - ptr))
-                return CborErrorUnexpectedEOF;
-
-            if (*result && *buflen >= newTotal)
-                *result = !!func(buffer + total, ptr, chunkLen);
-            else
-                *result = false;
-
-            ptr += chunkLen;
-            total = newTotal;
-        }
-    }
-
-    /* is there enough room for the ending NUL byte? */
-    if (*result && *buflen > total)
-        *result = !!func(buffer + total, (const uint8_t *)"", 1);
-    *buflen = total;
-
-    if (next) {
-        *next = *value;
-        next->ptr = ptr;
-        return preparse_next_value(next);
-    }
-    return CborNoError;
-}
-
-/**
- * \fn CborError cbor_value_copy_text_string(const CborValue *value, char *buffer, size_t *buflen, CborValue *next)
- *
- * Copies the string pointed by \a value into the buffer provided at \a buffer
- * of \a buflen bytes. If \a buffer is a NULL pointer, this function will not
- * copy anything and will only update the \a next value.
- *
- * If the iterator \a value does not point to a text string, the behaviour is
- * undefined, so checking with \ref cbor_value_get_type or \ref
- * cbor_value_is_text_string is recommended.
- *
- * If the provided buffer length was too small, this function returns an error
- * condition of \ref CborErrorOutOfMemory. If you need to calculate the length
- * of the string in order to preallocate a buffer, use
- * cbor_value_calculate_string_length().
- *
- * On success, this function sets the number of bytes copied to \c{*buflen}. If
- * the buffer is large enough, this function will insert a null byte after the
- * last copied byte, to facilitate manipulation of text strings. That byte is
- * not included in the returned value of \c{*buflen}.
- *
- * The \a next pointer, if not null, will be updated to point to the next item
- * after this string. If \a value points to the last item, then \a next will be
- * invalid.
- *
- * This function may not run in constant time (it will run in O(n) time on the
- * number of chunks). It requires constant memory (O(1)).
- *
- * \note This function does not perform UTF-8 validation on the incoming text
- * string.
- *
- * \sa cbor_value_dup_text_string(), cbor_value_copy_byte_string(), cbor_value_get_string_length(), cbor_value_calculate_string_length()
- */
-
-/**
- * \fn CborError cbor_value_copy_byte_string(const CborValue *value, uint8_t *buffer, size_t *buflen, CborValue *next)
- *
- * Copies the string pointed by \a value into the buffer provided at \a buffer
- * of \a buflen bytes. If \a buffer is a NULL pointer, this function will not
- * copy anything and will only update the \a next value.
- *
- * If the iterator \a value does not point to a byte string, the behaviour is
- * undefined, so checking with \ref cbor_value_get_type or \ref
- * cbor_value_is_byte_string is recommended.
- *
- * If the provided buffer length was too small, this function returns an error
- * condition of \ref CborErrorOutOfMemory. If you need to calculate the length
- * of the string in order to preallocate a buffer, use
- * cbor_value_calculate_string_length().
- *
- * On success, this function sets the number of bytes copied to \c{*buflen}. If
- * the buffer is large enough, this function will insert a null byte after the
- * last copied byte, to facilitate manipulation of null-terminated strings.
- * That byte is not included in the returned value of \c{*buflen}.
- *
- * The \a next pointer, if not null, will be updated to point to the next item
- * after this string. If \a value points to the last item, then \a next will be
- * invalid.
- *
- * This function may not run in constant time (it will run in O(n) time on the
- * number of chunks). It requires constant memory (O(1)).
- *
- * \sa cbor_value_dup_text_string(), cbor_value_copy_text_string(), cbor_value_get_string_length(), cbor_value_calculate_string_length()
- */
-
-CborError _cbor_value_copy_string(const CborValue *value, void *buffer,
-                                 size_t *buflen, CborValue *next)
-{
-    bool copied_all;
-    CborError err = iterate_string_chunks(value, (char*)buffer, buflen, &copied_all, next,
-                                          buffer ? (IterateFunction)memcpy : iterate_noop);
-    return err ? err :
-                 copied_all ? CborNoError : CborErrorOutOfMemory;
-}
-
-/**
- * Compares the entry \a value with the string \a string and store the result
- * in \a result. If the value is different from \a string \a result will
- * contain \c false.
- *
- * The entry at \a value may be a tagged string. If \a is not a string or a
- * tagged string, the comparison result will be false.
- *
- * CBOR requires text strings to be encoded in UTF-8, but this function does
- * not validate either the strings in the stream or the string \a string to be
- * matched. Moreover, comparison is done on strict codepoint comparison,
- * without any Unicode normalization.
- *
- * This function may not run in constant time (it will run in O(n) time on the
- * number of chunks). It requires constant memory (O(1)).
- *
- * \sa cbor_value_skip_tag(), cbor_value_copy_text_string()
- */
-CborError cbor_value_text_string_equals(const CborValue *value, const char *string, bool *result)
-{
-    CborValue copy = *value;
-    CborError err = cbor_value_skip_tag(&copy);
-    if (err)
-        return err;
-    if (!cbor_value_is_text_string(&copy)) {
-        *result = false;
-        return CborNoError;
-    }
-
-    size_t len = strlen(string);
-    return iterate_string_chunks(&copy, CONST_CAST(char *, string), &len, result, NULL, iterate_memcmp);
-}
-
-/**
- * \fn bool cbor_value_is_array(const CborValue *value)
- *
- * Returns true if the iterator \a value is valid and points to a CBOR array.
- *
- * \sa cbor_value_is_valid(), cbor_value_is_map()
- */
-
-/**
- * \fn CborError cbor_value_get_array_length(const CborValue *value, size_t *length)
- *
- * Extracts the length of the CBOR array that \a value points to and stores it
- * in \a result. If the iterator \a value does not point to a CBOR array, the
- * behaviour is undefined, so checking with \ref cbor_value_get_type or \ref
- * cbor_value_is_array is recommended.
- *
- * If the length of this array is not encoded in the CBOR data stream, this
- * function will return the recoverable error CborErrorUnknownLength. You may
- * also check whether that is the case by using cbor_value_is_length_known().
- *
- * \note On 32-bit platforms, this function will return error condition of \ref
- * CborErrorDataTooLarge if the stream indicates a length that is too big to
- * fit in 32-bit.
- *
- * \sa cbor_value_is_valid(), cbor_value_is_length_known()
- */
-
-/**
- * \fn bool cbor_value_is_map(const CborValue *value)
- *
- * Returns true if the iterator \a value is valid and points to a CBOR map.
- *
- * \sa cbor_value_is_valid(), cbor_value_is_array()
- */
-
-/**
- * \fn CborError cbor_value_get_map_length(const CborValue *value, size_t *length)
- *
- * Extracts the length of the CBOR map that \a value points to and stores it in
- * \a result. If the iterator \a value does not point to a CBOR map, the
- * behaviour is undefined, so checking with \ref cbor_value_get_type or \ref
- * cbor_value_is_map is recommended.
- *
- * If the length of this map is not encoded in the CBOR data stream, this
- * function will return the recoverable error CborErrorUnknownLength. You may
- * also check whether that is the case by using cbor_value_is_length_known().
- *
- * \note On 32-bit platforms, this function will return error condition of \ref
- * CborErrorDataTooLarge if the stream indicates a length that is too big to
- * fit in 32-bit.
- *
- * \sa cbor_value_is_valid(), cbor_value_is_length_known()
- */
-
-/**
- * Attempts to find the value in map \a map that corresponds to the text string
- * entry \a string. If the iterator \a value does not point to a CBOR map, the
- * behaviour is undefined, so checking with \ref cbor_value_get_type or \ref
- * cbor_value_is_map is recommended.
- *
- * If the item is found, it is stored in \a result. If no item is found
- * matching the key, then \a result will contain an element of type \ref
- * CborInvalidType. Matching is performed using
- * cbor_value_text_string_equals(), so tagged strings will also match.
- *
- * This function has a time complexity of O(n) where n is the number of
- * elements in the map to be searched. In addition, this function is has O(n)
- * memory requirement based on the number of nested containers (maps or arrays)
- * found as elements of this map.
- *
- * \sa cbor_value_is_valid(), cbor_value_text_string_equals(), cbor_value_advance()
- */
-CborError cbor_value_map_find_value(const CborValue *map, const char *string, CborValue *element)
-{
-    assert(cbor_value_is_map(map));
-    size_t len = strlen(string);
-    CborError err = cbor_value_enter_container(map, element);
-    if (err)
-        goto error;
-
-    while (!cbor_value_at_end(element)) {
-        /* find the non-tag so we can compare */
-        err = cbor_value_skip_tag(element);
-        if (err)
-            goto error;
-        if (cbor_value_is_text_string(element)) {
-            bool equals;
-            size_t dummyLen = len;
-            err = iterate_string_chunks(element, CONST_CAST(char *, string), &dummyLen,
-                                        &equals, element, iterate_memcmp);
-            if (err)
-                goto error;
-            if (equals)
-                return preparse_value(element);
-        } else {
-            /* skip this key */
-            err = cbor_value_advance(element);
-            if (err)
-                goto error;
-        }
-
-        /* skip this value */
-        err = cbor_value_skip_tag(element);
-        if (err)
-            goto error;
-        err = cbor_value_advance(element);
-        if (err)
-            goto error;
-    }
-
-    /* not found */
-    element->type = CborInvalidType;
-    return CborNoError;
-
-error:
-    element->type = CborInvalidType;
-    return err;
-}
-
-/**
- * \fn bool cbor_value_is_float(const CborValue *value)
- *
- * Returns true if the iterator \a value is valid and points to a CBOR
- * single-precision floating point (32-bit).
- *
- * \sa cbor_value_is_valid(), cbor_value_is_double(), cbor_value_is_half_float()
- */
-
-/**
- * \fn CborError cbor_value_get_float(const CborValue *value, float *result)
- *
- * Retrieves the CBOR single-precision floating point (32-bit) value that \a
- * value points to and stores it in \a result. If the iterator \a value does
- * not point to a single-precision floating point value, the behavior is
- * undefined, so checking with \ref cbor_value_get_type or with \ref
- * cbor_value_is_float is recommended.
- *
- * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_float(), cbor_value_get_double()
- */
-
-/**
- * \fn bool cbor_value_is_double(const CborValue *value)
- *
- * Returns true if the iterator \a value is valid and points to a CBOR
- * double-precision floating point (64-bit).
- *
- * \sa cbor_value_is_valid(), cbor_value_is_float(), cbor_value_is_half_float()
- */
-
-/**
- * \fn CborError cbor_value_get_double(const CborValue *value, float *result)
- *
- * Retrieves the CBOR double-precision floating point (64-bit) value that \a
- * value points to and stores it in \a result. If the iterator \a value does
- * not point to a double-precision floating point value, the behavior is
- * undefined, so checking with \ref cbor_value_get_type or with \ref
- * cbor_value_is_double is recommended.
- *
- * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_double(), cbor_value_get_float()
- */
-
-/**
- * \fn bool cbor_value_is_half_float(const CborValue *value)
- *
- * Returns true if the iterator \a value is valid and points to a CBOR
- * single-precision floating point (16-bit).
- *
- * \sa cbor_value_is_valid(), cbor_value_is_double(), cbor_value_is_float()
- */
-
-/**
- * Retrieves the CBOR half-precision floating point (16-bit) value that \a
- * value points to and stores it in \a result. If the iterator \a value does
- * not point to a half-precision floating point value, the behavior is
- * undefined, so checking with \ref cbor_value_get_type or with \ref
- * cbor_value_is_half_float is recommended.
- *
- * Note: since the C language does not have a standard type for half-precision
- * floating point, this function takes a \c{void *} as a parameter for the
- * storage area, which must be at least 16 bits wide.
- *
- * \sa cbor_value_get_type(), cbor_value_is_valid(), cbor_value_is_half_float(), cbor_value_get_float()
- */
-CborError cbor_value_get_half_float(const CborValue *value, void *result)
-{
-    assert(cbor_value_is_half_float(value));
-
-    /* size has been computed already */
-    uint16_t v = get16(value->ptr + 1);
-    memcpy(result, &v, sizeof(v));
-    return CborNoError;
-}
-
-/** @} */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/tinycbor/src/cborparser_dup_string.c
----------------------------------------------------------------------
diff --git a/libs/tinycbor/src/cborparser_dup_string.c b/libs/tinycbor/src/cborparser_dup_string.c
deleted file mode 100644
index 60dbdbe..0000000
--- a/libs/tinycbor/src/cborparser_dup_string.c
+++ /dev/null
@@ -1,113 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 Intel Corporation
-**
-** Permission is hereby granted, free of charge, to any person obtaining a copy
-** of this software and associated documentation files (the "Software"), to deal
-** in the Software without restriction, including without limitation the rights
-** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-** copies of the Software, and to permit persons to whom the Software is
-** furnished to do so, subject to the following conditions:
-**
-** The above copyright notice and this permission notice shall be included in
-** all copies or substantial portions of the Software.
-**
-** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-** THE SOFTWARE.
-**
-****************************************************************************/
-
-#define _BSD_SOURCE 1
-#define _DEFAULT_SOURCE 1
-#ifndef __STDC_LIMIT_MACROS
-#  define __STDC_LIMIT_MACROS 1
-#endif
-
-#include "cbor.h"
-#include <stdlib.h>
-
-/**
- * \fn CborError cbor_value_dup_text_string(const CborValue *value, char **buffer, size_t *buflen, CborValue *next)
- *
- * Allocates memory for the string pointed by \a value and copies it into this
- * buffer. The pointer to the buffer is stored in \a buffer and the number of
- * bytes copied is stored in \a len (those variables must not be NULL).
- *
- * If the iterator \a value does not point to a text string, the behaviour is
- * undefined, so checking with \ref cbor_value_get_type or \ref
- * cbor_value_is_text_string is recommended.
- *
- * If \c malloc returns a NULL pointer, this function will return error
- * condition \ref CborErrorOutOfMemory.
- *
- * On success, \c{*buffer} will contain a valid pointer that must be freed by
- * calling \c{free()}. This is the case even for zero-length strings.
- *
- * The \a next pointer, if not null, will be updated to point to the next item
- * after this string. If \a value points to the last item, then \a next will be
- * invalid.
- *
- * This function may not run in constant time (it will run in O(n) time on the
- * number of chunks). It requires constant memory (O(1)) in addition to the
- * malloc'ed block.
- *
- * \note This function does not perform UTF-8 validation on the incoming text
- * string.
- *
- * \sa cbor_value_copy_text_string(), cbor_value_dup_byte_string()
- */
-
-/**
- * \fn CborError cbor_value_dup_byte_string(const CborValue *value, uint8_t **buffer, size_t *buflen, CborValue *next)
- *
- * Allocates memory for the string pointed by \a value and copies it into this
- * buffer. The pointer to the buffer is stored in \a buffer and the number of
- * bytes copied is stored in \a len (those variables must not be NULL).
- *
- * If the iterator \a value does not point to a byte string, the behaviour is
- * undefined, so checking with \ref cbor_value_get_type or \ref
- * cbor_value_is_byte_string is recommended.
- *
- * If \c malloc returns a NULL pointer, this function will return error
- * condition \ref CborErrorOutOfMemory.
- *
- * On success, \c{*buffer} will contain a valid pointer that must be freed by
- * calling \c{free()}. This is the case even for zero-length strings.
- *
- * The \a next pointer, if not null, will be updated to point to the next item
- * after this string. If \a value points to the last item, then \a next will be
- * invalid.
- *
- * This function may not run in constant time (it will run in O(n) time on the
- * number of chunks). It requires constant memory (O(1)) in addition to the
- * malloc'ed block.
- *
- * \sa cbor_value_copy_byte_string(), cbor_value_dup_text_string()
- */
-CborError _cbor_value_dup_string(const CborValue *value, void **buffer, size_t *buflen, CborValue *next)
-{
-    assert(buffer);
-    assert(buflen);
-    *buflen = SIZE_MAX;
-    CborError err = _cbor_value_copy_string(value, NULL, buflen, NULL);
-    if (err)
-        return err;
-
-    ++*buflen;
-    *buffer = malloc(*buflen);
-    if (!*buffer) {
-        /* out of memory */
-        return CborErrorOutOfMemory;
-    }
-    err = _cbor_value_copy_string(value, *buffer, buflen, next);
-    if (err) {
-        free(*buffer);
-        return err;
-    }
-    return CborNoError;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/tinycbor/src/cborpretty.c
----------------------------------------------------------------------
diff --git a/libs/tinycbor/src/cborpretty.c b/libs/tinycbor/src/cborpretty.c
deleted file mode 100644
index e8e7316..0000000
--- a/libs/tinycbor/src/cborpretty.c
+++ /dev/null
@@ -1,470 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 Intel Corporation
-**
-** Permission is hereby granted, free of charge, to any person obtaining a copy
-** of this software and associated documentation files (the "Software"), to deal
-** in the Software without restriction, including without limitation the rights
-** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-** copies of the Software, and to permit persons to whom the Software is
-** furnished to do so, subject to the following conditions:
-**
-** The above copyright notice and this permission notice shall be included in
-** all copies or substantial portions of the Software.
-**
-** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-** THE SOFTWARE.
-**
-****************************************************************************/
-
-#define _BSD_SOURCE 1
-#define _DEFAULT_SOURCE 1
-#ifndef __STDC_LIMIT_MACROS
-#  define __STDC_LIMIT_MACROS 1
-#endif
-
-#include "cbor.h"
-#include "compilersupport_p.h"
-#include "math_support_p.h"
-
-#include <float.h>
-#include <inttypes.h>
-#include <math.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-/**
- * \defgroup CborPretty Converting CBOR to text
- * \brief Group of functions used to convert CBOR to text form.
- *
- * This group contains two functions that are can be used to convert one
- * CborValue object to a text representation. This module attempts to follow
- * the recommendations from RFC 7049 section 6 "Diagnostic Notation", though it
- * has a few differences. They are noted below.
- *
- * TinyCBOR does not provide a way to convert from the text representation back
- * to encoded form. To produce a text form meant to be parsed, CborToJson is
- * recommended instead.
- *
- * Either of the functions in this section will attempt to convert exactly one
- * CborValue object to text. Those functions may return any error documented
- * for the functions for CborParsing. In addition, if the C standard library
- * stream functions return with error, the text conversion will return with
- * error CborErrorIO.
- *
- * These functions also perform UTF-8 validation in CBOR text strings. If they
- * encounter a sequence of bytes that not permitted in UTF-8, they will return
- * CborErrorInvalidUtf8TextString. That includes encoding of surrogate points
- * in UTF-8.
- *
- * \warning The output type produced by these functions is not guaranteed to
- * remain stable. A future update of TinyCBOR may produce different output for
- * the same input and parsers may be unable to handle them.
- *
- * \sa CborParsing, CborToJson, cbor_parser_init()
- */
-
-/**
- * \addtogroup CborPretty
- * @{
- * <h2 class="groupheader">Text format</h2>
- *
- * As described in RFC 7049 section 6 "Diagnostic Notation", the format is
- * largely borrowed from JSON, but modified to suit CBOR's different data
- * types. TinyCBOR makes further modifications to distinguish different, but
- * similar values.
- *
- * CBOR values are currently encoded as follows:
- * \par Integrals (unsigned and negative)
- *      Base-10 (decimal) text representation of the value
- * \par Byte strings:
- *      <tt>"h'"</tt> followed by the Base16 (hex) representation of the binary data, followed by an ending quote (')
- * \par Text strings:
- *      C-style escaped string in quotes, with C11/C++11 escaping of Unicode codepoints above U+007F.
- * \par Tags:
- *      Tag value, with the tagged value in parentheses. No special encoding of the tagged value is performed.
- * \par Simple types:
- *      <tt>"simple(nn)"</tt> where \c nn is the simple value
- * \par Null:
- *      \c null
- * \par Undefined:
- *      \c undefined
- * \par Booleans:
- *      \c true or \c false
- * \par Floating point:
- *      If NaN or infinite, the actual words \c NaN or \c infinite.
- *      Otherwise, the decimal representation with as many digits as necessary to ensure no loss of information,
- *      with float values suffixed by "f" and half-float values suffixed by "f16" (doubles have no suffix). A dot is always present.
- * \par Arrays:
- *      Comma-separated list of elements, enclosed in square brackets ("[" and "]").
- *     If the array length is indeterminate, an underscore ("_") appears immediately after the opening bracket.
- * \par Maps:
- *      Comma-separated list of key-value pairs, with the key and value separated
- *      by a colon (":"), enclosed in curly braces ("{" and "}").
- *      If the map length is indeterminate, an underscore ("_") appears immediately after the opening brace.
- */
-
-static int hexDump(FILE *out, const uint8_t *buffer, size_t n)
-{
-    while (n--) {
-        int r = fprintf(out, "%02" PRIx8, *buffer++);
-        if (r < 0)
-            return r;
-    }
-    return 0;   /* should be n * 2, but we don't have the original n anymore */
-}
-
-/* This function decodes buffer as UTF-8 and prints as escaped UTF-16.
- * On UTF-8 decoding error, it returns CborErrorInvalidUtf8TextString */
-static int utf8EscapedDump(FILE *out, const char *buffer, size_t n)
-{
-    uint32_t uc;
-    while (n--) {
-        uc = (uint8_t)*buffer++;
-        if (uc < 0x80) {
-            /* single-byte UTF-8 */
-            if (uc < 0x7f && uc >= 0x20 && uc != '\\' && uc != '"') {
-                if (fprintf(out, "%c", (char)uc) < 0)
-                    return CborErrorIO;
-                continue;
-            }
-
-            /* print as an escape sequence */
-            char escaped = (char)uc;
-            switch (uc) {
-            case '"':
-            case '\\':
-                break;
-            case '\b':
-                escaped = 'b';
-                break;
-            case '\f':
-                escaped = 'f';
-                break;
-            case '\n':
-                escaped = 'n';
-                break;
-            case '\r':
-                escaped = 'r';
-                break;
-            case '\t':
-                escaped = 't';
-                break;
-            default:
-                goto print_utf16;
-            }
-            if (fprintf(out, "\\%c", escaped) < 0)
-                return CborErrorIO;
-            continue;
-        }
-
-        /* multi-byte UTF-8, decode it */
-        unsigned charsNeeded;
-        uint32_t min_uc;
-        if (unlikely(uc <= 0xC1))
-            return CborErrorInvalidUtf8TextString;
-        if (uc < 0xE0) {
-            /* two-byte UTF-8 */
-            charsNeeded = 2;
-            min_uc = 0x80;
-            uc &= 0x1f;
-        } else if (uc < 0xF0) {
-            /* three-byte UTF-8 */
-            charsNeeded = 3;
-            min_uc = 0x800;
-            uc &= 0x0f;
-        } else if (uc < 0xF5) {
-            /* four-byte UTF-8 */
-            charsNeeded = 4;
-            min_uc = 0x10000;
-            uc &= 0x07;
-        } else {
-            return CborErrorInvalidUtf8TextString;
-        }
-
-        if (n < charsNeeded - 1)
-            return CborErrorInvalidUtf8TextString;
-
-        /* first continuation character */
-        uint8_t b = (uint8_t)*buffer++;
-        if ((b & 0xc0) != 0x80)
-            return CborErrorInvalidUtf8TextString;
-        uc <<= 6;
-        uc |= b & 0x3f;
-
-        if (charsNeeded > 2) {
-            /* second continuation character */
-            b = (uint8_t)*buffer++;
-            if ((b & 0xc0) != 0x80)
-                return CborErrorInvalidUtf8TextString;
-            uc <<= 6;
-            uc |= b & 0x3f;
-
-            if (charsNeeded > 3) {
-                /* third continuation character */
-                b = (uint8_t)*buffer++;
-                if ((b & 0xc0) != 0x80)
-                    return CborErrorInvalidUtf8TextString;
-                uc <<= 6;
-                uc |= b & 0x3f;
-            }
-        }
-
-        /* overlong sequence? surrogate pair? out or range? */
-        if (uc < min_uc || uc - 0xd800U < 2048U || uc > 0x10ffff)
-            return CborErrorInvalidUtf8TextString;
-
-        /* now print the sequence */
-        if (charsNeeded > 3) {
-            /* needs surrogate pairs */
-            if (fprintf(out, "\\u%04" PRIX32 "\\u%04" PRIX32,
-                        (uc >> 10) + 0xd7c0,    /* high surrogate */
-                        (uc % 0x0400) + 0xdc00) < 0)
-                return CborErrorIO;
-        } else {
-print_utf16:
-            /* no surrogate pair needed */
-            if (fprintf(out, "\\u%04" PRIX32, uc) < 0)
-                return CborErrorIO;
-        }
-    }
-    return CborNoError;
-}
-
-static CborError value_to_pretty(FILE *out, CborValue *it);
-static CborError container_to_pretty(FILE *out, CborValue *it, CborType containerType)
-{
-    const char *comma = "";
-    while (!cbor_value_at_end(it)) {
-        if (fprintf(out, "%s", comma) < 0)
-            return CborErrorIO;
-        comma = ", ";
-
-        CborError err = value_to_pretty(out, it);
-        if (err)
-            return err;
-
-        if (containerType == CborArrayType)
-            continue;
-
-        /* map: that was the key, so get the value */
-        if (fprintf(out, ": ") < 0)
-            return CborErrorIO;
-        err = value_to_pretty(out, it);
-        if (err)
-            return err;
-    }
-    return CborNoError;
-}
-
-static CborError value_to_pretty(FILE *out, CborValue *it)
-{
-    CborError err;
-    CborType type = cbor_value_get_type(it);
-    switch (type) {
-    case CborArrayType:
-    case CborMapType: {
-        /* recursive type */
-        CborValue recursed;
-
-        if (fprintf(out, type == CborArrayType ? "[" : "{") < 0)
-            return CborErrorIO;
-        if (!cbor_value_is_length_known(it)) {
-            if (fprintf(out, "_ ") < 0)
-                return CborErrorIO;
-        }
-
-        err = cbor_value_enter_container(it, &recursed);
-        if (err) {
-            it->ptr = recursed.ptr;
-            return err;       /* parse error */
-        }
-        err = container_to_pretty(out, &recursed, type);
-        if (err) {
-            it->ptr = recursed.ptr;
-            return err;       /* parse error */
-        }
-        err = cbor_value_leave_container(it, &recursed);
-        if (err)
-            return err;       /* parse error */
-
-        if (fprintf(out, type == CborArrayType ? "]" : "}") < 0)
-            return CborErrorIO;
-        return CborNoError;
-    }
-
-    case CborIntegerType: {
-        uint64_t val;
-        cbor_value_get_raw_integer(it, &val);    /* can't fail */
-
-        if (cbor_value_is_unsigned_integer(it)) {
-            if (fprintf(out, "%" PRIu64, val) < 0)
-                return CborErrorIO;
-        } else {
-            /* CBOR stores the negative number X as -1 - X
-             * (that is, -1 is stored as 0, -2 as 1 and so forth) */
-            if (++val) {                /* unsigned overflow may happen */
-                if (fprintf(out, "-%" PRIu64, val) < 0)
-                    return CborErrorIO;
-            } else {
-                /* overflown
-                 *   0xffff`ffff`ffff`ffff + 1 =
-                 * 0x1`0000`0000`0000`0000 = 18446744073709551616 (2^64) */
-                if (fprintf(out, "-18446744073709551616") < 0)
-                    return CborErrorIO;
-            }
-        }
-        break;
-    }
-
-    case CborByteStringType:{
-        size_t n = 0;
-        uint8_t *buffer;
-        err = cbor_value_dup_byte_string(it, &buffer, &n, it);
-        if (err)
-            return err;
-
-        bool failed = fprintf(out, "h'") < 0 || hexDump(out, buffer, n) < 0 || fprintf(out, "'") < 0;
-        free(buffer);
-        return failed ? CborErrorIO : CborNoError;
-    }
-
-    case CborTextStringType: {
-        size_t n = 0;
-        char *buffer;
-        err = cbor_value_dup_text_string(it, &buffer, &n, it);
-        if (err)
-            return err;
-
-        err = CborNoError;
-        bool failed = fprintf(out, "\"") < 0
-                      || (err = utf8EscapedDump(out, buffer, n)) != CborNoError
-                      || fprintf(out, "\"") < 0;
-        free(buffer);
-        return err != CborNoError ? err :
-                                    failed ? CborErrorIO : CborNoError;
-    }
-
-    case CborTagType: {
-        CborTag tag;
-        cbor_value_get_tag(it, &tag);       /* can't fail */
-        if (fprintf(out, "%" PRIu64 "(", tag) < 0)
-            return CborErrorIO;
-        err = cbor_value_advance_fixed(it);
-        if (err)
-            return err;
-        err = value_to_pretty(out, it);
-        if (err)
-            return err;
-        if (fprintf(out, ")") < 0)
-            return CborErrorIO;
-        return CborNoError;
-    }
-
-    case CborSimpleType: {
-        uint8_t simple_type;
-        cbor_value_get_simple_type(it, &simple_type);  /* can't fail */
-        if (fprintf(out, "simple(%" PRIu8 ")", simple_type) < 0)
-            return CborErrorIO;
-        break;
-    }
-
-    case CborNullType:
-        if (fprintf(out, "null") < 0)
-            return CborErrorIO;
-        break;
-
-    case CborUndefinedType:
-        if (fprintf(out, "undefined") < 0)
-            return CborErrorIO;
-        break;
-
-    case CborBooleanType: {
-        bool val;
-        cbor_value_get_boolean(it, &val);       /* can't fail */
-        if (fprintf(out, val ? "true" : "false") < 0)
-            return CborErrorIO;
-        break;
-    }
-
-    case CborDoubleType: {
-        const char *suffix;
-        double val;
-        if (false) {
-            float f;
-    case CborFloatType:
-            cbor_value_get_float(it, &f);
-            val = f;
-            suffix = "f";
-        } else if (false) {
-            uint16_t f16;
-    case CborHalfFloatType:
-            cbor_value_get_half_float(it, &f16);
-            val = decode_half(f16);
-            suffix = "f16";
-        } else {
-            cbor_value_get_double(it, &val);
-            suffix = "";
-        }
-
-        int r = fpclassify(val);
-        if (r == FP_NAN || r == FP_INFINITE)
-            suffix = "";
-
-        uint64_t ival = (uint64_t)fabs(val);
-        if (ival == fabs(val)) {
-            /* this double value fits in a 64-bit integer, so show it as such
-             * (followed by a floating point suffix, to disambiguate) */
-            r = fprintf(out, "%s%" PRIu64 ".%s", val < 0 ? "-" : "", ival, suffix);
-        } else {
-            /* this number is definitely not a 64-bit integer */
-            r = fprintf(out, "%." DBL_DECIMAL_DIG_STR "g%s", val, suffix);
-        }
-        if (r < 0)
-            return CborErrorIO;
-        break;
-    }
-
-    case CborInvalidType:
-        if (fprintf(out, "invalid") < 0)
-            return CborErrorIO;
-        return CborErrorUnknownType;
-    }
-
-    err = cbor_value_advance_fixed(it);
-    return err;
-}
-
-/**
- * \fn CborError cbor_value_to_pretty(FILE *out, const CborValue *value)
- *
- * Converts the current CBOR type pointed by \a value to its textual
- * representation and writes it to the \a out stream. If an error occurs, this
- * function returns an error code similar to CborParsing.
- *
- * \sa cbor_value_to_pretty_advance(), cbor_value_to_json_advance()
- */
-
-/**
- * Converts the current CBOR type pointed by \a value to its textual
- * representation and writes it to the \a out stream. If an error occurs, this
- * function returns an error code similar to CborParsing.
- *
- * If no error ocurred, this function advances \a value to the next element.
- * Often, concatenating the text representation of multiple elements can be
- * done by appending a comma to the output stream.
- *
- * \sa cbor_value_to_pretty(), cbor_value_to_json_advance()
- */
-CborError cbor_value_to_pretty_advance(FILE *out, CborValue *value)
-{
-    return value_to_pretty(out, value);
-}
-
-/** @} */


[19/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/loslib.c.donotcompile
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/loslib.c.donotcompile b/libs/elua/elua_base/src/loslib.c.donotcompile
deleted file mode 100644
index 1139cb6..0000000
--- a/libs/elua/elua_base/src/loslib.c.donotcompile
+++ /dev/null
@@ -1,247 +0,0 @@
-/*
-** $Id: loslib.c,v 1.19.1.3 2008/01/18 16:38:18 roberto Exp $
-** Standard Operating System library
-** See Copyright Notice in lua.h
-*/
-
-
-#include <errno.h>
-#include <locale.h>
-#include <stdlib.h>
-#include <string.h>
-#include <time.h>
-
-#define loslib_c
-#define LUA_LIB
-
-#include "lua.h"
-
-#include "lauxlib.h"
-#include "lualib.h"
-#include "lrotable.h"
-
-
-static int os_pushresult (lua_State *L, int i, const char *filename) {
-  int en = errno;  /* calls to Lua API may change this value */
-  if (i) {
-    lua_pushboolean(L, 1);
-    return 1;
-  }
-  else {
-    lua_pushnil(L);
-    lua_pushfstring(L, "%s: %s", filename, strerror(en));
-    lua_pushinteger(L, en);
-    return 3;
-  }
-}
-
-
-static int os_execute (lua_State *L) {
-  lua_pushinteger(L, system(luaL_optstring(L, 1, NULL)));
-  return 1;
-}
-
-
-static int os_remove (lua_State *L) {
-  const char *filename = luaL_checkstring(L, 1);
-  return os_pushresult(L, remove(filename) == 0, filename);
-}
-
-
-static int os_rename (lua_State *L) {
-  const char *fromname = luaL_checkstring(L, 1);
-  const char *toname = luaL_checkstring(L, 2);
-  return os_pushresult(L, rename(fromname, toname) == 0, fromname);
-}
-
-
-static int os_tmpname (lua_State *L) {
-  char buff[LUA_TMPNAMBUFSIZE];
-  int err;
-  lua_tmpnam(buff, err);
-  if (err)
-    return luaL_error(L, "unable to generate a unique filename");
-  lua_pushstring(L, buff);
-  return 1;
-}
-
-
-static int os_getenv (lua_State *L) {
-  lua_pushstring(L, getenv(luaL_checkstring(L, 1)));  /* if NULL push nil */
-  return 1;
-}
-
-
-static int os_clock (lua_State *L) {
-  lua_pushnumber(L, ((lua_Number)clock())/(lua_Number)CLOCKS_PER_SEC);
-  return 1;
-}
-
-
-/*
-** {======================================================
-** Time/Date operations
-** { year=%Y, month=%m, day=%d, hour=%H, min=%M, sec=%S,
-**   wday=%w+1, yday=%j, isdst=? }
-** =======================================================
-*/
-
-static void setfield (lua_State *L, const char *key, int value) {
-  lua_pushinteger(L, value);
-  lua_setfield(L, -2, key);
-}
-
-static void setboolfield (lua_State *L, const char *key, int value) {
-  if (value < 0)  /* undefined? */
-    return;  /* does not set field */
-  lua_pushboolean(L, value);
-  lua_setfield(L, -2, key);
-}
-
-static int getboolfield (lua_State *L, const char *key) {
-  int res;
-  lua_getfield(L, -1, key);
-  res = lua_isnil(L, -1) ? -1 : lua_toboolean(L, -1);
-  lua_pop(L, 1);
-  return res;
-}
-
-
-static int getfield (lua_State *L, const char *key, int d) {
-  int res;
-  lua_getfield(L, -1, key);
-  if (lua_isnumber(L, -1))
-    res = (int)lua_tointeger(L, -1);
-  else {
-    if (d < 0)
-      return luaL_error(L, "field " LUA_QS " missing in date table", key);
-    res = d;
-  }
-  lua_pop(L, 1);
-  return res;
-}
-
-
-static int os_date (lua_State *L) {
-  const char *s = luaL_optstring(L, 1, "%c");
-  time_t t = luaL_opt(L, (time_t)luaL_checknumber, 2, time(NULL));
-  struct tm *stm;
-  if (*s == '!') {  /* UTC? */
-    stm = gmtime(&t);
-    s++;  /* skip `!' */
-  }
-  else
-    stm = localtime(&t);
-  if (stm == NULL)  /* invalid date? */
-    lua_pushnil(L);
-  else if (strcmp(s, "*t") == 0) {
-    lua_createtable(L, 0, 9);  /* 9 = number of fields */
-    setfield(L, "sec", stm->tm_sec);
-    setfield(L, "min", stm->tm_min);
-    setfield(L, "hour", stm->tm_hour);
-    setfield(L, "day", stm->tm_mday);
-    setfield(L, "month", stm->tm_mon+1);
-    setfield(L, "year", stm->tm_year+1900);
-    setfield(L, "wday", stm->tm_wday+1);
-    setfield(L, "yday", stm->tm_yday+1);
-    setboolfield(L, "isdst", stm->tm_isdst);
-  }
-  else {
-    char cc[3];
-    luaL_Buffer b;
-    cc[0] = '%'; cc[2] = '\0';
-    luaL_buffinit(L, &b);
-    for (; *s; s++) {
-      if (*s != '%' || *(s + 1) == '\0')  /* no conversion specifier? */
-        luaL_addchar(&b, *s);
-      else {
-        size_t reslen;
-        char buff[200];  /* should be big enough for any conversion result */
-        cc[1] = *(++s);
-        reslen = strftime(buff, sizeof(buff), cc, stm);
-        luaL_addlstring(&b, buff, reslen);
-      }
-    }
-    luaL_pushresult(&b);
-  }
-  return 1;
-}
-
-
-static int os_time (lua_State *L) {
-  time_t t;
-  if (lua_isnoneornil(L, 1))  /* called without args? */
-    t = time(NULL);  /* get current time */
-  else {
-    struct tm ts;
-    luaL_checktype(L, 1, LUA_TTABLE);
-    lua_settop(L, 1);  /* make sure table is at the top */
-    ts.tm_sec = getfield(L, "sec", 0);
-    ts.tm_min = getfield(L, "min", 0);
-    ts.tm_hour = getfield(L, "hour", 12);
-    ts.tm_mday = getfield(L, "day", -1);
-    ts.tm_mon = getfield(L, "month", -1) - 1;
-    ts.tm_year = getfield(L, "year", -1) - 1900;
-    ts.tm_isdst = getboolfield(L, "isdst");
-    t = mktime(&ts);
-  }
-  if (t == (time_t)(-1))
-    lua_pushnil(L);
-  else
-    lua_pushnumber(L, (lua_Number)t);
-  return 1;
-}
-
-#if !defined LUA_NUMBER_INTEGRAL
-static int os_difftime (lua_State *L) {
-  lua_pushnumber(L, difftime((time_t)(luaL_checknumber(L, 1)),
-                             (time_t)(luaL_optnumber(L, 2, 0))));
-  return 1;
-}
-#endif
-
-/* }====================================================== */
-
-
-static int os_setlocale (lua_State *L) {
-  static const int cat[] = {LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY,
-                      LC_NUMERIC, LC_TIME};
-  static const char *const catnames[] = {"all", "collate", "ctype", "monetary",
-     "numeric", "time", NULL};
-  const char *l = luaL_optstring(L, 1, NULL);
-  int op = luaL_checkoption(L, 2, "all", catnames);
-  lua_pushstring(L, setlocale(cat[op], l));
-  return 1;
-}
-
-
-static int os_exit (lua_State *L) {
-  exit(luaL_optint(L, 1, EXIT_SUCCESS));
-}
-
-#define MIN_OPT_LEVEL 1
-#include "lrodefs.h"
-const LUA_REG_TYPE syslib[] = {
-  {LSTRKEY("clock"),     LFUNCVAL(os_clock)},
-  {LSTRKEY("date"),      LFUNCVAL(os_date)},
-#if !defined LUA_NUMBER_INTEGRAL
-  {LSTRKEY("difftime"),  LFUNCVAL(os_difftime)},
-#endif
-  {LSTRKEY("execute"),   LFUNCVAL(os_execute)},
-  {LSTRKEY("exit"),      LFUNCVAL(os_exit)},
-  {LSTRKEY("getenv"),    LFUNCVAL(os_getenv)},
-  {LSTRKEY("remove"),    LFUNCVAL(os_remove)},
-  {LSTRKEY("rename"),    LFUNCVAL(os_rename)},
-  {LSTRKEY("setlocale"), LFUNCVAL(os_setlocale)},
-  {LSTRKEY("time"),      LFUNCVAL(os_time)},
-  {LSTRKEY("tmpname"),   LFUNCVAL(os_tmpname)},
-  {LNILKEY, LNILVAL}
-};
-
-/* }====================================================== */
-
-
-
-LUALIB_API int luaopen_os (lua_State *L) {
-  LREGISTER(L, LUA_OSLIBNAME, syslib);
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/lparser.c
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/lparser.c b/libs/elua/elua_base/src/lparser.c
deleted file mode 100644
index 5ada04c..0000000
--- a/libs/elua/elua_base/src/lparser.c
+++ /dev/null
@@ -1,1345 +0,0 @@
-/*
-** $Id: lparser.c,v 2.42.1.3 2007/12/28 15:32:23 roberto Exp $
-** Lua Parser
-** See Copyright Notice in lua.h
-*/
-
-
-#include <string.h>
-
-#define lparser_c
-#define LUA_CORE
-
-#include "lua.h"
-
-#include "lcode.h"
-#include "ldebug.h"
-#include "ldo.h"
-#include "lfunc.h"
-#include "llex.h"
-#include "lmem.h"
-#include "lobject.h"
-#include "lopcodes.h"
-#include "lparser.h"
-#include "lstate.h"
-#include "lstring.h"
-#include "ltable.h"
-
-
-
-#define hasmultret(k)		((k) == VCALL || (k) == VVARARG)
-
-#define getlocvar(fs, i)	((fs)->f->locvars[(fs)->actvar[i]])
-
-#define luaY_checklimit(fs,v,l,m)	if ((v)>(l)) errorlimit(fs,l,m)
-
-
-/*
-** nodes for block list (list of active blocks)
-*/
-typedef struct BlockCnt {
-  struct BlockCnt *previous;  /* chain */
-  int breaklist;  /* list of jumps out of this loop */
-  lu_byte nactvar;  /* # active locals outside the breakable structure */
-  lu_byte upval;  /* true if some variable in the block is an upvalue */
-  lu_byte isbreakable;  /* true if `block' is a loop */
-} BlockCnt;
-
-
-
-/*
-** prototypes for recursive non-terminal functions
-*/
-static void chunk (LexState *ls);
-static void expr (LexState *ls, expdesc *v);
-
-
-static void anchor_token (LexState *ls) {
-  if (ls->t.token == TK_NAME || ls->t.token == TK_STRING) {
-    TString *ts = ls->t.seminfo.ts;
-    luaX_newstring(ls, getstr(ts), ts->tsv.len);
-  }
-}
-
-
-static void error_expected (LexState *ls, int token) {
-  luaX_syntaxerror(ls,
-      luaO_pushfstring(ls->L, LUA_QS " expected", luaX_token2str(ls, token)));
-}
-
-
-static void errorlimit (FuncState *fs, int limit, const char *what) {
-  const char *msg = (fs->f->linedefined == 0) ?
-    luaO_pushfstring(fs->L, "main function has more than %d %s", limit, what) :
-    luaO_pushfstring(fs->L, "function at line %d has more than %d %s",
-                            fs->f->linedefined, limit, what);
-  luaX_lexerror(fs->ls, msg, 0);
-}
-
-
-static int testnext (LexState *ls, int c) {
-  if (ls->t.token == c) {
-    luaX_next(ls);
-    return 1;
-  }
-  else return 0;
-}
-
-
-static void check (LexState *ls, int c) {
-  if (ls->t.token != c)
-    error_expected(ls, c);
-}
-
-static void checknext (LexState *ls, int c) {
-  check(ls, c);
-  luaX_next(ls);
-}
-
-
-#define check_condition(ls,c,msg)	{ if (!(c)) luaX_syntaxerror(ls, msg); }
-
-
-
-static void check_match (LexState *ls, int what, int who, int where) {
-  if (!testnext(ls, what)) {
-    if (where == ls->linenumber)
-      error_expected(ls, what);
-    else {
-      luaX_syntaxerror(ls, luaO_pushfstring(ls->L,
-             LUA_QS " expected (to close " LUA_QS " at line %d)",
-              luaX_token2str(ls, what), luaX_token2str(ls, who), where));
-    }
-  }
-}
-
-
-static TString *str_checkname (LexState *ls) {
-  TString *ts;
-  check(ls, TK_NAME);
-  ts = ls->t.seminfo.ts;
-  luaX_next(ls);
-  return ts;
-}
-
-
-static void init_exp (expdesc *e, expkind k, int i) {
-  e->f = e->t = NO_JUMP;
-  e->k = k;
-  e->u.s.info = i;
-}
-
-
-static void codestring (LexState *ls, expdesc *e, TString *s) {
-  init_exp(e, VK, luaK_stringK(ls->fs, s));
-}
-
-
-static void checkname(LexState *ls, expdesc *e) {
-  codestring(ls, e, str_checkname(ls));
-}
-
-
-static int registerlocalvar (LexState *ls, TString *varname) {
-  FuncState *fs = ls->fs;
-  Proto *f = fs->f;
-  int oldsize = f->sizelocvars;
-  luaM_growvector(ls->L, f->locvars, fs->nlocvars, f->sizelocvars,
-                  LocVar, SHRT_MAX, "too many local variables");
-  while (oldsize < f->sizelocvars) f->locvars[oldsize++].varname = NULL;
-  f->locvars[fs->nlocvars].varname = varname;
-  luaC_objbarrier(ls->L, f, varname);
-  return fs->nlocvars++;
-}
-
-
-#define new_localvarliteral(ls,v,n) \
-  new_localvar(ls, luaX_newstring(ls, "" v, (sizeof(v)/sizeof(char))-1), n)
-
-
-static void new_localvar (LexState *ls, TString *name, int n) {
-  FuncState *fs = ls->fs;
-  luaY_checklimit(fs, fs->nactvar+n+1, LUAI_MAXVARS, "local variables");
-  fs->actvar[fs->nactvar+n] = cast(unsigned short, registerlocalvar(ls, name));
-}
-
-
-static void adjustlocalvars (LexState *ls, int nvars) {
-  FuncState *fs = ls->fs;
-  fs->nactvar = cast_byte(fs->nactvar + nvars);
-  for (; nvars; nvars--) {
-    getlocvar(fs, fs->nactvar - nvars).startpc = fs->pc;
-  }
-}
-
-
-static void removevars (LexState *ls, int tolevel) {
-  FuncState *fs = ls->fs;
-  while (fs->nactvar > tolevel)
-    getlocvar(fs, --fs->nactvar).endpc = fs->pc;
-}
-
-
-static int indexupvalue (FuncState *fs, TString *name, expdesc *v) {
-  int i;
-  Proto *f = fs->f;
-  int oldsize = f->sizeupvalues;
-  for (i=0; i<f->nups; i++) {
-    if (fs->upvalues[i].k == v->k && fs->upvalues[i].info == v->u.s.info) {
-      lua_assert(f->upvalues[i] == name);
-      return i;
-    }
-  }
-  /* new one */
-  luaY_checklimit(fs, f->nups + 1, LUAI_MAXUPVALUES, "upvalues");
-  luaM_growvector(fs->L, f->upvalues, f->nups, f->sizeupvalues,
-                  TString *, MAX_INT, "");
-  while (oldsize < f->sizeupvalues) f->upvalues[oldsize++] = NULL;
-  f->upvalues[f->nups] = name;
-  luaC_objbarrier(fs->L, f, name);
-  lua_assert(v->k == VLOCAL || v->k == VUPVAL);
-  fs->upvalues[f->nups].k = cast_byte(v->k);
-  fs->upvalues[f->nups].info = cast_byte(v->u.s.info);
-  return f->nups++;
-}
-
-
-static int searchvar (FuncState *fs, TString *n) {
-  int i;
-  for (i=fs->nactvar-1; i >= 0; i--) {
-    if (n == getlocvar(fs, i).varname)
-      return i;
-  }
-  return -1;  /* not found */
-}
-
-
-static void markupval (FuncState *fs, int level) {
-  BlockCnt *bl = fs->bl;
-  while (bl && bl->nactvar > level) bl = bl->previous;
-  if (bl) bl->upval = 1;
-}
-
-
-static int singlevaraux (FuncState *fs, TString *n, expdesc *var, int base) {
-  if (fs == NULL) {  /* no more levels? */
-    init_exp(var, VGLOBAL, NO_REG);  /* default is global variable */
-    return VGLOBAL;
-  }
-  else {
-    int v = searchvar(fs, n);  /* look up at current level */
-    if (v >= 0) {
-      init_exp(var, VLOCAL, v);
-      if (!base)
-        markupval(fs, v);  /* local will be used as an upval */
-      return VLOCAL;
-    }
-    else {  /* not found at current level; try upper one */
-      if (singlevaraux(fs->prev, n, var, 0) == VGLOBAL)
-        return VGLOBAL;
-      var->u.s.info = indexupvalue(fs, n, var);  /* else was LOCAL or UPVAL */
-      var->k = VUPVAL;  /* upvalue in this level */
-      return VUPVAL;
-    }
-  }
-}
-
-
-static void singlevar (LexState *ls, expdesc *var) {
-  TString *varname = str_checkname(ls);
-  FuncState *fs = ls->fs;
-  if (singlevaraux(fs, varname, var, 1) == VGLOBAL)
-    var->u.s.info = luaK_stringK(fs, varname);  /* info points to global name */
-}
-
-
-static void adjust_assign (LexState *ls, int nvars, int nexps, expdesc *e) {
-  FuncState *fs = ls->fs;
-  int extra = nvars - nexps;
-  if (hasmultret(e->k)) {
-    extra++;  /* includes call itself */
-    if (extra < 0) extra = 0;
-    luaK_setreturns(fs, e, extra);  /* last exp. provides the difference */
-    if (extra > 1) luaK_reserveregs(fs, extra-1);
-  }
-  else {
-    if (e->k != VVOID) luaK_exp2nextreg(fs, e);  /* close last expression */
-    if (extra > 0) {
-      int reg = fs->freereg;
-      luaK_reserveregs(fs, extra);
-      luaK_nil(fs, reg, extra);
-    }
-  }
-}
-
-
-static void enterlevel (LexState *ls) {
-  if (++ls->L->nCcalls > LUAI_MAXCCALLS)
-	luaX_lexerror(ls, "chunk has too many syntax levels", 0);
-}
-
-
-#define leavelevel(ls)	((ls)->L->nCcalls--)
-
-
-static void enterblock (FuncState *fs, BlockCnt *bl, lu_byte isbreakable) {
-  bl->breaklist = NO_JUMP;
-  bl->isbreakable = isbreakable;
-  bl->nactvar = fs->nactvar;
-  bl->upval = 0;
-  bl->previous = fs->bl;
-  fs->bl = bl;
-  lua_assert(fs->freereg == fs->nactvar);
-}
-
-
-static void leaveblock (FuncState *fs) {
-  BlockCnt *bl = fs->bl;
-  fs->bl = bl->previous;
-  removevars(fs->ls, bl->nactvar);
-  if (bl->upval)
-    luaK_codeABC(fs, OP_CLOSE, bl->nactvar, 0, 0);
-  /* a block either controls scope or breaks (never both) */
-  lua_assert(!bl->isbreakable || !bl->upval);
-  lua_assert(bl->nactvar == fs->nactvar);
-  fs->freereg = fs->nactvar;  /* free registers */
-  luaK_patchtohere(fs, bl->breaklist);
-}
-
-
-static void pushclosure (LexState *ls, FuncState *func, expdesc *v) {
-  FuncState *fs = ls->fs;
-  Proto *f = fs->f;
-  int oldsize = f->sizep;
-  int i;
-  luaM_growvector(ls->L, f->p, fs->np, f->sizep, Proto *,
-                  MAXARG_Bx, "constant table overflow");
-  while (oldsize < f->sizep) f->p[oldsize++] = NULL;
-  f->p[fs->np++] = func->f;
-  luaC_objbarrier(ls->L, f, func->f);
-  init_exp(v, VRELOCABLE, luaK_codeABx(fs, OP_CLOSURE, 0, fs->np-1));
-  for (i=0; i<func->f->nups; i++) {
-    OpCode o = (func->upvalues[i].k == VLOCAL) ? OP_MOVE : OP_GETUPVAL;
-    luaK_codeABC(fs, o, 0, func->upvalues[i].info, 0);
-  }
-}
-
-
-static void open_func (LexState *ls, FuncState *fs) {
-  lua_State *L = ls->L;
-  Proto *f = luaF_newproto(L);
-  fs->f = f;
-  fs->prev = ls->fs;  /* linked list of funcstates */
-  fs->ls = ls;
-  fs->L = L;
-  ls->fs = fs;
-  fs->pc = 0;
-  fs->lasttarget = -1;
-  fs->jpc = NO_JUMP;
-  fs->freereg = 0;
-  fs->nk = 0;
-  fs->np = 0;
-  fs->nlocvars = 0;
-  fs->nactvar = 0;
-  fs->bl = NULL;
-  f->source = ls->source;
-  f->maxstacksize = 2;  /* registers 0/1 are always valid */
-  fs->h = luaH_new(L, 0, 0);
-  /* anchor table of constants and prototype (to avoid being collected) */
-  sethvalue2s(L, L->top, fs->h);
-  incr_top(L);
-  setptvalue2s(L, L->top, f);
-  incr_top(L);
-}
-
-
-static void close_func (LexState *ls) {
-  lua_State *L = ls->L;
-  FuncState *fs = ls->fs;
-  Proto *f = fs->f;
-  removevars(ls, 0);
-  luaK_ret(fs, 0, 0);  /* final return */
-  luaM_reallocvector(L, f->code, f->sizecode, fs->pc, Instruction);
-  f->sizecode = fs->pc;
-  luaM_reallocvector(L, f->lineinfo, f->sizelineinfo, fs->pc, int);
-  f->sizelineinfo = fs->pc;
-  luaM_reallocvector(L, f->k, f->sizek, fs->nk, TValue);
-  f->sizek = fs->nk;
-  luaM_reallocvector(L, f->p, f->sizep, fs->np, Proto *);
-  f->sizep = fs->np;
-  luaM_reallocvector(L, f->locvars, f->sizelocvars, fs->nlocvars, LocVar);
-  f->sizelocvars = fs->nlocvars;
-  luaM_reallocvector(L, f->upvalues, f->sizeupvalues, f->nups, TString *);
-  f->sizeupvalues = f->nups;
-  lua_assert(luaG_checkcode(f));
-  lua_assert(fs->bl == NULL);
-  ls->fs = fs->prev;
-  /* last token read was anchored in defunct function; must reanchor it */
-  if (fs) anchor_token(ls);
-  L->top -= 2;  /* remove table and prototype from the stack */
-}
-
-
-Proto *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff, const char *name) {
-  struct LexState lexstate;
-  struct FuncState funcstate;
-  TString *tname = luaS_new(L, name);
-  setsvalue2s(L, L->top, tname);  /* protect name */
-  incr_top(L);
-  lexstate.buff = buff;
-  luaX_setinput(L, &lexstate, z, tname);
-  open_func(&lexstate, &funcstate);
-  funcstate.f->is_vararg = VARARG_ISVARARG;  /* main func. is always vararg */
-  luaX_next(&lexstate);  /* read first token */
-  chunk(&lexstate);
-  check(&lexstate, TK_EOS);
-  close_func(&lexstate);
-  L->top--; /* remove 'name' from stack */
-  lua_assert(funcstate.prev == NULL);
-  lua_assert(funcstate.f->nups == 0);
-  lua_assert(lexstate.fs == NULL);
-  return funcstate.f;
-}
-
-
-
-/*============================================================*/
-/* GRAMMAR RULES */
-/*============================================================*/
-
-
-static void field (LexState *ls, expdesc *v) {
-  /* field -> ['.' | ':'] NAME */
-  FuncState *fs = ls->fs;
-  expdesc key;
-  luaK_exp2anyreg(fs, v);
-  luaX_next(ls);  /* skip the dot or colon */
-  checkname(ls, &key);
-  luaK_indexed(fs, v, &key);
-}
-
-
-static void yindex (LexState *ls, expdesc *v) {
-  /* index -> '[' expr ']' */
-  luaX_next(ls);  /* skip the '[' */
-  expr(ls, v);
-  luaK_exp2val(ls->fs, v);
-  checknext(ls, ']');
-}
-
-
-/*
-** {======================================================================
-** Rules for Constructors
-** =======================================================================
-*/
-
-
-struct ConsControl {
-  expdesc v;  /* last list item read */
-  expdesc *t;  /* table descriptor */
-  int nh;  /* total number of `record' elements */
-  int na;  /* total number of array elements */
-  int tostore;  /* number of array elements pending to be stored */
-};
-
-
-static void recfield (LexState *ls, struct ConsControl *cc) {
-  /* recfield -> (NAME | `['exp1`]') = exp1 */
-  FuncState *fs = ls->fs;
-  int reg = ls->fs->freereg;
-  expdesc key, val;
-  int rkkey;
-  if (ls->t.token == TK_NAME) {
-    luaY_checklimit(fs, cc->nh, MAX_INT, "items in a constructor");
-    checkname(ls, &key);
-  }
-  else  /* ls->t.token == '[' */
-    yindex(ls, &key);
-  cc->nh++;
-  checknext(ls, '=');
-  rkkey = luaK_exp2RK(fs, &key);
-  expr(ls, &val);
-  luaK_codeABC(fs, OP_SETTABLE, cc->t->u.s.info, rkkey, luaK_exp2RK(fs, &val));
-  fs->freereg = reg;  /* free registers */
-}
-
-
-static void closelistfield (FuncState *fs, struct ConsControl *cc) {
-  if (cc->v.k == VVOID) return;  /* there is no list item */
-  luaK_exp2nextreg(fs, &cc->v);
-  cc->v.k = VVOID;
-  if (cc->tostore == LFIELDS_PER_FLUSH) {
-    luaK_setlist(fs, cc->t->u.s.info, cc->na, cc->tostore);  /* flush */
-    cc->tostore = 0;  /* no more items pending */
-  }
-}
-
-
-static void lastlistfield (FuncState *fs, struct ConsControl *cc) {
-  if (cc->tostore == 0) return;
-  if (hasmultret(cc->v.k)) {
-    luaK_setmultret(fs, &cc->v);
-    luaK_setlist(fs, cc->t->u.s.info, cc->na, LUA_MULTRET);
-    cc->na--;  /* do not count last expression (unknown number of elements) */
-  }
-  else {
-    if (cc->v.k != VVOID)
-      luaK_exp2nextreg(fs, &cc->v);
-    luaK_setlist(fs, cc->t->u.s.info, cc->na, cc->tostore);
-  }
-}
-
-
-static void listfield (LexState *ls, struct ConsControl *cc) {
-  expr(ls, &cc->v);
-  luaY_checklimit(ls->fs, cc->na, MAX_INT, "items in a constructor");
-  cc->na++;
-  cc->tostore++;
-}
-
-
-static void constructor (LexState *ls, expdesc *t) {
-  /* constructor -> ?? */
-  FuncState *fs = ls->fs;
-  int line = ls->linenumber;
-  int pc = luaK_codeABC(fs, OP_NEWTABLE, 0, 0, 0);
-  struct ConsControl cc;
-  cc.na = cc.nh = cc.tostore = 0;
-  cc.t = t;
-  init_exp(t, VRELOCABLE, pc);
-  init_exp(&cc.v, VVOID, 0);  /* no value (yet) */
-  luaK_exp2nextreg(ls->fs, t);  /* fix it at stack top (for gc) */
-  checknext(ls, '{');
-  do {
-    lua_assert(cc.v.k == VVOID || cc.tostore > 0);
-    if (ls->t.token == '}') break;
-    closelistfield(fs, &cc);
-    switch(ls->t.token) {
-      case TK_NAME: {  /* may be listfields or recfields */
-        luaX_lookahead(ls);
-        if (ls->lookahead.token != '=')  /* expression? */
-          listfield(ls, &cc);
-        else
-          recfield(ls, &cc);
-        break;
-      }
-      case '[': {  /* constructor_item -> recfield */
-        recfield(ls, &cc);
-        break;
-      }
-      default: {  /* constructor_part -> listfield */
-        listfield(ls, &cc);
-        break;
-      }
-    }
-  } while (testnext(ls, ',') || testnext(ls, ';'));
-  check_match(ls, '}', '{', line);
-  lastlistfield(fs, &cc);
-  SETARG_B(fs->f->code[pc], luaO_int2fb(cc.na)); /* set initial array size */
-  SETARG_C(fs->f->code[pc], luaO_int2fb(cc.nh));  /* set initial table size */
-}
-
-/* }====================================================================== */
-
-
-
-static void parlist (LexState *ls) {
-  /* parlist -> [ param { `,' param } ] */
-  FuncState *fs = ls->fs;
-  Proto *f = fs->f;
-  int nparams = 0;
-  f->is_vararg = 0;
-  if (ls->t.token != ')') {  /* is `parlist' not empty? */
-    do {
-      switch (ls->t.token) {
-        case TK_NAME: {  /* param -> NAME */
-          new_localvar(ls, str_checkname(ls), nparams++);
-          break;
-        }
-        case TK_DOTS: {  /* param -> `...' */
-          luaX_next(ls);
-#if defined(LUA_COMPAT_VARARG)
-          /* use `arg' as default name */
-          new_localvarliteral(ls, "arg", nparams++);
-          f->is_vararg = VARARG_HASARG | VARARG_NEEDSARG;
-#endif
-          f->is_vararg |= VARARG_ISVARARG;
-          break;
-        }
-        default: luaX_syntaxerror(ls, "<name> or " LUA_QL("...") " expected");
-      }
-    } while (!f->is_vararg && testnext(ls, ','));
-  }
-  adjustlocalvars(ls, nparams);
-  f->numparams = cast_byte(fs->nactvar - (f->is_vararg & VARARG_HASARG));
-  luaK_reserveregs(fs, fs->nactvar);  /* reserve register for parameters */
-}
-
-
-static void body (LexState *ls, expdesc *e, int needself, int line) {
-  /* body ->  `(' parlist `)' chunk END */
-  FuncState new_fs;
-  open_func(ls, &new_fs);
-  new_fs.f->linedefined = line;
-  checknext(ls, '(');
-  if (needself) {
-    new_localvarliteral(ls, "self", 0);
-    adjustlocalvars(ls, 1);
-  }
-  parlist(ls);
-  checknext(ls, ')');
-  chunk(ls);
-  new_fs.f->lastlinedefined = ls->linenumber;
-  check_match(ls, TK_END, TK_FUNCTION, line);
-  close_func(ls);
-  pushclosure(ls, &new_fs, e);
-}
-
-
-static int explist1 (LexState *ls, expdesc *v) {
-  /* explist1 -> expr { `,' expr } */
-  int n = 1;  /* at least one expression */
-  expr(ls, v);
-  while (testnext(ls, ',')) {
-    luaK_exp2nextreg(ls->fs, v);
-    expr(ls, v);
-    n++;
-  }
-  return n;
-}
-
-
-static void funcargs (LexState *ls, expdesc *f) {
-  FuncState *fs = ls->fs;
-  expdesc args;
-  int base, nparams;
-  int line = ls->linenumber;
-  switch (ls->t.token) {
-    case '(': {  /* funcargs -> `(' [ explist1 ] `)' */
-      if (line != ls->lastline)
-        luaX_syntaxerror(ls,"ambiguous syntax (function call x new statement)");
-      luaX_next(ls);
-      if (ls->t.token == ')')  /* arg list is empty? */
-        args.k = VVOID;
-      else {
-        explist1(ls, &args);
-        luaK_setmultret(fs, &args);
-      }
-      check_match(ls, ')', '(', line);
-      break;
-    }
-    case '{': {  /* funcargs -> constructor */
-      constructor(ls, &args);
-      break;
-    }
-    case TK_STRING: {  /* funcargs -> STRING */
-      codestring(ls, &args, ls->t.seminfo.ts);
-      luaX_next(ls);  /* must use `seminfo' before `next' */
-      break;
-    }
-    default: {
-      luaX_syntaxerror(ls, "function arguments expected");
-      return;
-    }
-  }
-  lua_assert(f->k == VNONRELOC);
-  base = f->u.s.info;  /* base register for call */
-  if (hasmultret(args.k))
-    nparams = LUA_MULTRET;  /* open call */
-  else {
-    if (args.k != VVOID)
-      luaK_exp2nextreg(fs, &args);  /* close last argument */
-    nparams = fs->freereg - (base+1);
-  }
-  init_exp(f, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams+1, 2));
-  luaK_fixline(fs, line);
-  fs->freereg = base+1;  /* call remove function and arguments and leaves
-                            (unless changed) one result */
-}
-
-
-
-
-/*
-** {======================================================================
-** Expression parsing
-** =======================================================================
-*/
-
-
-static void prefixexp (LexState *ls, expdesc *v) {
-  /* prefixexp -> NAME | '(' expr ')' */
-  switch (ls->t.token) {
-    case '(': {
-      int line = ls->linenumber;
-      luaX_next(ls);
-      expr(ls, v);
-      check_match(ls, ')', '(', line);
-      luaK_dischargevars(ls->fs, v);
-      return;
-    }
-    case TK_NAME: {
-      singlevar(ls, v);
-      return;
-    }
-    default: {
-      luaX_syntaxerror(ls, "unexpected symbol");
-      return;
-    }
-  }
-}
-
-
-static void primaryexp (LexState *ls, expdesc *v) {
-  /* primaryexp ->
-        prefixexp { `.' NAME | `[' exp `]' | `:' NAME funcargs | funcargs } */
-  FuncState *fs = ls->fs;
-  prefixexp(ls, v);
-  for (;;) {
-    switch (ls->t.token) {
-      case '.': {  /* field */
-        field(ls, v);
-        break;
-      }
-      case '[': {  /* `[' exp1 `]' */
-        expdesc key;
-        luaK_exp2anyreg(fs, v);
-        yindex(ls, &key);
-        luaK_indexed(fs, v, &key);
-        break;
-      }
-      case ':': {  /* `:' NAME funcargs */
-        expdesc key;
-        luaX_next(ls);
-        checkname(ls, &key);
-        luaK_self(fs, v, &key);
-        funcargs(ls, v);
-        break;
-      }
-      case '(': case TK_STRING: case '{': {  /* funcargs */
-        luaK_exp2nextreg(fs, v);
-        funcargs(ls, v);
-        break;
-      }
-      default: return;
-    }
-  }
-}
-
-
-static void simpleexp (LexState *ls, expdesc *v) {
-  /* simpleexp -> NUMBER | STRING | NIL | true | false | ... |
-                  constructor | FUNCTION body | primaryexp */
-  switch (ls->t.token) {
-    case TK_NUMBER: {
-      init_exp(v, VKNUM, 0);
-      v->u.nval = ls->t.seminfo.r;
-      break;
-    }
-    case TK_STRING: {
-      codestring(ls, v, ls->t.seminfo.ts);
-      break;
-    }
-    case TK_NIL: {
-      init_exp(v, VNIL, 0);
-      break;
-    }
-    case TK_TRUE: {
-      init_exp(v, VTRUE, 0);
-      break;
-    }
-    case TK_FALSE: {
-      init_exp(v, VFALSE, 0);
-      break;
-    }
-    case TK_DOTS: {  /* vararg */
-      FuncState *fs = ls->fs;
-      check_condition(ls, fs->f->is_vararg,
-                      "cannot use " LUA_QL("...") " outside a vararg function");
-      fs->f->is_vararg &= ~VARARG_NEEDSARG;  /* don't need 'arg' */
-      init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, 1, 0));
-      break;
-    }
-    case '{': {  /* constructor */
-      constructor(ls, v);
-      return;
-    }
-    case TK_FUNCTION: {
-      luaX_next(ls);
-      body(ls, v, 0, ls->linenumber);
-      return;
-    }
-    default: {
-      primaryexp(ls, v);
-      return;
-    }
-  }
-  luaX_next(ls);
-}
-
-
-static UnOpr getunopr (int op) {
-  switch (op) {
-    case TK_NOT: return OPR_NOT;
-    case '-': return OPR_MINUS;
-    case '#': return OPR_LEN;
-    default: return OPR_NOUNOPR;
-  }
-}
-
-
-static BinOpr getbinopr (int op) {
-  switch (op) {
-    case '+': return OPR_ADD;
-    case '-': return OPR_SUB;
-    case '*': return OPR_MUL;
-    case '/': return OPR_DIV;
-    case '%': return OPR_MOD;
-    case '^': return OPR_POW;
-    case TK_CONCAT: return OPR_CONCAT;
-    case TK_NE: return OPR_NE;
-    case TK_EQ: return OPR_EQ;
-    case '<': return OPR_LT;
-    case TK_LE: return OPR_LE;
-    case '>': return OPR_GT;
-    case TK_GE: return OPR_GE;
-    case TK_AND: return OPR_AND;
-    case TK_OR: return OPR_OR;
-    default: return OPR_NOBINOPR;
-  }
-}
-
-
-static const struct {
-  lu_byte left;  /* left priority for each binary operator */
-  lu_byte right; /* right priority */
-} priority[] = {  /* ORDER OPR */
-   {6, 6}, {6, 6}, {7, 7}, {7, 7}, {7, 7},  /* `+' `-' `/' `%' */
-   {10, 9}, {5, 4},                 /* power and concat (right associative) */
-   {3, 3}, {3, 3},                  /* equality and inequality */
-   {3, 3}, {3, 3}, {3, 3}, {3, 3},  /* order */
-   {2, 2}, {1, 1}                   /* logical (and/or) */
-};
-
-#define UNARY_PRIORITY	8  /* priority for unary operators */
-
-
-/*
-** subexpr -> (simpleexp | unop subexpr) { binop subexpr }
-** where `binop' is any binary operator with a priority higher than `limit'
-*/
-static BinOpr subexpr (LexState *ls, expdesc *v, unsigned int limit) {
-  BinOpr op;
-  UnOpr uop;
-  enterlevel(ls);
-  uop = getunopr(ls->t.token);
-  if (uop != OPR_NOUNOPR) {
-    luaX_next(ls);
-    subexpr(ls, v, UNARY_PRIORITY);
-    luaK_prefix(ls->fs, uop, v);
-  }
-  else simpleexp(ls, v);
-  /* expand while operators have priorities higher than `limit' */
-  op = getbinopr(ls->t.token);
-  while (op != OPR_NOBINOPR && priority[op].left > limit) {
-    expdesc v2;
-    BinOpr nextop;
-    luaX_next(ls);
-    luaK_infix(ls->fs, op, v);
-    /* read sub-expression with higher priority */
-    nextop = subexpr(ls, &v2, priority[op].right);
-    luaK_posfix(ls->fs, op, v, &v2);
-    op = nextop;
-  }
-  leavelevel(ls);
-  return op;  /* return first untreated operator */
-}
-
-
-static void expr (LexState *ls, expdesc *v) {
-  subexpr(ls, v, 0);
-}
-
-/* }==================================================================== */
-
-
-
-/*
-** {======================================================================
-** Rules for Statements
-** =======================================================================
-*/
-
-
-static int block_follow (int token) {
-  switch (token) {
-    case TK_ELSE: case TK_ELSEIF: case TK_END:
-    case TK_UNTIL: case TK_EOS:
-      return 1;
-    default: return 0;
-  }
-}
-
-
-static void block (LexState *ls) {
-  /* block -> chunk */
-  FuncState *fs = ls->fs;
-  BlockCnt *pbl = (BlockCnt*)luaM_malloc(ls->L,sizeof(BlockCnt));
-  enterblock(fs, pbl, 0);
-  chunk(ls);
-  lua_assert(pbl->breaklist == NO_JUMP);
-  leaveblock(fs);
-  luaM_free(ls->L,pbl);
-}
-
-
-/*
-** structure to chain all variables in the left-hand side of an
-** assignment
-*/
-struct LHS_assign {
-  struct LHS_assign *prev;
-  expdesc v;  /* variable (global, local, upvalue, or indexed) */
-};
-
-
-/*
-** check whether, in an assignment to a local variable, the local variable
-** is needed in a previous assignment (to a table). If so, save original
-** local value in a safe place and use this safe copy in the previous
-** assignment.
-*/
-static void check_conflict (LexState *ls, struct LHS_assign *lh, expdesc *v) {
-  FuncState *fs = ls->fs;
-  int extra = fs->freereg;  /* eventual position to save local variable */
-  int conflict = 0;
-  for (; lh; lh = lh->prev) {
-    if (lh->v.k == VINDEXED) {
-      if (lh->v.u.s.info == v->u.s.info) {  /* conflict? */
-        conflict = 1;
-        lh->v.u.s.info = extra;  /* previous assignment will use safe copy */
-      }
-      if (lh->v.u.s.aux == v->u.s.info) {  /* conflict? */
-        conflict = 1;
-        lh->v.u.s.aux = extra;  /* previous assignment will use safe copy */
-      }
-    }
-  }
-  if (conflict) {
-    luaK_codeABC(fs, OP_MOVE, fs->freereg, v->u.s.info, 0);  /* make copy */
-    luaK_reserveregs(fs, 1);
-  }
-}
-
-
-static void assignment (LexState *ls, struct LHS_assign *lh, int nvars) {
-  expdesc e;
-  check_condition(ls, VLOCAL <= lh->v.k && lh->v.k <= VINDEXED,
-                      "syntax error");
-  if (testnext(ls, ',')) {  /* assignment -> `,' primaryexp assignment */
-    struct LHS_assign nv;
-    nv.prev = lh;
-    primaryexp(ls, &nv.v);
-    if (nv.v.k == VLOCAL)
-      check_conflict(ls, lh, &nv.v);
-    luaY_checklimit(ls->fs, nvars, LUAI_MAXCCALLS - ls->L->nCcalls,
-                    "variables in assignment");
-    assignment(ls, &nv, nvars+1);
-  }
-  else {  /* assignment -> `=' explist1 */
-    int nexps;
-    checknext(ls, '=');
-    nexps = explist1(ls, &e);
-    if (nexps != nvars) {
-      adjust_assign(ls, nvars, nexps, &e);
-      if (nexps > nvars)
-        ls->fs->freereg -= nexps - nvars;  /* remove extra values */
-    }
-    else {
-      luaK_setoneret(ls->fs, &e);  /* close last expression */
-      luaK_storevar(ls->fs, &lh->v, &e);
-      return;  /* avoid default */
-    }
-  }
-  init_exp(&e, VNONRELOC, ls->fs->freereg-1);  /* default assignment */
-  luaK_storevar(ls->fs, &lh->v, &e);
-}
-
-
-static int cond (LexState *ls) {
-  /* cond -> exp */
-  expdesc v;
-  expr(ls, &v);  /* read condition */
-  if (v.k == VNIL) v.k = VFALSE;  /* `falses' are all equal here */
-  luaK_goiftrue(ls->fs, &v);
-  return v.f;
-}
-
-
-static void breakstat (LexState *ls) {
-  FuncState *fs = ls->fs;
-  BlockCnt *bl = fs->bl;
-  int upval = 0;
-  while (bl && !bl->isbreakable) {
-    upval |= bl->upval;
-    bl = bl->previous;
-  }
-  if (!bl)
-    luaX_syntaxerror(ls, "no loop to break");
-  if (upval)
-    luaK_codeABC(fs, OP_CLOSE, bl->nactvar, 0, 0);
-  luaK_concat(fs, &bl->breaklist, luaK_jump(fs));
-}
-
-
-static void whilestat (LexState *ls, int line) {
-  /* whilestat -> WHILE cond DO block END */
-  FuncState *fs = ls->fs;
-  int whileinit;
-  int condexit;
-  BlockCnt bl;
-  luaX_next(ls);  /* skip WHILE */
-  whileinit = luaK_getlabel(fs);
-  condexit = cond(ls);
-  enterblock(fs, &bl, 1);
-  checknext(ls, TK_DO);
-  block(ls);
-  luaK_patchlist(fs, luaK_jump(fs), whileinit);
-  check_match(ls, TK_END, TK_WHILE, line);
-  leaveblock(fs);
-  luaK_patchtohere(fs, condexit);  /* false conditions finish the loop */
-}
-
-
-static void repeatstat (LexState *ls, int line) {
-  /* repeatstat -> REPEAT block UNTIL cond */
-  int condexit;
-  FuncState *fs = ls->fs;
-  int repeat_init = luaK_getlabel(fs);
-  BlockCnt bl1, bl2;
-  enterblock(fs, &bl1, 1);  /* loop block */
-  enterblock(fs, &bl2, 0);  /* scope block */
-  luaX_next(ls);  /* skip REPEAT */
-  chunk(ls);
-  check_match(ls, TK_UNTIL, TK_REPEAT, line);
-  condexit = cond(ls);  /* read condition (inside scope block) */
-  if (!bl2.upval) {  /* no upvalues? */
-    leaveblock(fs);  /* finish scope */
-    luaK_patchlist(ls->fs, condexit, repeat_init);  /* close the loop */
-  }
-  else {  /* complete semantics when there are upvalues */
-    breakstat(ls);  /* if condition then break */
-    luaK_patchtohere(ls->fs, condexit);  /* else... */
-    leaveblock(fs);  /* finish scope... */
-    luaK_patchlist(ls->fs, luaK_jump(fs), repeat_init);  /* and repeat */
-  }
-  leaveblock(fs);  /* finish loop */
-}
-
-
-static int exp1 (LexState *ls) {
-  expdesc e;
-  int k;
-  expr(ls, &e);
-  k = e.k;
-  luaK_exp2nextreg(ls->fs, &e);
-  return k;
-}
-
-
-static void forbody (LexState *ls, int base, int line, int nvars, int isnum) {
-  /* forbody -> DO block */
-  BlockCnt *pbl = (BlockCnt*)luaM_malloc(ls->L,sizeof(BlockCnt));
-  FuncState *fs = ls->fs;
-  int prep, endfor;
-  adjustlocalvars(ls, 3);  /* control variables */
-  checknext(ls, TK_DO);
-  prep = isnum ? luaK_codeAsBx(fs, OP_FORPREP, base, NO_JUMP) : luaK_jump(fs);
-  enterblock(fs, pbl, 0);  /* scope for declared variables */
-  adjustlocalvars(ls, nvars);
-  luaK_reserveregs(fs, nvars);
-  block(ls);
-  leaveblock(fs);  /* end of scope for declared variables */
-  luaK_patchtohere(fs, prep);
-  endfor = (isnum) ? luaK_codeAsBx(fs, OP_FORLOOP, base, NO_JUMP) :
-                     luaK_codeABC(fs, OP_TFORLOOP, base, 0, nvars);
-  luaK_fixline(fs, line);  /* pretend that `OP_FOR' starts the loop */
-  luaK_patchlist(fs, (isnum ? endfor : luaK_jump(fs)), prep + 1);
-  luaM_free(ls->L,pbl);
-}
-
-
-static void fornum (LexState *ls, TString *varname, int line) {
-  /* fornum -> NAME = exp1,exp1[,exp1] forbody */
-  FuncState *fs = ls->fs;
-  int base = fs->freereg;
-  new_localvarliteral(ls, "(for index)", 0);
-  new_localvarliteral(ls, "(for limit)", 1);
-  new_localvarliteral(ls, "(for step)", 2);
-  new_localvar(ls, varname, 3);
-  checknext(ls, '=');
-  exp1(ls);  /* initial value */
-  checknext(ls, ',');
-  exp1(ls);  /* limit */
-  if (testnext(ls, ','))
-    exp1(ls);  /* optional step */
-  else {  /* default step = 1 */
-    luaK_codeABx(fs, OP_LOADK, fs->freereg, luaK_numberK(fs, 1));
-    luaK_reserveregs(fs, 1);
-  }
-  forbody(ls, base, line, 1, 1);
-}
-
-
-static void forlist (LexState *ls, TString *indexname) {
-  /* forlist -> NAME {,NAME} IN explist1 forbody */
-  FuncState *fs = ls->fs;
-  expdesc e;
-  int nvars = 0;
-  int line;
-  int base = fs->freereg;
-  /* create control variables */
-  new_localvarliteral(ls, "(for generator)", nvars++);
-  new_localvarliteral(ls, "(for state)", nvars++);
-  new_localvarliteral(ls, "(for control)", nvars++);
-  /* create declared variables */
-  new_localvar(ls, indexname, nvars++);
-  while (testnext(ls, ','))
-    new_localvar(ls, str_checkname(ls), nvars++);
-  checknext(ls, TK_IN);
-  line = ls->linenumber;
-  adjust_assign(ls, 3, explist1(ls, &e), &e);
-  luaK_checkstack(fs, 3);  /* extra space to call generator */
-  forbody(ls, base, line, nvars - 3, 0);
-}
-
-
-static void forstat (LexState *ls, int line) {
-  /* forstat -> FOR (fornum | forlist) END */
-  FuncState *fs = ls->fs;
-  TString *varname;
-  BlockCnt bl;
-  enterblock(fs, &bl, 1);  /* scope for loop and control variables */
-  luaX_next(ls);  /* skip `for' */
-  varname = str_checkname(ls);  /* first variable name */
-  switch (ls->t.token) {
-    case '=': fornum(ls, varname, line); break;
-    case ',': case TK_IN: forlist(ls, varname); break;
-    default: luaX_syntaxerror(ls, LUA_QL("=") " or " LUA_QL("in") " expected");
-  }
-  check_match(ls, TK_END, TK_FOR, line);
-  leaveblock(fs);  /* loop scope (`break' jumps to this point) */
-}
-
-
-static int test_then_block (LexState *ls) {
-  /* test_then_block -> [IF | ELSEIF] cond THEN block */
-  int condexit;
-  luaX_next(ls);  /* skip IF or ELSEIF */
-  condexit = cond(ls);
-  checknext(ls, TK_THEN);
-  block(ls);  /* `then' part */
-  return condexit;
-}
-
-
-static void ifstat (LexState *ls, int line) {
-  /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */
-  FuncState *fs = ls->fs;
-  int flist;
-  int escapelist = NO_JUMP;
-  flist = test_then_block(ls);  /* IF cond THEN block */
-  while (ls->t.token == TK_ELSEIF) {
-    luaK_concat(fs, &escapelist, luaK_jump(fs));
-    luaK_patchtohere(fs, flist);
-    flist = test_then_block(ls);  /* ELSEIF cond THEN block */
-  }
-  if (ls->t.token == TK_ELSE) {
-    luaK_concat(fs, &escapelist, luaK_jump(fs));
-    luaK_patchtohere(fs, flist);
-    luaX_next(ls);  /* skip ELSE (after patch, for correct line info) */
-    block(ls);  /* `else' part */
-  }
-  else
-    luaK_concat(fs, &escapelist, flist);
-  luaK_patchtohere(fs, escapelist);
-  check_match(ls, TK_END, TK_IF, line);
-}
-
-
-static void localfunc (LexState *ls) {
-  expdesc v, b;
-  FuncState *fs = ls->fs;
-  new_localvar(ls, str_checkname(ls), 0);
-  init_exp(&v, VLOCAL, fs->freereg);
-  luaK_reserveregs(fs, 1);
-  adjustlocalvars(ls, 1);
-  body(ls, &b, 0, ls->linenumber);
-  luaK_storevar(fs, &v, &b);
-  /* debug information will only see the variable after this point! */
-  getlocvar(fs, fs->nactvar - 1).startpc = fs->pc;
-}
-
-
-static void localstat (LexState *ls) {
-  /* stat -> LOCAL NAME {`,' NAME} [`=' explist1] */
-  int nvars = 0;
-  int nexps;
-  expdesc e;
-  do {
-    new_localvar(ls, str_checkname(ls), nvars++);
-  } while (testnext(ls, ','));
-  if (testnext(ls, '='))
-    nexps = explist1(ls, &e);
-  else {
-    e.k = VVOID;
-    nexps = 0;
-  }
-  adjust_assign(ls, nvars, nexps, &e);
-  adjustlocalvars(ls, nvars);
-}
-
-
-static int funcname (LexState *ls, expdesc *v) {
-  /* funcname -> NAME {field} [`:' NAME] */
-  int needself = 0;
-  singlevar(ls, v);
-  while (ls->t.token == '.')
-    field(ls, v);
-  if (ls->t.token == ':') {
-    needself = 1;
-    field(ls, v);
-  }
-  return needself;
-}
-
-
-static void funcstat (LexState *ls, int line) {
-  /* funcstat -> FUNCTION funcname body */
-  int needself;
-  expdesc v, b;
-  luaX_next(ls);  /* skip FUNCTION */
-  needself = funcname(ls, &v);
-  body(ls, &b, needself, line);
-  luaK_storevar(ls->fs, &v, &b);
-  luaK_fixline(ls->fs, line);  /* definition `happens' in the first line */
-}
-
-
-static void exprstat (LexState *ls) {
-  /* stat -> func | assignment */
-  FuncState *fs = ls->fs;
-  struct LHS_assign v;
-  primaryexp(ls, &v.v);
-  if (v.v.k == VCALL)  /* stat -> func */
-    SETARG_C(getcode(fs, &v.v), 1);  /* call statement uses no results */
-  else {  /* stat -> assignment */
-    v.prev = NULL;
-    assignment(ls, &v, 1);
-  }
-}
-
-
-static void retstat (LexState *ls) {
-  /* stat -> RETURN explist */
-  FuncState *fs = ls->fs;
-  expdesc e;
-  int first, nret;  /* registers with returned values */
-  luaX_next(ls);  /* skip RETURN */
-  if (block_follow(ls->t.token) || ls->t.token == ';')
-    first = nret = 0;  /* return no values */
-  else {
-    nret = explist1(ls, &e);  /* optional return values */
-    if (hasmultret(e.k)) {
-      luaK_setmultret(fs, &e);
-      if (e.k == VCALL && nret == 1) {  /* tail call? */
-        SET_OPCODE(getcode(fs,&e), OP_TAILCALL);
-        lua_assert(GETARG_A(getcode(fs,&e)) == fs->nactvar);
-      }
-      first = fs->nactvar;
-      nret = LUA_MULTRET;  /* return all values */
-    }
-    else {
-      if (nret == 1)  /* only one single value? */
-        first = luaK_exp2anyreg(fs, &e);
-      else {
-        luaK_exp2nextreg(fs, &e);  /* values must go to the `stack' */
-        first = fs->nactvar;  /* return all `active' values */
-        lua_assert(nret == fs->freereg - first);
-      }
-    }
-  }
-  luaK_ret(fs, first, nret);
-}
-
-
-static int statement (LexState *ls) {
-  int line = ls->linenumber;  /* may be needed for error messages */
-  switch (ls->t.token) {
-    case TK_IF: {  /* stat -> ifstat */
-      ifstat(ls, line);
-      return 0;
-    }
-    case TK_WHILE: {  /* stat -> whilestat */
-      whilestat(ls, line);
-      return 0;
-    }
-    case TK_DO: {  /* stat -> DO block END */
-      luaX_next(ls);  /* skip DO */
-      block(ls);
-      check_match(ls, TK_END, TK_DO, line);
-      return 0;
-    }
-    case TK_FOR: {  /* stat -> forstat */
-      forstat(ls, line);
-      return 0;
-    }
-    case TK_REPEAT: {  /* stat -> repeatstat */
-      repeatstat(ls, line);
-      return 0;
-    }
-    case TK_FUNCTION: {
-      funcstat(ls, line);  /* stat -> funcstat */
-      return 0;
-    }
-    case TK_LOCAL: {  /* stat -> localstat */
-      luaX_next(ls);  /* skip LOCAL */
-      if (testnext(ls, TK_FUNCTION))  /* local function? */
-        localfunc(ls);
-      else
-        localstat(ls);
-      return 0;
-    }
-    case TK_RETURN: {  /* stat -> retstat */
-      retstat(ls);
-      return 1;  /* must be last statement */
-    }
-    case TK_BREAK: {  /* stat -> breakstat */
-      luaX_next(ls);  /* skip BREAK */
-      breakstat(ls);
-      return 1;  /* must be last statement */
-    }
-    default: {
-      exprstat(ls);
-      return 0;  /* to avoid warnings */
-    }
-  }
-}
-
-
-static void chunk (LexState *ls) {
-  /* chunk -> { stat [`;'] } */
-  int islast = 0;
-  enterlevel(ls);
-  while (!islast && !block_follow(ls->t.token)) {
-    islast = statement(ls);
-    testnext(ls, ';');
-    lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg &&
-               ls->fs->freereg >= ls->fs->nactvar);
-    ls->fs->freereg = ls->fs->nactvar;  /* free registers */
-  }
-  leavelevel(ls);
-}
-
-/* }====================================================================== */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/lparser.h
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/lparser.h b/libs/elua/elua_base/src/lparser.h
deleted file mode 100644
index 18836af..0000000
--- a/libs/elua/elua_base/src/lparser.h
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
-** $Id: lparser.h,v 1.57.1.1 2007/12/27 13:02:25 roberto Exp $
-** Lua Parser
-** See Copyright Notice in lua.h
-*/
-
-#ifndef lparser_h
-#define lparser_h
-
-#include "llimits.h"
-#include "lobject.h"
-#include "lzio.h"
-
-
-/*
-** Expression descriptor
-*/
-
-typedef enum {
-  VVOID,	/* no value */
-  VNIL,
-  VTRUE,
-  VFALSE,
-  VK,		/* info = index of constant in `k' */
-  VKNUM,	/* nval = numerical value */
-  VLOCAL,	/* info = local register */
-  VUPVAL,       /* info = index of upvalue in `upvalues' */
-  VGLOBAL,	/* info = index of table; aux = index of global name in `k' */
-  VINDEXED,	/* info = table register; aux = index register (or `k') */
-  VJMP,		/* info = instruction pc */
-  VRELOCABLE,	/* info = instruction pc */
-  VNONRELOC,	/* info = result register */
-  VCALL,	/* info = instruction pc */
-  VVARARG	/* info = instruction pc */
-} expkind;
-
-typedef struct expdesc {
-  expkind k;
-  union {
-    struct { int info, aux; } s;
-    lua_Number nval;
-  } u;
-  int t;  /* patch list of `exit when true' */
-  int f;  /* patch list of `exit when false' */
-} expdesc;
-
-
-typedef struct upvaldesc {
-  lu_byte k;
-  lu_byte info;
-} upvaldesc;
-
-
-struct BlockCnt;  /* defined in lparser.c */
-
-
-/* state needed to generate code for a given function */
-typedef struct FuncState {
-  Proto *f;  /* current function header */
-  Table *h;  /* table to find (and reuse) elements in `k' */
-  struct FuncState *prev;  /* enclosing function */
-  struct LexState *ls;  /* lexical state */
-  struct lua_State *L;  /* copy of the Lua state */
-  struct BlockCnt *bl;  /* chain of current blocks */
-  int pc;  /* next position to code (equivalent to `ncode') */
-  int lasttarget;   /* `pc' of last `jump target' */
-  int jpc;  /* list of pending jumps to `pc' */
-  int freereg;  /* first free register */
-  int nk;  /* number of elements in `k' */
-  int np;  /* number of elements in `p' */
-  short nlocvars;  /* number of elements in `locvars' */
-  lu_byte nactvar;  /* number of active local variables */
-  upvaldesc upvalues[LUAI_MAXUPVALUES];  /* upvalues */
-  unsigned short actvar[LUAI_MAXVARS];  /* declared-variable stack */
-} FuncState;
-
-
-LUAI_FUNC Proto *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff,
-                                            const char *name);
-
-
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/lrodefs.h
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/lrodefs.h b/libs/elua/elua_base/src/lrodefs.h
deleted file mode 100644
index a68e0cf..0000000
--- a/libs/elua/elua_base/src/lrodefs.h
+++ /dev/null
@@ -1,34 +0,0 @@
-/* Read-only tables helper */
-
-#undef LUA_REG_TYPE
-#undef LSTRKEY
-#undef LNILKEY
-#undef LNUMKEY
-#undef LFUNCVAL
-#undef LNUMVAL
-#undef LROVAL
-#undef LNILVAL
-#undef LREGISTER
-
-#if (MIN_OPT_LEVEL > 0) && (LUA_OPTIMIZE_MEMORY >= MIN_OPT_LEVEL)
-#define LUA_REG_TYPE                luaR_entry 
-#define LSTRKEY                     LRO_STRKEY
-#define LNUMKEY                     LRO_NUMKEY
-#define LNILKEY                     LRO_NILKEY
-#define LFUNCVAL                    LRO_FUNCVAL
-#define LNUMVAL                     LRO_NUMVAL
-#define LROVAL                      LRO_ROVAL
-#define LNILVAL                     LRO_NILVAL
-#define LREGISTER(L, name, table)\
-  return 0
-#else
-#define LUA_REG_TYPE                luaL_reg
-#define LSTRKEY(x)                  x
-#define LNILKEY                     NULL
-#define LFUNCVAL(x)                 x
-#define LNILVAL                     NULL
-#define LREGISTER(L, name, table)\
-  luaL_register(L, name, table);\
-  return 1
-#endif
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/lrotable.c
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/lrotable.c b/libs/elua/elua_base/src/lrotable.c
deleted file mode 100644
index 4487841..0000000
--- a/libs/elua/elua_base/src/lrotable.c
+++ /dev/null
@@ -1,134 +0,0 @@
-/* Read-only tables for Lua */
-
-#include <string.h>
-#include "lrotable.h"
-#include "lua.h"
-#include "lauxlib.h"
-#include "lstring.h"
-#include "lobject.h"
-#include "lapi.h"
-
-/* Local defines */
-#define LUAR_FINDFUNCTION     0
-#define LUAR_FINDVALUE        1
-
-/* Externally defined read-only table array */
-extern const luaR_table lua_rotable[];
-
-/* Find a global "read only table" in the constant lua_rotable array */
-void* luaR_findglobal(const char *name, unsigned len) {
-  unsigned i;    
-  
-  if (strlen(name) > LUA_MAX_ROTABLE_NAME)
-    return NULL;
-  for (i=0; lua_rotable[i].name; i ++)
-    if (*lua_rotable[i].name != '\0' && strlen(lua_rotable[i].name) == len && !strncmp(lua_rotable[i].name, name, len)) {
-      return (void*)(lua_rotable[i].pentries);
-    }
-  return NULL;
-}
-
-/* Find an entry in a rotable and return it */
-static const TValue* luaR_auxfind(const luaR_entry *pentry, const char *strkey, luaR_numkey numkey, unsigned *ppos) {
-  const TValue *res = NULL;
-  unsigned i = 0;
-  
-  if (pentry == NULL)
-    return NULL;  
-  while(pentry->key.type != LUA_TNIL) {
-    if ((strkey && (pentry->key.type == LUA_TSTRING) && (!strcmp(pentry->key.id.strkey, strkey))) || 
-        (!strkey && (pentry->key.type == LUA_TNUMBER) && ((luaR_numkey)pentry->key.id.numkey == numkey))) {
-      res = &pentry->value;
-      break;
-    }
-    i ++; pentry ++;
-  }
-  if (res && ppos)
-    *ppos = i;   
-  return res;
-}
-
-int luaR_findfunction(lua_State *L, const luaR_entry *ptable) {
-  const TValue *res = NULL;
-  const char *key = luaL_checkstring(L, 2);
-    
-  res = luaR_auxfind(ptable, key, 0, NULL);  
-  if (res && ttislightfunction(res)) {
-    luaA_pushobject(L, res);
-    return 1;
-  }
-  else
-    return 0;
-}
-
-/* Find an entry in a rotable and return its type 
-   If "strkey" is not NULL, the function will look for a string key,
-   otherwise it will look for a number key */
-const TValue* luaR_findentry(void *data, const char *strkey, luaR_numkey numkey, unsigned *ppos) {
-  return luaR_auxfind((const luaR_entry*)data, strkey, numkey, ppos);
-}
-
-/* Find the metatable of a given table */
-void* luaR_getmeta(void *data) {
-#ifdef LUA_META_ROTABLES
-  const TValue *res = luaR_auxfind((const luaR_entry*)data, "__metatable", 0, NULL);
-  return res && ttisrotable(res) ? rvalue(res) : NULL;
-#else
-  return NULL;
-#endif
-}
-
-static void luaR_next_helper(lua_State *L, const luaR_entry *pentries, int pos, TValue *key, TValue *val) {
-  setnilvalue(key);
-  setnilvalue(val);
-  if (pentries[pos].key.type != LUA_TNIL) {
-    /* Found an entry */
-    if (pentries[pos].key.type == LUA_TSTRING)
-      setsvalue(L, key, luaS_newro(L, pentries[pos].key.id.strkey))
-    else
-      setnvalue(key, (lua_Number)pentries[pos].key.id.numkey)
-   setobj2s(L, val, &pentries[pos].value);
-  }
-}
-/* next (used for iteration) */
-void luaR_next(lua_State *L, void *data, TValue *key, TValue *val) {
-  const luaR_entry* pentries = (const luaR_entry*)data;
-  char strkey[LUA_MAX_ROTABLE_NAME + 1], *pstrkey = NULL;
-  luaR_numkey numkey = 0;
-  unsigned keypos;
-  
-  /* Special case: if key is nil, return the first element of the rotable */
-  if (ttisnil(key)) 
-    luaR_next_helper(L, pentries, 0, key, val);
-  else if (ttisstring(key) || ttisnumber(key)) {
-    /* Find the previoud key again */  
-    if (ttisstring(key)) {
-      luaR_getcstr(strkey, rawtsvalue(key), LUA_MAX_ROTABLE_NAME);          
-      pstrkey = strkey;
-    } else   
-      numkey = (luaR_numkey)nvalue(key);
-    luaR_findentry(data, pstrkey, numkey, &keypos);
-    /* Advance to next key */
-    keypos ++;    
-    luaR_next_helper(L, pentries, keypos, key, val);
-  }
-}
-
-/* Convert a Lua string to a C string */
-void luaR_getcstr(char *dest, const TString *src, size_t maxsize) {
-  if (src->tsv.len+1 > maxsize)
-    dest[0] = '\0';
-  else {
-    memcpy(dest, getstr(src), src->tsv.len);
-    dest[src->tsv.len] = '\0';
-  } 
-}
-
-/* Return 1 if the given pointer is a rotable */
-#ifdef LUA_META_ROTABLES
-extern char stext;
-extern char etext;
-int luaR_isrotable(void *p) {
-  return &stext <= ( char* )p && ( char* )p <= &etext;
-}
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/lrotable.h
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/lrotable.h b/libs/elua/elua_base/src/lrotable.h
deleted file mode 100644
index 27de84a..0000000
--- a/libs/elua/elua_base/src/lrotable.h
+++ /dev/null
@@ -1,77 +0,0 @@
-/* Read-only tables for Lua */
-
-#ifndef lrotable_h
-#define lrotable_h
-
-#include "lua.h"
-#include "llimits.h"
-#include "lobject.h"
-#include "luaconf.h"
-
-/* Macros one can use to define rotable entries */
-#ifndef LUA_PACK_VALUE
-#define LRO_FUNCVAL(v)  {{.p = v}, LUA_TLIGHTFUNCTION}
-#define LRO_NUMVAL(v)   {{.n = v}, LUA_TNUMBER}
-#define LRO_ROVAL(v)    {{.p = (void*)v}, LUA_TROTABLE}
-#define LRO_NILVAL      {{.p = NULL}, LUA_TNIL}
-#else // #ifndef LUA_PACK_VALUE
-#define LRO_NUMVAL(v)   {.value.n = v}
-#ifdef ELUA_ENDIAN_LITTLE
-#define LRO_FUNCVAL(v)  {{(int)v, add_sig(LUA_TLIGHTFUNCTION)}}
-#define LRO_ROVAL(v)    {{(int)v, add_sig(LUA_TROTABLE)}}
-#define LRO_NILVAL      {{0, add_sig(LUA_TNIL)}}
-#else // #ifdef ELUA_ENDIAN_LITTLE
-#define LRO_FUNCVAL(v)  {{add_sig(LUA_TLIGHTFUNCTION), (int)v}}
-#define LRO_ROVAL(v)    {{add_sig(LUA_TROTABLE), (int)v}}
-#define LRO_NILVAL      {{add_sig(LUA_TNIL), 0}}
-#endif // #ifdef ELUA_ENDIAN_LITTLE
-#endif // #ifndef LUA_PACK_VALUE
-
-#define LRO_STRKEY(k)   {LUA_TSTRING, {.strkey = k}}
-#define LRO_NUMKEY(k)   {LUA_TNUMBER, {.numkey = k}}
-#define LRO_NILKEY      {LUA_TNIL, {.strkey=NULL}}
-
-/* Maximum length of a rotable name and of a string key*/
-#define LUA_MAX_ROTABLE_NAME      32
-
-/* Type of a numeric key in a rotable */
-typedef int luaR_numkey;
-
-/* The next structure defines the type of a key */
-typedef struct
-{
-  int type;
-  union
-  {
-    const char*   strkey;
-    luaR_numkey   numkey;
-  } id;
-} luaR_key;
-
-/* An entry in the read only table */
-typedef struct
-{
-  const luaR_key key;
-  const TValue value;
-} luaR_entry;
-
-/* A rotable */
-typedef struct
-{
-  const char *name;
-  const luaR_entry *pentries;
-} luaR_table;
-
-void* luaR_findglobal(const char *key, unsigned len);
-int luaR_findfunction(lua_State *L, const luaR_entry *ptable);
-const TValue* luaR_findentry(void *data, const char *strkey, luaR_numkey numkey, unsigned *ppos);
-void luaR_getcstr(char *dest, const TString *src, size_t maxsize);
-void luaR_next(lua_State *L, void *data, TValue *key, TValue *val);
-void* luaR_getmeta(void *data);
-#ifdef LUA_META_ROTABLES
-int luaR_isrotable(void *p);
-#else
-#define luaR_isrotable(p)     (0)
-#endif
-
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/lstate.c
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/lstate.c b/libs/elua/elua_base/src/lstate.c
deleted file mode 100644
index a0a7107..0000000
--- a/libs/elua/elua_base/src/lstate.c
+++ /dev/null
@@ -1,258 +0,0 @@
-/*
-** $Id: lstate.c,v 2.36.1.2 2008/01/03 15:20:39 roberto Exp $
-** Global State
-** See Copyright Notice in lua.h
-*/
-
-
-#include <stddef.h>
-
-#define lstate_c
-#define LUA_CORE
-
-#include "lua.h"
-
-#include "ldebug.h"
-#include "ldo.h"
-#include "lfunc.h"
-#include "lgc.h"
-#include "llex.h"
-#include "lmem.h"
-#include "lstate.h"
-#include "lstring.h"
-#include "ltable.h"
-#include "ltm.h"
-// BogdanM: modified for Lua interrupt support
-#ifndef LUA_CROSS_COMPILER
-#include "platform_conf.h"
-#include "elua_int.h"
-#include "platform.h"
-// BogdanM: linenoise clenaup
-#include "linenoise.h"
-#endif
-
-#define state_size(x)	(sizeof(x) + LUAI_EXTRASPACE)
-#define fromstate(l)	(cast(lu_byte *, (l)) - LUAI_EXTRASPACE)
-#define tostate(l)   (cast(lua_State *, cast(lu_byte *, l) + LUAI_EXTRASPACE))
-
-
-/*
-** Main thread combines a thread state and the global state
-*/
-typedef struct LG {
-  lua_State l;
-  global_State g;
-} LG;
-  
-
-
-static void stack_init (lua_State *L1, lua_State *L) {
-  /* initialize CallInfo array */
-  L1->base_ci = luaM_newvector(L, BASIC_CI_SIZE, CallInfo);
-  L1->ci = L1->base_ci;
-  L1->size_ci = BASIC_CI_SIZE;
-  L1->end_ci = L1->base_ci + L1->size_ci - 1;
-  /* initialize stack array */
-  L1->stack = luaM_newvector(L, BASIC_STACK_SIZE + EXTRA_STACK, TValue);
-  L1->stacksize = BASIC_STACK_SIZE + EXTRA_STACK;
-  L1->top = L1->stack;
-  L1->stack_last = L1->stack+(L1->stacksize - EXTRA_STACK)-1;
-  /* initialize first ci */
-  L1->ci->func = L1->top;
-  setnilvalue(L1->top++);  /* `function' entry for this `ci' */
-  L1->base = L1->ci->base = L1->top;
-  L1->ci->top = L1->top + LUA_MINSTACK;
-}
-
-
-static void freestack (lua_State *L, lua_State *L1) {
-  luaM_freearray(L, L1->base_ci, L1->size_ci, CallInfo);
-  luaM_freearray(L, L1->stack, L1->stacksize, TValue);
-}
-
-
-/*
-** open parts that may cause memory-allocation errors
-*/
-static void f_luaopen (lua_State *L, void *ud) {
-  global_State *g = G(L);
-  UNUSED(ud);
-  stack_init(L, L);  /* init stack */
-  sethvalue(L, gt(L), luaH_new(L, 0, 2));  /* table of globals */
-  sethvalue(L, registry(L), luaH_new(L, 0, 2));  /* registry */
-  luaS_resize(L, MINSTRTABSIZE);  /* initial size of string table */
-  luaT_init(L);
-  luaX_init(L);
-  luaS_fix(luaS_newliteral(L, MEMERRMSG));
-  g->GCthreshold = 4*g->totalbytes;
-}
-
-
-static void preinit_state (lua_State *L, global_State *g) {
-  G(L) = g;
-  L->stack = NULL;
-  L->stacksize = 0;
-  L->errorJmp = NULL;
-  L->hook = NULL;
-  L->hookmask = 0;
-  L->basehookcount = 0;
-  L->allowhook = 1;
-  resethookcount(L);
-  L->openupval = NULL;
-  L->size_ci = 0;
-  L->nCcalls = L->baseCcalls = 0;
-  L->status = 0;
-  L->base_ci = L->ci = NULL;
-  L->savedpc = NULL;
-  L->errfunc = 0;
-  setnilvalue(gt(L));
-}
-
-
-static void close_state (lua_State *L) {
-  global_State *g = G(L);
-  luaF_close(L, L->stack);  /* close all upvalues for this thread */
-  luaC_freeall(L);  /* collect all objects */
-  lua_assert(g->rootgc == obj2gco(L));
-  lua_assert(g->strt.nuse == 0);
-  luaM_freearray(L, G(L)->strt.hash, G(L)->strt.size, TString *);
-  luaZ_freebuffer(L, &g->buff);
-  freestack(L, L);
-  lua_assert(g->totalbytes == sizeof(LG));
-  (*g->frealloc)(g->ud, fromstate(L), state_size(LG), 0);
-}
-
-
-lua_State *luaE_newthread (lua_State *L) {
-  lua_State *L1 = tostate(luaM_malloc(L, state_size(lua_State)));
-  luaC_link(L, obj2gco(L1), LUA_TTHREAD);
-  setthvalue(L, L->top, L1); /* put thread on stack */
-  incr_top(L);
-  preinit_state(L1, G(L));
-  stack_init(L1, L);  /* init stack */
-  setobj2n(L, gt(L1), gt(L));  /* share table of globals */
-  L1->hookmask = L->hookmask;
-  L1->basehookcount = L->basehookcount;
-  L1->hook = L->hook;
-  resethookcount(L1);
-  lua_assert(!isdead(G(L), obj2gco(L1)));
-  L->top--; /* remove thread from stack */
-  return L1;
-}
-
-
-void luaE_freethread (lua_State *L, lua_State *L1) {
-  luaF_close(L1, L1->stack);  /* close all upvalues for this thread */
-  lua_assert(L1->openupval == NULL);
-  luai_userstatefree(L1);
-  freestack(L, L1);
-  luaM_freemem(L, fromstate(L1), state_size(lua_State));
-}
-
-
-LUA_API lua_State *lua_newstate (lua_Alloc f, void *ud) {
-  int i;
-  lua_State *L;
-  global_State *g;
-  void *l = (*f)(ud, NULL, 0, state_size(LG));
-  if (l == NULL) return NULL;
-  L = tostate(l);
-  g = &((LG *)L)->g;
-  L->next = NULL;
-  L->tt = LUA_TTHREAD;
-  g->currentwhite = bit2mask(WHITE0BIT, FIXEDBIT);
-  L->marked = luaC_white(g);
-  set2bits(L->marked, FIXEDBIT, SFIXEDBIT);
-  preinit_state(L, g);
-  g->frealloc = f;
-  g->ud = ud;
-  g->mainthread = L;
-  g->uvhead.u.l.prev = &g->uvhead;
-  g->uvhead.u.l.next = &g->uvhead;
-  g->GCthreshold = 0;  /* mark it as unfinished state */
-  g->estimate = 0;
-  g->strt.size = 0;
-  g->strt.nuse = 0;
-  g->strt.hash = NULL;
-  setnilvalue(registry(L));
-  luaZ_initbuffer(L, &g->buff);
-  g->panic = NULL;
-  g->gcstate = GCSpause;
-  g->gcflags = GCFlagsNone;
-  g->rootgc = obj2gco(L);
-  g->sweepstrgc = 0;
-  g->sweepgc = &g->rootgc;
-  g->gray = NULL;
-  g->grayagain = NULL;
-  g->weak = NULL;
-  g->tmudata = NULL;
-  g->totalbytes = sizeof(LG);
-  g->memlimit = 0;
-  g->gcpause = LUAI_GCPAUSE;
-  g->gcstepmul = LUAI_GCMUL;
-  g->gcdept = 0;
-#ifdef EGC_INITIAL_MODE
-  g->egcmode = EGC_INITIAL_MODE;
-#else
-  g->egcmode = 0;
-#endif
-#ifdef EGC_INITIAL_MEMLIMIT
-  g->memlimit = EGC_INITIAL_MEMLIMIT;
-#else
-  g->memlimit = 0;
-#endif
-  for (i=0; i<NUM_TAGS; i++) g->mt[i] = NULL;
-  if (luaD_rawrunprotected(L, f_luaopen, NULL) != 0) {
-    /* memory allocation error: free partial state */
-    close_state(L);
-    L = NULL;
-  }
-  else
-    luai_userstateopen(L);
-  return L;
-}
-
-
-static void callallgcTM (lua_State *L, void *ud) {
-  UNUSED(ud);
-  luaC_callGCTM(L);  /* call GC metamethods for all udata */
-}
-
-// BogdanM: modified for eLua interrupt support
-extern lua_State *luaL_newstate (void);
-static lua_State *lua_crtstate;
-
-lua_State *lua_open(void) {
-  lua_crtstate = luaL_newstate(); 
-  return lua_crtstate;
-}
-
-lua_State *lua_getstate(void) {
-  return lua_crtstate;
-}
-LUA_API void lua_close (lua_State *L) {
-#ifndef LUA_CROSS_COMPILER  
-  int oldstate = platform_cpu_set_global_interrupts( PLATFORM_CPU_DISABLE );
-  lua_sethook( L, NULL, 0, 0 );
-  lua_crtstate = NULL;
-  lua_pushnil( L );
-  lua_rawseti( L, LUA_REGISTRYINDEX, LUA_INT_HANDLER_KEY );
-  elua_int_cleanup();
-  platform_cpu_set_global_interrupts( oldstate );
-  linenoise_cleanup( LINENOISE_ID_LUA );
-#endif  
-  L = G(L)->mainthread;  /* only the main thread can be closed */
-  lua_lock(L);
-  luaF_close(L, L->stack);  /* close all upvalues for this thread */
-  luaC_separateudata(L, 1);  /* separate udata that have GC metamethods */
-  L->errfunc = 0;  /* no error function during GC metamethods */
-  do {  /* repeat until no more errors */
-    L->ci = L->base_ci;
-    L->base = L->top = L->ci->base;
-    L->nCcalls = L->baseCcalls = 0;
-  } while (luaD_rawrunprotected(L, callallgcTM, NULL) != 0);
-  lua_assert(G(L)->tmudata == NULL);
-  luai_userstateclose(L);
-  close_state(L);
-}
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/lstate.h
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/lstate.h b/libs/elua/elua_base/src/lstate.h
deleted file mode 100644
index 1b3c363..0000000
--- a/libs/elua/elua_base/src/lstate.h
+++ /dev/null
@@ -1,171 +0,0 @@
-/*
-** $Id: lstate.h,v 2.24.1.2 2008/01/03 15:20:39 roberto Exp $
-** Global State
-** See Copyright Notice in lua.h
-*/
-
-#ifndef lstate_h
-#define lstate_h
-
-#include "lua.h"
-
-#include "lobject.h"
-#include "ltm.h"
-#include "lzio.h"
-
-
-
-struct lua_longjmp;  /* defined in ldo.c */
-
-
-/* table of globals */
-#define gt(L)	(&L->l_gt)
-
-/* registry */
-#define registry(L)	(&G(L)->l_registry)
-
-
-/* extra stack space to handle TM calls and some other extras */
-#define EXTRA_STACK   5
-
-
-#define BASIC_CI_SIZE           8
-
-#define BASIC_STACK_SIZE        (2*LUA_MINSTACK)
-
-
-
-typedef struct stringtable {
-  GCObject **hash;
-  lu_int32 nuse;  /* number of elements */
-  int size;
-} stringtable;
-
-
-/*
-** informations about a call
-*/
-typedef struct CallInfo {
-  StkId base;  /* base for this function */
-  StkId func;  /* function index in the stack */
-  StkId	top;  /* top for this function */
-  const Instruction *savedpc;
-  int nresults;  /* expected number of results from this function */
-  int tailcalls;  /* number of tail calls lost under this entry */
-} CallInfo;
-
-
-
-#define curr_func(L)	(ttisfunction(L->ci->func) ? clvalue(L->ci->func) : NULL)
-#define ci_func(ci)	(ttisfunction((ci)->func) ? clvalue((ci)->func) : NULL)
-#define f_isLua(ci)	(!ttislightfunction((ci)->func) && !ci_func(ci)->c.isC)
-#define isLua(ci)	(ttisfunction((ci)->func) && f_isLua(ci))
-
-
-/*
-** `global state', shared by all threads of this state
-*/
-typedef struct global_State {
-  stringtable strt;  /* hash table for strings */
-  lua_Alloc frealloc;  /* function to reallocate memory */
-  void *ud;         /* auxiliary data to `frealloc' */
-  lu_byte currentwhite;
-  lu_byte gcstate;  /* state of garbage collector */
-  lu_byte gcflags;  /* flags for the garbage collector */
-  int sweepstrgc;  /* position of sweep in `strt' */
-  GCObject *rootgc;  /* list of all collectable objects */
-  GCObject **sweepgc;  /* position of sweep in `rootgc' */
-  GCObject *gray;  /* list of gray objects */
-  GCObject *grayagain;  /* list of objects to be traversed atomically */
-  GCObject *weak;  /* list of weak tables (to be cleared) */
-  GCObject *tmudata;  /* last element of list of userdata to be GC */
-  Mbuffer buff;  /* temporary buffer for string concatentation */
-  lu_mem GCthreshold;
-  lu_mem totalbytes;  /* number of bytes currently allocated */
-  lu_mem memlimit;  /* maximum number of bytes that can be allocated, 0 = no limit. */
-  lu_mem estimate;  /* an estimate of number of bytes actually in use */
-  lu_mem gcdept;  /* how much GC is `behind schedule' */
-  int gcpause;  /* size of pause between successive GCs */
-  int gcstepmul;  /* GC `granularity' */
-  int egcmode;    /* emergency garbage collection operation mode */
-  lua_CFunction panic;  /* to be called in unprotected errors */
-  TValue l_registry;
-  struct lua_State *mainthread;
-  UpVal uvhead;  /* head of double-linked list of all open upvalues */
-  struct Table *mt[NUM_TAGS];  /* metatables for basic types */
-  TString *tmname[TM_N];  /* array with tag-method names */
-} global_State;
-
-
-/*
-** `per thread' state
-*/
-struct lua_State {
-  CommonHeader;
-  lu_byte status;
-  StkId top;  /* first free slot in the stack */
-  StkId base;  /* base of current function */
-  global_State *l_G;
-  CallInfo *ci;  /* call info for current function */
-  const Instruction *savedpc;  /* `savedpc' of current function */
-  StkId stack_last;  /* last free slot in the stack */
-  StkId stack;  /* stack base */
-  CallInfo *end_ci;  /* points after end of ci array*/
-  CallInfo *base_ci;  /* array of CallInfo's */
-  int stacksize;
-  int size_ci;  /* size of array `base_ci' */
-  unsigned short nCcalls;  /* number of nested C calls */
-  unsigned short baseCcalls;  /* nested C calls when resuming coroutine */
-  lu_byte hookmask;
-  lu_byte allowhook;
-  int basehookcount;
-  int hookcount;
-  lua_Hook hook;
-  TValue l_gt;  /* table of globals */
-  TValue env;  /* temporary place for environments */
-  GCObject *openupval;  /* list of open upvalues in this stack */
-  GCObject *gclist;
-  struct lua_longjmp *errorJmp;  /* current error recover point */
-  ptrdiff_t errfunc;  /* current error handling function (stack index) */
-};
-
-
-#define G(L)	(L->l_G)
-
-
-/*
-** Union of all collectable objects
-*/
-union GCObject {
-  GCheader gch;
-  union TString ts;
-  union Udata u;
-  union Closure cl;
-  struct Table h;
-  struct Proto p;
-  struct UpVal uv;
-  struct lua_State th;  /* thread */
-};
-
-
-/* macros to convert a GCObject into a specific value */
-#define rawgco2ts(o)	check_exp((o)->gch.tt == LUA_TSTRING, &((o)->ts))
-#define gco2ts(o)	(&rawgco2ts(o)->tsv)
-#define rawgco2u(o)	check_exp((o)->gch.tt == LUA_TUSERDATA, &((o)->u))
-#define gco2u(o)	(&rawgco2u(o)->uv)
-#define gco2cl(o)	check_exp((o)->gch.tt == LUA_TFUNCTION, &((o)->cl))
-#define gco2h(o)	check_exp((o)->gch.tt == LUA_TTABLE, &((o)->h))
-#define gco2p(o)	check_exp((o)->gch.tt == LUA_TPROTO, &((o)->p))
-#define gco2uv(o)	check_exp((o)->gch.tt == LUA_TUPVAL, &((o)->uv))
-#define ngcotouv(o) \
-	check_exp((o) == NULL || (o)->gch.tt == LUA_TUPVAL, &((o)->uv))
-#define gco2th(o)	check_exp((o)->gch.tt == LUA_TTHREAD, &((o)->th))
-
-/* macro to convert any Lua object into a GCObject */
-#define obj2gco(v)	(cast(GCObject *, (v)))
-
-LUAI_FUNC lua_State *luaE_newthread (lua_State *L);
-LUAI_FUNC void luaE_freethread (lua_State *L, lua_State *L1);
-
-#endif
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/lstring.c
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/lstring.c b/libs/elua/elua_base/src/lstring.c
deleted file mode 100644
index 92d0148..0000000
--- a/libs/elua/elua_base/src/lstring.c
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
-** $Id: lstring.c,v 2.8.1.1 2007/12/27 13:02:25 roberto Exp $
-** String table (keeps all strings handled by Lua)
-** See Copyright Notice in lua.h
-*/
-
-
-#include <string.h>
-
-#define lstring_c
-#define LUA_CORE
-
-#include "lua.h"
-
-#include "lmem.h"
-#include "lobject.h"
-#include "lstate.h"
-#include "lstring.h"
-
-#define LUAS_READONLY_STRING      1
-#define LUAS_REGULAR_STRING       0
-
-void luaS_resize (lua_State *L, int newsize) {
-  stringtable *tb;
-  int i;
-  tb = &G(L)->strt;
-  if (luaC_sweepstrgc(L) || newsize == tb->size || is_resizing_strings_gc(L))
-    return;  /* cannot resize during GC traverse or doesn't need to be resized */
-  set_resizing_strings_gc(L);
-  if (newsize > tb->size) {
-    luaM_reallocvector(L, tb->hash, tb->size, newsize, GCObject *);
-    for (i=tb->size; i<newsize; i++) tb->hash[i] = NULL;
-  }
-  /* rehash */
-  for (i=0; i<tb->size; i++) {
-    GCObject *p = tb->hash[i];
-    tb->hash[i] = NULL;
-    while (p) {  /* for each node in the list */
-      GCObject *next = p->gch.next;  /* save next */
-      unsigned int h = gco2ts(p)->hash;
-      int h1 = lmod(h, newsize);  /* new position */
-      lua_assert(cast_int(h%newsize) == lmod(h, newsize));
-      p->gch.next = tb->hash[h1];  /* chain it */
-      tb->hash[h1] = p;
-      p = next;
-    }
-  }
-  if (newsize < tb->size)
-    luaM_reallocvector(L, tb->hash, tb->size, newsize, GCObject *);
-  tb->size = newsize;
-  unset_resizing_strings_gc(L);
-}
-
-static TString *newlstr (lua_State *L, const char *str, size_t l,
-                                       unsigned int h, int readonly) {
-  TString *ts;
-  stringtable *tb;
-  if (l+1 > (MAX_SIZET - sizeof(TString))/sizeof(char))
-    luaM_toobig(L);
-  tb = &G(L)->strt;
-  if ((tb->nuse + 1) > cast(lu_int32, tb->size) && tb->size <= MAX_INT/2)
-    luaS_resize(L, tb->size*2);  /* too crowded */
-  ts = cast(TString *, luaM_malloc(L, readonly ? sizeof(char**)+sizeof(TString) : (l+1)*sizeof(char)+sizeof(TString)));
-  ts->tsv.len = l;
-  ts->tsv.hash = h;
-  ts->tsv.marked = luaC_white(G(L));
-  ts->tsv.tt = LUA_TSTRING;
-  if (!readonly) {
-    memcpy(ts+1, str, l*sizeof(char));
-    ((char *)(ts+1))[l] = '\0';  /* ending 0 */
-  } else {
-    *(char **)(ts+1) = (char *)str;
-    luaS_readonly(ts);
-  }
-  h = lmod(h, tb->size);
-  ts->tsv.next = tb->hash[h];  /* chain new entry */
-  tb->hash[h] = obj2gco(ts);
-  tb->nuse++;
-  return ts;
-}
-
-
-static TString *luaS_newlstr_helper (lua_State *L, const char *str, size_t l, int readonly) {
-  GCObject *o;
-  unsigned int h = cast(unsigned int, l);  /* seed */
-  size_t step = (l>>5)+1;  /* if string is too long, don't hash all its chars */
-  size_t l1;
-  for (l1=l; l1>=step; l1-=step)  /* compute hash */
-    h = h ^ ((h<<5)+(h>>2)+cast(unsigned char, str[l1-1]));
-  for (o = G(L)->strt.hash[lmod(h, G(L)->strt.size)];
-       o != NULL;
-       o = o->gch.next) {
-    TString *ts = rawgco2ts(o);
-    if (ts->tsv.len == l && (memcmp(str, getstr(ts), l) == 0)) {
-      /* string may be dead */
-      if (isdead(G(L), o)) changewhite(o);
-      return ts;
-    }
-  }
-  return newlstr(L, str, l, h, readonly);  /* not found */
-}
-
-extern char stext;
-extern char etext;
-
-static int lua_is_ptr_in_ro_area(const char *p) {
-#ifdef LUA_CROSS_COMPILER
-  return 0;
-#else
-  return p >= &stext && p <= &etext;
-#endif
-}
-
-TString *luaS_newlstr (lua_State *L, const char *str, size_t l) {
-  // If the pointer is in a read-only memory and the string is at least 4 chars in length,
-  // create it as a read-only string instead
-  if(lua_is_ptr_in_ro_area(str) && l+1 > sizeof(char**) && l == strlen(str))
-    return luaS_newlstr_helper(L, str, l, LUAS_READONLY_STRING);
-  else
-    return luaS_newlstr_helper(L, str, l, LUAS_REGULAR_STRING);
-}
-
-
-LUAI_FUNC TString *luaS_newrolstr (lua_State *L, const char *str, size_t l) {
-  if(l+1 > sizeof(char**) && l == strlen(str))
-    return luaS_newlstr_helper(L, str, l, LUAS_READONLY_STRING);
-  else // no point in creating a RO string, as it would actually be larger
-    return luaS_newlstr_helper(L, str, l, LUAS_REGULAR_STRING);
-}
-
-
-Udata *luaS_newudata (lua_State *L, size_t s, Table *e) {
-  Udata *u;
-  if (s > MAX_SIZET - sizeof(Udata))
-    luaM_toobig(L);
-  u = cast(Udata *, luaM_malloc(L, s + sizeof(Udata)));
-  u->uv.marked = luaC_white(G(L));  /* is not finalized */
-  u->uv.tt = LUA_TUSERDATA;
-  u->uv.len = s;
-  u->uv.metatable = NULL;
-  u->uv.env = e;
-  /* chain it on udata list (after main thread) */
-  u->uv.next = G(L)->mainthread->next;
-  G(L)->mainthread->next = obj2gco(u);
-  return u;
-}
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/lstring.h
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/lstring.h b/libs/elua/elua_base/src/lstring.h
deleted file mode 100644
index 442c9fc..0000000
--- a/libs/elua/elua_base/src/lstring.h
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
-** $Id: lstring.h,v 1.43.1.1 2007/12/27 13:02:25 roberto Exp $
-** String table (keep all strings handled by Lua)
-** See Copyright Notice in lua.h
-*/
-
-#ifndef lstring_h
-#define lstring_h
-
-
-#include "lgc.h"
-#include "lobject.h"
-#include "lstate.h"
-
-
-#define sizestring(s) (sizeof(union TString)+(luaS_isreadonly(s) ? sizeof(char **) : ((s)->len+1)*sizeof(char)))
-
-#define sizeudata(u)	(sizeof(union Udata)+(u)->len)
-
-#define luaS_new(L, s)	(luaS_newlstr(L, s, strlen(s)))
-#define luaS_newro(L, s)  (luaS_newrolstr(L, s, strlen(s)))
-#define luaS_newliteral(L, s)  (luaS_newlstr(L, "" s, \
-                                  (sizeof(s)/sizeof(char))-1))
-
-#define luaS_fix(s)	l_setbit((s)->tsv.marked, FIXEDBIT)
-#define luaS_readonly(s) l_setbit((s)->tsv.marked, READONLYBIT)
-#define luaS_isreadonly(s) testbit((s)->marked, READONLYBIT)
-
-LUAI_FUNC void luaS_resize (lua_State *L, int newsize);
-LUAI_FUNC Udata *luaS_newudata (lua_State *L, size_t s, Table *e);
-LUAI_FUNC TString *luaS_newlstr (lua_State *L, const char *str, size_t l);
-LUAI_FUNC TString *luaS_newrolstr (lua_State *L, const char *str, size_t l);
-
-#endif


[32/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/strpbrk.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/strpbrk.c b/libc/baselibc/src/strpbrk.c
new file mode 100644
index 0000000..1873971
--- /dev/null
+++ b/libc/baselibc/src/strpbrk.c
@@ -0,0 +1,55 @@
+/*
+FUNCTION
+	<<strpbrk>>---find characters in string
+
+INDEX
+	strpbrk
+
+ANSI_SYNOPSIS
+	#include <string.h>
+	char *strpbrk(const char *<[s1]>, const char *<[s2]>);
+
+TRAD_SYNOPSIS
+	#include <string.h>
+	char *strpbrk(<[s1]>, <[s2]>)
+	char *<[s1]>;
+	char *<[s2]>;
+
+DESCRIPTION
+	This function locates the first occurence in the string
+	pointed to by <[s1]> of any character in string pointed to by
+	<[s2]> (excluding the terminating null character).
+
+RETURNS
+	<<strpbrk>> returns a pointer to the character found in <[s1]>, or a
+	null pointer if no character from <[s2]> occurs in <[s1]>.
+
+PORTABILITY
+<<strpbrk>> requires no supporting OS subroutines.
+*/
+
+#include <string.h>
+
+char *strpbrk(const char *s1, const char *s2)
+{
+  const char *c = s2;
+  if (!*s1)
+    return (char *) NULL;
+
+  while (*s1)
+    {
+      for (c = s2; *c; c++)
+	{
+	  if (*s1 == *c)
+	    break;
+	}
+      if (*c)
+	break;
+      s1++;
+    }
+
+  if (*c == '\0')
+    s1 = NULL;
+
+  return (char *) s1;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/strrchr.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/strrchr.c b/libc/baselibc/src/strrchr.c
new file mode 100644
index 0000000..69b238f
--- /dev/null
+++ b/libc/baselibc/src/strrchr.c
@@ -0,0 +1,19 @@
+/*
+ * strrchr.c
+ */
+
+#include <string.h>
+
+char *strrchr(const char *s, int c)
+{
+	const char *found = NULL;
+
+	while (*s) {
+		if (*s == (char)c)
+			found = s;
+		s++;
+	}
+
+	return (char *)found;
+}
+

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/strsep.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/strsep.c b/libc/baselibc/src/strsep.c
new file mode 100644
index 0000000..44e76bd
--- /dev/null
+++ b/libc/baselibc/src/strsep.c
@@ -0,0 +1,21 @@
+/*
+ * strsep.c
+ */
+
+#include <string.h>
+
+char *strsep(char **stringp, const char *delim)
+{
+	char *s = *stringp;
+	char *e;
+
+	if (!s)
+		return NULL;
+
+	e = strpbrk(s, delim);
+	if (e)
+		*e++ = '\0';
+
+	*stringp = e;
+	return s;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/strspn.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/strspn.c b/libc/baselibc/src/strspn.c
new file mode 100644
index 0000000..e8b213c
--- /dev/null
+++ b/libc/baselibc/src/strspn.c
@@ -0,0 +1,56 @@
+/*
+FUNCTION
+	<<strspn>>---find initial match
+
+INDEX
+	strspn
+
+ANSI_SYNOPSIS
+	#include <string.h>
+	size_t strspn(const char *<[s1]>, const char *<[s2]>);
+
+TRAD_SYNOPSIS
+	#include <string.h>
+	size_t strspn(<[s1]>, <[s2]>)
+	char *<[s1]>;
+	char *<[s2]>;
+
+DESCRIPTION
+	This function computes the length of the initial segment of
+	the string pointed to by <[s1]> which consists entirely of
+	characters from the string pointed to by <[s2]> (excluding the
+	terminating null character).
+
+RETURNS
+	<<strspn>> returns the length of the segment found.
+
+PORTABILITY
+<<strspn>> is ANSI C.
+
+<<strspn>> requires no supporting OS subroutines.
+
+QUICKREF
+	strspn ansi pure
+*/
+
+#include <string.h>
+
+size_t strspn(const char *s1, const char *s2)
+{
+  const char *s = s1;
+  const char *c;
+
+  while (*s1)
+    {
+      for (c = s2; *c; c++)
+	{
+	  if (*s1 == *c)
+	    break;
+	}
+      if (*c == '\0')
+	break;
+      s1++;
+    }
+
+  return s1 - s;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/strstr.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/strstr.c b/libc/baselibc/src/strstr.c
new file mode 100644
index 0000000..8850858
--- /dev/null
+++ b/libc/baselibc/src/strstr.c
@@ -0,0 +1,11 @@
+/*
+ * strstr.c
+ */
+
+#include <string.h>
+
+char *strstr(const char *haystack, const char *needle)
+{
+	return (char *)memmem(haystack, strlen(haystack), needle,
+			      strlen(needle));
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/strtoimax.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/strtoimax.c b/libc/baselibc/src/strtoimax.c
new file mode 100644
index 0000000..cd4fdca
--- /dev/null
+++ b/libc/baselibc/src/strtoimax.c
@@ -0,0 +1,3 @@
+#define TYPE intmax_t
+#define NAME strtoimax
+#include "templates/strtox.c.template"

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/strtok.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/strtok.c b/libc/baselibc/src/strtok.c
new file mode 100644
index 0000000..6b169a1
--- /dev/null
+++ b/libc/baselibc/src/strtok.c
@@ -0,0 +1,12 @@
+/*
+ * strtok.c
+ */
+
+#include <string.h>
+
+char *strtok(char *s, const char *delim)
+{
+	static char *holder;
+
+	return strtok_r(s, delim, &holder);
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/strtok_r.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/strtok_r.c b/libc/baselibc/src/strtok_r.c
new file mode 100644
index 0000000..695d516
--- /dev/null
+++ b/libc/baselibc/src/strtok_r.c
@@ -0,0 +1,13 @@
+#include <string.h>
+
+char *strtok_r(char *s, const char *delim, char **holder)
+{
+	if (s)
+		*holder = s;
+
+	do {
+		s = strsep(holder, delim);
+	} while (s && !*s);
+
+	return s;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/strtol.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/strtol.c b/libc/baselibc/src/strtol.c
new file mode 100644
index 0000000..ab318cd
--- /dev/null
+++ b/libc/baselibc/src/strtol.c
@@ -0,0 +1,3 @@
+#define TYPE signed long
+#define NAME strtol
+#include "templates/strtox.c.template"

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/strtoll.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/strtoll.c b/libc/baselibc/src/strtoll.c
new file mode 100644
index 0000000..ceb924d
--- /dev/null
+++ b/libc/baselibc/src/strtoll.c
@@ -0,0 +1,3 @@
+#define TYPE signed long long
+#define NAME strtoll
+#include "templates/strtox.c.template"

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/strtoul.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/strtoul.c b/libc/baselibc/src/strtoul.c
new file mode 100644
index 0000000..d0201e1
--- /dev/null
+++ b/libc/baselibc/src/strtoul.c
@@ -0,0 +1,3 @@
+#define TYPE unsigned long
+#define NAME strtoul
+#include "templates/strtox.c.template"

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/strtoull.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/strtoull.c b/libc/baselibc/src/strtoull.c
new file mode 100644
index 0000000..2da622a
--- /dev/null
+++ b/libc/baselibc/src/strtoull.c
@@ -0,0 +1,3 @@
+#define TYPE unsigned long long
+#define NAME strtoull
+#include "templates/strtox.c.template"

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/strtoumax.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/strtoumax.c b/libc/baselibc/src/strtoumax.c
new file mode 100644
index 0000000..c49d125
--- /dev/null
+++ b/libc/baselibc/src/strtoumax.c
@@ -0,0 +1,3 @@
+#define TYPE uintmax_t
+#define NAME strtoumax
+#include "templates/strtox.c.template"

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/templates/atox.c.template
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/templates/atox.c.template b/libc/baselibc/src/templates/atox.c.template
new file mode 100644
index 0000000..c013bb4
--- /dev/null
+++ b/libc/baselibc/src/templates/atox.c.template
@@ -0,0 +1,14 @@
+/*
+ * atox.c
+ *
+ * atoi(), atol(), atoll()
+ */
+
+#include <inttypes.h>
+#include <stdlib.h>
+#include <stdio.h>
+
+TYPE NAME(const char *nptr)
+{
+	return (TYPE) strntoumax(nptr, (char **)NULL, 10, ~(size_t) 0);
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/templates/strtox.c.template
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/templates/strtox.c.template b/libc/baselibc/src/templates/strtox.c.template
new file mode 100644
index 0000000..c22e7c7
--- /dev/null
+++ b/libc/baselibc/src/templates/strtox.c.template
@@ -0,0 +1,14 @@
+/*
+ * strtox.c
+ *
+ * strto...() functions, by macro definition
+ */
+
+#include <stddef.h>
+#include <stdlib.h>
+#include <inttypes.h>
+
+TYPE NAME(const char *nptr, char **endptr, int base)
+{
+	return (TYPE) strntoumax(nptr, endptr, base, ~(size_t) 0);
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/tinyprintf.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/tinyprintf.c b/libc/baselibc/src/tinyprintf.c
new file mode 100644
index 0000000..e48be4a
--- /dev/null
+++ b/libc/baselibc/src/tinyprintf.c
@@ -0,0 +1,362 @@
+/*
+File: tinyprintf.c
+
+Copyright (C) 2004  Kustaa Nyholm
+Copyright (C) 2010  CJlano
+Copyright (C) 2011  Petteri Aimonen
+
+This file is dual-licensed. You can use either of these licenses:
+
+1) GNU LGPL
+This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 of the License, or (at your option) any later version.
+
+This library is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+
+2) BSD
+Copyright (c) 2004,2012 Kustaa Nyholm / SpareTimeLabs
+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 Kustaa Nyholm or SpareTimeLabs 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 COPYRIGHT HOLDER 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.
+
+*/
+
+/* This is a smaller implementation of printf-family of functions,
+ * based on tinyprintf code by Kustaa Nyholm.
+ * The formats supported by this implementation are: 'd' 'u' 'c' 's' 'x' 'X'.
+ * Zero padding and field width are also supported.
+ * If the library is compiled with 'PRINTF_SUPPORT_LONG' defined then the
+ * long specifier is also supported.
+ * Otherwise it is ignored, so on 32 bit platforms there is no point to use
+ * PRINTF_SUPPORT_LONG because int == long.
+ */
+
+#include <stdio.h>
+
+struct param {
+    unsigned char width; /**< field width */
+    char lz;            /**< Leading zeros */
+    char sign:1;        /**<  The sign to display (if any) */
+    char alt:1;         /**< alternate form */
+    char uc:1;          /**<  Upper case (for base16 only) */
+    char base;  /**<  number base (e.g.: 8, 10, 16) */
+    char *bf;           /**<  Buffer to output */
+};
+
+static void ui2a(unsigned long long int num, struct param *p)
+{
+    int n = 0;
+    unsigned long long int d = 1;
+    char *bf = p->bf;
+    while (num / d >= p->base)
+        d *= p->base;
+    while (d != 0) {
+        unsigned long long  dgt = num / d;
+        num %= d;
+        d /= p->base;
+        if (n || dgt > 0 || d == 0) {
+            *bf++ = dgt + (dgt < 10 ? '0' : (p->uc ? 'A' : 'a') - 10);
+            ++n;
+        }
+    }
+    *bf = 0;
+}
+
+static void i2a(long long int num, struct param *p)
+{
+    if (num < 0) {
+        num = -num;
+        p->sign = 1;
+    }
+    ui2a(num, p);
+}
+
+static int a2d(char ch)
+{
+    if (ch >= '0' && ch <= '9')
+        return ch - '0';
+    else if (ch >= 'a' && ch <= 'f')
+        return ch - 'a' + 10;
+    else if (ch >= 'A' && ch <= 'F')
+        return ch - 'A' + 10;
+    else
+        return -1;
+}
+
+static char a2i(char ch, const char **src, int base, unsigned char *nump)
+{
+    const char *p = *src;
+    int num = 0;
+    int digit;
+    while ((digit = a2d(ch)) >= 0) {
+        if (digit > base)
+            break;
+        num = num * base + digit;
+        ch = *p++;
+    }
+    *src = p;
+    *nump = num;
+    return ch;
+}
+
+static int putf(FILE *putp, char c)
+{
+    if (fputc(c, putp) == EOF)
+        return 0;
+    else
+        return 1;
+}
+
+static unsigned putchw(FILE *putp, struct param *p)
+{
+    unsigned written = 0;
+    char ch;
+    int n = p->width;
+    char *bf = p->bf;
+
+    /* Number of filling characters */
+    while (*bf++ && n > 0)
+        n--;
+    if (p->sign)
+        n--;
+    if (p->alt && p->base == 16)
+        n -= 2;
+    else if (p->alt && p->base == 8)
+        n--;
+
+    /* Fill with space, before alternate or sign */
+    if (!p->lz) {
+        while (n-- > 0)
+            written += putf(putp, ' ');
+    }
+
+    /* print sign */
+    if (p->sign)
+        written += putf(putp, '-');
+
+    /* Alternate */
+    if (p->alt && p->base == 16) {
+        written += putf(putp, '0');
+        written += putf(putp, (p->uc ? 'X' : 'x'));
+    } else if (p->alt && p->base == 8) {
+        written += putf(putp, '0');
+    }
+
+    /* Fill with zeros, after alternate or sign */
+    if (p->lz) {
+        while (n-- > 0)
+            written += putf(putp, '0');
+    }
+
+    /* Put actual buffer */
+    bf = p->bf;
+    while ((ch = *bf++))
+        written += putf(putp, ch);
+    
+    return written;
+}
+
+static unsigned long long
+intarg(int lng, int sign, va_list *va)
+{
+    unsigned long long val;
+
+    switch (lng) {
+    case 0:
+        if (sign) {
+            val = va_arg(*va, int);
+        } else {
+            val = va_arg(*va, unsigned int);
+        }
+        break;
+
+    case 1:
+        if (sign) {
+            val = va_arg(*va, long);
+        } else {
+            val = va_arg(*va, unsigned long);
+        }
+        break;
+
+    case 2:
+    default:
+        /* Pull the 64-bit number off the stack as a pair of 32-bit integers.
+         * The va_arg macro was reading from the wrong location when a 64-bit
+         * type was specified.
+         */
+        /* XXX: Look into this; may just be an incorrect setting when the
+         * compiler / newlib was built.
+         */
+        val = va_arg(*va, unsigned long);
+        val |= (unsigned long long)(va_arg(*va, unsigned long)) << 32;
+        break;
+    }
+
+    return val;
+}
+
+size_t tfp_format(FILE *putp, const char *fmt, va_list va)
+{
+    size_t written = 0;
+    struct param p;
+    char bf[23];
+    char ch;
+    char lng;
+
+    p.bf = bf;
+
+    while ((ch = *(fmt++))) {
+        if (ch != '%') {
+            written += putf(putp, ch);
+        } else {
+            /* Init parameter struct */
+            p.lz = 0;
+            p.alt = 0;
+            p.width = 0;
+            p.sign = 0;
+            lng = 0;
+
+            /* Flags */
+            while ((ch = *(fmt++))) {
+                switch (ch) {
+                case '0':
+                    p.lz = 1;
+                    continue;
+                case '#':
+                    p.alt = 1;
+                    continue;
+                default:
+                    break;
+                }
+                break;
+            }
+
+            /* Width */
+            if (ch >= '0' && ch <= '9') {
+                ch = a2i(ch, &fmt, 10, &(p.width));
+            }
+            if (ch == 'l') {
+                ch = *(fmt++);
+                lng = 1;
+
+                if (ch == 'l') {
+                    ch = *(fmt++);
+                    lng = 2;
+                }
+            }
+
+            switch (ch) {
+            case 0:
+                goto abort;
+            case 'u':
+                p.base = 10;
+                ui2a(intarg(lng, 0, &va), &p);
+                written += putchw(putp, &p);
+                break;
+            case 'd':
+            case 'i':
+                p.base = 10;
+                i2a(intarg(lng, 1, &va), &p);
+                written += putchw(putp, &p);
+                break;
+            case 'x':
+            case 'X':
+                p.base = 16;
+                p.uc = (ch == 'X');
+                ui2a(intarg(lng, 0, &va), &p);
+                written += putchw(putp, &p);
+                break;
+            case 'o':
+                p.base = 8;
+                ui2a(intarg(lng, 0, &va), &p);
+                written += putchw(putp, &p);
+                break;
+            case 'c':
+                written += putf(putp, (char)(va_arg(va, int)));
+                break;
+            case 's':
+                p.bf = va_arg(va, char *);
+                written += putchw(putp, &p);
+                p.bf = bf;
+                break;
+            case '%':
+                written += putf(putp, ch);
+            default:
+                break;
+            }
+        }
+    }
+ abort:;
+ 
+ return written;
+}
+
+int vfprintf(FILE *f, const char *fmt, va_list va)
+{
+    return tfp_format(f, fmt, va);
+}
+
+int fprintf(FILE *f, const char *fmt, ...)
+{
+    va_list va;
+    va_start(va, fmt);
+    int rv = vfprintf(f, fmt, va);
+    va_end(va);
+    return rv;
+}
+
+int printf(const char *fmt, ...)
+{
+    va_list va;
+    va_start(va, fmt);
+    int rv = vfprintf(stdout, fmt, va);
+    va_end(va);
+    return rv;
+}
+
+int vsnprintf(char *str, size_t size, const char *fmt, va_list va)
+{
+    struct MemFile state;
+    FILE *f = fmemopen_w(&state, str, size - 1);
+    tfp_format(f, fmt, va);
+    *(state.buffer) = '\0';
+    return state.bytes_written;
+}
+
+int snprintf(char *str, size_t size, const char *fmt, ...)
+{
+    va_list va;
+    va_start(va, fmt);
+    int rv = vsnprintf(str, size, fmt, va);
+    va_end(va);
+    return rv;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/vasprintf.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/vasprintf.c b/libc/baselibc/src/vasprintf.c
new file mode 100644
index 0000000..cdc302f
--- /dev/null
+++ b/libc/baselibc/src/vasprintf.c
@@ -0,0 +1,25 @@
+/*
+ * vasprintf.c
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdarg.h>
+
+int vasprintf(char **bufp, const char *format, va_list ap)
+{
+	va_list ap1;
+	int bytes;
+	char *p;
+
+	va_copy(ap1, ap);
+
+	bytes = vsnprintf(NULL, 0, format, ap1) + 1;
+	va_end(ap1);
+
+	*bufp = p = malloc(bytes);
+	if (!p)
+		return -1;
+
+	return vsnprintf(p, bytes, format, ap);
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/vprintf.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/vprintf.c b/libc/baselibc/src/vprintf.c
new file mode 100644
index 0000000..d6bfeaf
--- /dev/null
+++ b/libc/baselibc/src/vprintf.c
@@ -0,0 +1,11 @@
+/*
+ * vprintf.c
+ */
+
+#include <stdio.h>
+#include <stdarg.h>
+
+int vprintf(const char *format, va_list ap)
+{
+	return vfprintf(stdout, format, ap);
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/vsprintf.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/vsprintf.c b/libc/baselibc/src/vsprintf.c
new file mode 100644
index 0000000..51f5d87
--- /dev/null
+++ b/libc/baselibc/src/vsprintf.c
@@ -0,0 +1,11 @@
+/*
+ * vsprintf.c
+ */
+
+#include <stdio.h>
+#include <unistd.h>
+
+int vsprintf(char *buffer, const char *format, va_list ap)
+{
+	return vsnprintf(buffer, ~(size_t) 0, format, ap);
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/vsscanf.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/vsscanf.c b/libc/baselibc/src/vsscanf.c
new file mode 100644
index 0000000..60eaca6
--- /dev/null
+++ b/libc/baselibc/src/vsscanf.c
@@ -0,0 +1,400 @@
+/*
+ * vsscanf.c
+ *
+ * vsscanf(), from which the rest of the scanf()
+ * family is built
+ */
+
+#include <ctype.h>
+#include <stdarg.h>
+#include <stddef.h>
+#include <inttypes.h>
+#include <string.h>
+#include <limits.h>
+#include <stdio.h>
+
+#ifndef LONG_BIT
+#define LONG_BIT (CHAR_BIT*sizeof(long))
+#endif
+
+enum flags {
+	FL_SPLAT = 0x01,	/* Drop the value, do not assign */
+	FL_INV   = 0x02,	/* Character-set with inverse */
+	FL_WIDTH = 0x04,	/* Field width specified */
+	FL_MINUS = 0x08,	/* Negative number */
+};
+
+enum ranks {
+	rank_char     = -2,
+	rank_short    = -1,
+	rank_int      = 0,
+	rank_long     = 1,
+	rank_longlong = 2,
+	rank_ptr      = INT_MAX	/* Special value used for pointers */
+};
+
+#define MIN_RANK	rank_char
+#define MAX_RANK	rank_longlong
+
+#define INTMAX_RANK	rank_longlong
+#define SIZE_T_RANK	rank_long
+#define PTRDIFF_T_RANK	rank_long
+
+enum bail {
+	bail_none = 0,		/* No error condition */
+	bail_eof,		/* Hit EOF */
+	bail_err		/* Conversion mismatch */
+};
+
+static inline const char *skipspace(const char *p)
+{
+	while (isspace((unsigned char)*p))
+		p++;
+	return p;
+}
+
+#undef set_bit
+static inline void set_bit(unsigned long *bitmap, unsigned int bit)
+{
+	bitmap[bit / LONG_BIT] |= 1UL << (bit % LONG_BIT);
+}
+
+#undef test_bit
+static inline int test_bit(unsigned long *bitmap, unsigned int bit)
+{
+	return (int)(bitmap[bit / LONG_BIT] >> (bit % LONG_BIT)) & 1;
+}
+
+int vsscanf(const char *buffer, const char *format, va_list ap)
+{
+	const char *p = format;
+	char ch;
+	unsigned char uc;
+	const char *q = buffer;
+	const char *qq;
+	uintmax_t val = 0;
+	int rank = rank_int;	/* Default rank */
+	unsigned int width = UINT_MAX;
+	int base;
+	enum flags flags = 0;
+	enum {
+		st_normal,	/* Ground state */
+		st_flags,	/* Special flags */
+		st_width,	/* Field width */
+		st_modifiers,	/* Length or conversion modifiers */
+		st_match_init,	/* Initial state of %[ sequence */
+		st_match,	/* Main state of %[ sequence */
+		st_match_range,	/* After - in a %[ sequence */
+	} state = st_normal;
+	char *sarg = NULL;	/* %s %c or %[ string argument */
+	enum bail bail = bail_none;
+	int sign;
+	int converted = 0;	/* Successful conversions */
+	unsigned long matchmap[((1 << CHAR_BIT) + (LONG_BIT - 1)) / LONG_BIT];
+	int matchinv = 0;	/* Is match map inverted? */
+	unsigned char range_start = 0;
+	(void)sign;
+
+	while ((ch = *p++) && !bail) {
+		switch (state) {
+		case st_normal:
+			if (ch == '%') {
+				state = st_flags;
+				flags = 0;
+				rank = rank_int;
+				width = UINT_MAX;
+			} else if (isspace((unsigned char)ch)) {
+				q = skipspace(q);
+			} else {
+				if (*q == ch)
+					q++;
+				else
+					bail = bail_err; /* Match failure */
+			}
+			break;
+
+		case st_flags:
+			switch (ch) {
+			case '*':
+				flags |= FL_SPLAT;
+				break;
+			case '0'...'9':
+				width = (ch - '0');
+				state = st_width;
+				flags |= FL_WIDTH;
+				break;
+			default:
+				state = st_modifiers;
+				p--;	/* Process this character again */
+				break;
+			}
+			break;
+
+		case st_width:
+			if (ch >= '0' && ch <= '9') {
+				width = width * 10 + (ch - '0');
+			} else {
+				state = st_modifiers;
+				p--;	/* Process this character again */
+			}
+			break;
+
+		case st_modifiers:
+			switch (ch) {
+				/* Length modifiers - nonterminal sequences */
+			case 'h':
+				rank--;	/* Shorter rank */
+				break;
+			case 'l':
+				rank++;	/* Longer rank */
+				break;
+			case 'j':
+				rank = INTMAX_RANK;
+				break;
+			case 'z':
+				rank = SIZE_T_RANK;
+				break;
+			case 't':
+				rank = PTRDIFF_T_RANK;
+				break;
+			case 'L':
+			case 'q':
+				rank = rank_longlong;	/* long double/long long */
+				break;
+
+			default:
+				/* Output modifiers - terminal sequences */
+				/* Next state will be normal */
+				state = st_normal;
+
+				/* Canonicalize rank */
+				if (rank < MIN_RANK)
+					rank = MIN_RANK;
+				else if (rank > MAX_RANK)
+					rank = MAX_RANK;
+
+				switch (ch) {
+				case 'P':	/* Upper case pointer */
+				case 'p':	/* Pointer */
+					rank = rank_ptr;
+					base = 0;
+					sign = 0;
+					goto scan_int;
+
+				case 'i':	/* Base-independent integer */
+					base = 0;
+					sign = 1;
+					goto scan_int;
+
+				case 'd':	/* Decimal integer */
+					base = 10;
+					sign = 1;
+					goto scan_int;
+
+				case 'o':	/* Octal integer */
+					base = 8;
+					sign = 0;
+					goto scan_int;
+
+				case 'u':	/* Unsigned decimal integer */
+					base = 10;
+					sign = 0;
+					goto scan_int;
+
+				case 'x':	/* Hexadecimal integer */
+				case 'X':
+					base = 16;
+					sign = 0;
+					goto scan_int;
+
+				case 'n':	/* # of characters consumed */
+					val = (q - buffer);
+					goto set_integer;
+
+				      scan_int:
+					q = skipspace(q);
+					if (!*q) {
+						bail = bail_eof;
+						break;
+					}
+					val =
+					    strntoumax(q, (char **)&qq, base,
+						       width);
+					if (qq == q) {
+						bail = bail_err;
+						break;
+					}
+					q = qq;
+					if (!(flags & FL_SPLAT))
+						converted++;
+					/* fall through */
+
+				      set_integer:
+					if (!(flags & FL_SPLAT)) {
+						switch (rank) {
+						case rank_char:
+							*va_arg(ap,
+								unsigned char *)
+								= val;
+							break;
+						case rank_short:
+							*va_arg(ap,
+								unsigned short
+								*) = val;
+							break;
+						case rank_int:
+							*va_arg(ap,
+								unsigned int *)
+							    = val;
+							break;
+						case rank_long:
+							*va_arg(ap,
+								unsigned long *)
+								= val;
+							break;
+						case rank_longlong:
+							*va_arg(ap,
+								unsigned long
+								long *) = val;
+							break;
+						case rank_ptr:
+							*va_arg(ap, void **) =
+								(void *)
+								(uintptr_t)val;
+							break;
+						}
+					}
+					break;
+
+				case 'c':	/* Character */
+					/* Default width == 1 */
+					width = (flags & FL_WIDTH) ? width : 1;
+					if (flags & FL_SPLAT) {
+						while (width--) {
+							if (!*q) {
+								bail = bail_eof;
+								break;
+							}
+						}
+					} else {
+						sarg = va_arg(ap, char *);
+						while (width--) {
+							if (!*q) {
+								bail = bail_eof;
+								break;
+							}
+							*sarg++ = *q++;
+						}
+						if (!bail)
+							converted++;
+					}
+					break;
+
+				case 's':	/* String */
+					uc = 1;	/* Anything nonzero */
+					if (flags & FL_SPLAT) {
+						while (width-- && (uc = *q) &&
+						       !isspace(uc)) {
+							q++;
+						}
+					} else {
+						char *sp;
+						sp = sarg = va_arg(ap, char *);
+						while (width-- && (uc = *q) &&
+						       !isspace(uc)) {
+							*sp++ = uc;
+							q++;
+						}
+						if (sarg != sp) {
+							/* Terminate output */
+							*sp = '\0';
+							converted++;
+						}
+					}
+					if (!uc)
+						bail = bail_eof;
+					break;
+
+				case '[':	/* Character range */
+					sarg = (flags & FL_SPLAT) ? NULL
+						: va_arg(ap, char *);
+					state = st_match_init;
+					matchinv = 0;
+					memset(matchmap, 0, sizeof matchmap);
+					break;
+
+				case '%':	/* %% sequence */
+					if (*q == '%')
+						q++;
+					else
+						bail = bail_err;
+					break;
+
+				default:	/* Anything else */
+					/* Unknown sequence */
+					bail = bail_err;
+					break;
+				}
+			}
+			break;
+
+		case st_match_init:	/* Initial state for %[ match */
+			if (ch == '^' && !(flags & FL_INV)) {
+				matchinv = 1;
+			} else {
+				set_bit(matchmap, (unsigned char)ch);
+				state = st_match;
+			}
+			break;
+
+		case st_match:	/* Main state for %[ match */
+			if (ch == ']') {
+				goto match_run;
+			} else if (ch == '-') {
+				range_start = (unsigned char)ch;
+				state = st_match_range;
+			} else {
+				set_bit(matchmap, (unsigned char)ch);
+			}
+			break;
+
+		case st_match_range:	/* %[ match after - */
+			if (ch == ']') {
+				/* - was last character */
+				set_bit(matchmap, (unsigned char)'-');
+				goto match_run;
+			} else {
+				int i;
+				for (i = range_start; i < (unsigned char)ch;
+				     i++)
+					set_bit(matchmap, i);
+				state = st_match;
+			}
+			break;
+
+		      match_run:	/* Match expression finished */
+			qq = q;
+			uc = 1;	/* Anything nonzero */
+			while (width && (uc = *q)
+			       && test_bit(matchmap, uc)^matchinv) {
+				if (sarg)
+					*sarg++ = uc;
+				q++;
+			}
+			if (q != qq && sarg) {
+				*sarg = '\0';
+				converted++;
+			} else {
+				bail = bail_err;
+			}
+			if (!uc)
+				bail = bail_eof;
+			break;
+		}
+	}
+
+	if (bail == bail_eof && !converted)
+		converted = -1;	/* Return EOF (-1) */
+
+	return converted;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/LICENSE
----------------------------------------------------------------------
diff --git a/libs/baselibc/LICENSE b/libs/baselibc/LICENSE
deleted file mode 100644
index b791574..0000000
--- a/libs/baselibc/LICENSE
+++ /dev/null
@@ -1,133 +0,0 @@
-Baselibc is based on klibc 1.5.23 and tinyprintf modules.
-None of the GPL-licensed parts of klibc are used.
-
-Baselibc is licensed under the BSD license:
-
-Copyright (c) 2012 Petteri Aimonen <jpa at blc.mail.kapsi.fi>
-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 Kustaa Nyholm or SpareTimeLabs 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 COPYRIGHT HOLDER BE LIABLE FOR ANY
-DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-The original licenses of the modules are included below:
-
------------------- Tinyprintf license ------------------
-
-Copyright (c) 2004,2012 Kustaa Nyholm / SpareTimeLabs
-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 Kustaa Nyholm or SpareTimeLabs 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 COPYRIGHT HOLDER 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.
-
-------------------- klibc license -------------------------
-This license applies to all files in directory and its subdirectories,
-unless otherwise noted in individual files.
-
-
-Some files are derived from files derived from the include/ directory
-of the Linux kernel, and are licensed under the terms of the GNU
-General Public License, version 2, as released by the Free Software
-Foundation, Inc.; incorporated herein by reference.
-[These files are not included in the baselibc.]
-
-                                -----
-
-Some files are derived from files copyrighted by the Regents of The
-University of California, and are available under the following
-license:
-
-Note: The advertising clause in the license appearing on BSD Unix
-files was officially rescinded by the Director of the Office of
-Technology Licensing of the University of California on July 22
-1999. He states that clause 3 is "hereby deleted in its entirety."
-
- * Copyright (c)
- *      The Regents of the University of California.  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.
- * 3. All advertising materials mentioning features or use of this software
- *    must display the following acknowledgement:
- *      This product includes software developed by the University of
- *      California, Berkeley and its contributors.
- * 4. Neither the name of the University 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 REGENTS 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 REGENTS 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.
-
-For all remaining files [of klibc], the following license applies:
-
- * Permission is hereby granted, free of charge, to any person obtaining
- * a copy of this software and associated documentation files (the
- * "Software"), to deal in the Software without restriction, including
- * without limitation the rights to use, copy, modify, merge, publish,
- * distribute, sublicense, and/or sell copies of the Software, and to
- * permit persons to whom the Software is furnished to do so, subject to
- * the following conditions:
- *
- * Any copyright notice(s) and this permission notice shall be
- * included in all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
- * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
- * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/Makefile
----------------------------------------------------------------------
diff --git a/libs/baselibc/Makefile b/libs/baselibc/Makefile
deleted file mode 100644
index 88c8987..0000000
--- a/libs/baselibc/Makefile
+++ /dev/null
@@ -1,46 +0,0 @@
-# You can override the CFLAGS and C compiler externally,
-# e.g. make PLATFORM=cortex-m3
-CFLAGS += -g -Wall -Werror -I include
-
-ifeq ($(PLATFORM),cortex-m3)
-  CC      = arm-none-eabi-gcc
-  AR      = arm-none-eabi-ar
-  CFLAGS += -mcpu=cortex-m3 -mthumb
-  CFLAGS += -fno-common -Os
-  CFLAGS += -ffunction-sections -fdata-sections
-endif
-
-# With this, the makefile should work on Windows also.
-ifdef windir
-  RM = del
-endif
-
-# Just include all the source files in the build.
-CSRC = $(wildcard src/*.c)
-OBJS = $(CSRC:.c=.o)
-
-# And the files for the test suite
-TESTS_CSRC = $(wildcard tests/*_tests.c)
-TESTS_OBJS = $(TESTS_CSRC:.c=)
-
-# Some of the files uses "templates", i.e. common pieces
-# of code included from multiple files.
-CFLAGS += -Isrc/templates
-
-all: libc.a
-
-clean:
-	$(RM) $(OBJS) $(TESTS_OBJS) libc.a
-
-libc.a: $(OBJS)
-	$(RM) $@
-	$(AR) ru $@ $^
-
-run_tests: $(TESTS_OBJS)
-	$(foreach f,$^,$f)
-
-tests/%: tests/%.c tests/tests_glue.c libc.a
-	$(CC) $(CFLAGS) -o $@ $^
-
-%.o: %.c
-	$(CC) $(CFLAGS) -c -o $@ $<

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/README.md
----------------------------------------------------------------------
diff --git a/libs/baselibc/README.md b/libs/baselibc/README.md
deleted file mode 100644
index f7e9e49..0000000
--- a/libs/baselibc/README.md
+++ /dev/null
@@ -1,6 +0,0 @@
-Baselibc
-========
-This is a very simple libc for embedded systems. Mainly geared for 32-bit microcontrollers in the 10-100kB memory range.
-The library compiles to less than 5kB total on Cortex-M3, and much less if some functions aren't used.
-
-The code is based on klibc and tinyprintf modules, and licensed under the BSD license.

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/include/assert.h
----------------------------------------------------------------------
diff --git a/libs/baselibc/include/assert.h b/libs/baselibc/include/assert.h
deleted file mode 100644
index 273058f..0000000
--- a/libs/baselibc/include/assert.h
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * assert.h
- */
-
-#ifndef _ASSERT_H
-#define _ASSERT_H
-
-#ifdef NDEBUG
-
-/*
- * NDEBUG doesn't just suppress the faulting behavior of assert(),
- * but also all side effects of the assert() argument.  This behavior
- * is required by the C standard, and allows the argument to reference
- * variables that are not defined without NDEBUG.
- */
-#define assert(x) ((void)(0))
-
-#else
-#include <stddef.h>
-
-extern void __assert_func(const char *, int, const char *, const char *)
-    __attribute((noreturn));
-
-#define assert(x) ((x) ? (void)0 : __assert_func(__FILE__, __LINE__, NULL, NULL))
-
-#endif
-
-#endif				/* _ASSERT_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/include/ctype.h
----------------------------------------------------------------------
diff --git a/libs/baselibc/include/ctype.h b/libs/baselibc/include/ctype.h
deleted file mode 100644
index 4670b6a..0000000
--- a/libs/baselibc/include/ctype.h
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * ctype.h
- *
- * This assumes ASCII.
- */
-
-#ifndef _CTYPE_H
-#define _CTYPE_H
-
-#include <klibc/extern.h>
-#include <klibc/inline.h>
-
-__extern_inline int isupper(int __c)
-{
-	return __c >= 'A' && __c <= 'Z';
-}
-
-__extern_inline int islower(int __c)
-{
-	return __c >= 'a' && __c <= 'z';
-}
-
-__extern_inline int isalpha(int __c)
-{
-	return islower(__c) || isupper(__c);
-}
-
-__extern_inline int isdigit(int __c)
-{
-	return ((unsigned)__c - '0') <= 9;
-}
-
-__extern_inline int isalnum(int __c)
-{
-	return isalpha(__c) || isdigit(__c);
-}
-
-__extern_inline int isascii(int __c)
-{
-	return !(__c & ~0x7f);
-}
-
-__extern_inline int isblank(int __c)
-{
-	return (__c == '\t') || (__c == ' ');
-}
-
-__extern_inline int iscntrl(int __c)
-{
-	return __c < 0x20;
-}
-
-__extern_inline int isspace(int __c)
-{
-	return __c == ' ' || __c == '\n' || __c == '\t' || __c == '\r';
-}
-
-__extern_inline int isxdigit(int __c)
-{
-	return isdigit(__c) || (__c >= 'a' && __c <= 'f') || (__c >= 'A' && __c <= 'F');
-}
-
-__extern_inline int ispunct(int __c)
-{
-	return (__c >= '!' && __c <= '/') ||
-	    (__c >= ':' && __c <= '@') ||
-	    (__c >= '[' && __c <= '`') ||
-	    (__c >= '{' && __c <= '~');
-}
-
-__extern_inline int isprint(int __c)
-{
-	return (__c >= 0x20 && __c <= 0x7e);
-}
-
-__extern_inline int toupper(int __c)
-{
-	return islower(__c) ? (__c & ~32) : __c;
-}
-
-__extern_inline int tolower(int __c)
-{
-	return isupper(__c) ? (__c | 32) : __c;
-}
-
-#endif				/* _CTYPE_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/include/inttypes.h
----------------------------------------------------------------------
diff --git a/libs/baselibc/include/inttypes.h b/libs/baselibc/include/inttypes.h
deleted file mode 100644
index e9ee426..0000000
--- a/libs/baselibc/include/inttypes.h
+++ /dev/null
@@ -1,229 +0,0 @@
-/*
- * inttypes.h
- */
-
-#ifndef _INTTYPES_H
-#define _INTTYPES_H
-
-#include <klibc/extern.h>
-#include <stdint.h>
-#include <stddef.h>
-
-static __inline__ intmax_t imaxabs(intmax_t __n)
-{
-	return (__n < (intmax_t) 0) ? -__n : __n;
-}
-
-__extern intmax_t strtoimax(const char *, char **, int);
-__extern uintmax_t strtoumax(const char *, char **, int);
-
-/* extensions */
-__extern intmax_t strntoimax(const char *, char **, int, size_t);
-__extern uintmax_t strntoumax(const char *, char **, int, size_t);
-
-#if !defined(__cplusplus) || defined(__STDC_FORMAT_MACROS)
-
-#define __PRI64_RANK "ll"
-#define __PRI32_RANK "l"
-
-#define PRId8	"d"
-#define PRId16	"d"
-#define PRId32	"d"
-#define PRId64	__PRI64_RANK "d"
-
-#define PRIdLEAST8	"d"
-#define PRIdLEAST16	"d"
-#define PRIdLEAST32	"d"
-#define PRIdLEAST64	__PRI64_RANK "d"
-
-#define PRIdFAST8	"d"
-#define PRIdFAST16	__PRIFAST_RANK "d"
-#define PRIdFAST32	__PRIFAST_RANK "d"
-#define PRIdFAST64	__PRI64_RANK "d"
-
-#define PRIdMAX	 __PRI64_RANK "d"
-#define PRIdPTR  __PRIPTR_RANK "d"
-
-#define PRIi8	"i"
-#define PRIi16	"i"
-#define PRIi32	"i"
-#define PRIi64	__PRI64_RANK "i"
-
-#define PRIiLEAST8	"i"
-#define PRIiLEAST16	"i"
-#define PRIiLEAST32	"i"
-#define PRIiLEAST64	__PRI64_RANK "i"
-
-#define PRIiFAST8	"i"
-#define PRIiFAST16	__PRIFAST_RANK "i"
-#define PRIiFAST32	__PRIFAST_RANK "i"
-#define PRIiFAST64	__PRI64_RANK "i"
-
-#define PRIiMAX	 __PRI64_RANK "i"
-#define PRIiPTR  __PRIPTR_RANK "i"
-
-#define PRIo8	"o"
-#define PRIo16	"o"
-#define PRIo32	"o"
-#define PRIo64	__PRI64_RANK "o"
-
-#define PRIoLEAST8	"o"
-#define PRIoLEAST16	"o"
-#define PRIoLEAST32	"o"
-#define PRIoLEAST64	__PRI64_RANK "o"
-
-#define PRIoFAST8	"o"
-#define PRIoFAST16	__PRIFAST_RANK "o"
-#define PRIoFAST32	__PRIFAST_RANK "o"
-#define PRIoFAST64	__PRI64_RANK "o"
-
-#define PRIoMAX	 __PRI64_RANK "o"
-#define PRIoPTR  __PRIPTR_RANK "o"
-
-#define PRIu8	"u"
-#define PRIu16	"u"
-#define PRIu32	"u"
-#define PRIu64	__PRI64_RANK "u"
-
-#define PRIuLEAST8	"u"
-#define PRIuLEAST16	"u"
-#define PRIuLEAST32	"u"
-#define PRIuLEAST64	__PRI64_RANK "u"
-
-#define PRIuFAST8	"u"
-#define PRIuFAST16	__PRIFAST_RANK "u"
-#define PRIuFAST32	__PRIFAST_RANK "u"
-#define PRIuFAST64	__PRI64_RANK "u"
-
-#define PRIuMAX	 __PRI64_RANK "u"
-#define PRIuPTR  __PRIPTR_RANK "u"
-
-#define PRIx8	"x"
-#define PRIx16	"x"
-#define PRIx32	__PRI32_RANK "x"
-#define PRIx64	__PRI64_RANK "x"
-
-#define PRIxLEAST8	"x"
-#define PRIxLEAST16	"x"
-#define PRIxLEAST32	"x"
-#define PRIxLEAST64	__PRI64_RANK "x"
-
-#define PRIxFAST8	"x"
-#define PRIxFAST16	__PRIFAST_RANK "x"
-#define PRIxFAST32	__PRIFAST_RANK "x"
-#define PRIxFAST64	__PRI64_RANK "x"
-
-#define PRIxMAX	 __PRI64_RANK "x"
-#define PRIxPTR  __PRIPTR_RANK "x"
-
-#define PRIX8	"X"
-#define PRIX16	"X"
-#define PRIX32	__PRI32_RANK "X"
-#define PRIX64	__PRI64_RANK "X"
-
-#define PRIXLEAST8	"X"
-#define PRIXLEAST16	"X"
-#define PRIXLEAST32	"X"
-#define PRIXLEAST64	__PRI64_RANK "X"
-
-#define PRIXFAST8	"X"
-#define PRIXFAST16	__PRIFAST_RANK "X"
-#define PRIXFAST32	__PRIFAST_RANK "X"
-#define PRIXFAST64	__PRI64_RANK "X"
-
-#define PRIXMAX	 __PRI64_RANK "X"
-#define PRIXPTR  __PRIPTR_RANK "X"
-
-#define SCNd8	"hhd"
-#define SCNd16	"hd"
-#define SCNd32	"d"
-#define SCNd64	__PRI64_RANK "d"
-
-#define SCNdLEAST8	"hhd"
-#define SCNdLEAST16	"hd"
-#define SCNdLEAST32	"d"
-#define SCNdLEAST64	__PRI64_RANK "d"
-
-#define SCNdFAST8	"hhd"
-#define SCNdFAST16	__PRIFAST_RANK "d"
-#define SCNdFAST32	__PRIFAST_RANK "d"
-#define SCNdFAST64	__PRI64_RANK "d"
-
-#define SCNdMAX	 __PRI64_RANK "d"
-#define SCNdPTR  __PRIPTR_RANK "d"
-
-#define SCNi8	"hhi"
-#define SCNi16	"hi"
-#define SCNi32	"i"
-#define SCNi64	__PRI64_RANK "i"
-
-#define SCNiLEAST8	"hhi"
-#define SCNiLEAST16	"hi"
-#define SCNiLEAST32	"i"
-#define SCNiLEAST64	__PRI64_RANK "i"
-
-#define SCNiFAST8	"hhi"
-#define SCNiFAST16	__PRIFAST_RANK "i"
-#define SCNiFAST32	__PRIFAST_RANK "i"
-#define SCNiFAST64	__PRI64_RANK "i"
-
-#define SCNiMAX	 __PRI64_RANK "i"
-#define SCNiPTR  __PRIPTR_RANK "i"
-
-#define SCNo8	"hho"
-#define SCNo16	"ho"
-#define SCNo32	"o"
-#define SCNo64	__PRI64_RANK "o"
-
-#define SCNoLEAST8	"hho"
-#define SCNoLEAST16	"ho"
-#define SCNoLEAST32	"o"
-#define SCNoLEAST64	__PRI64_RANK "o"
-
-#define SCNoFAST8	"hho"
-#define SCNoFAST16	__PRIFAST_RANK "o"
-#define SCNoFAST32	__PRIFAST_RANK "o"
-#define SCNoFAST64	__PRI64_RANK "o"
-
-#define SCNoMAX	 __PRI64_RANK "o"
-#define SCNoPTR  __PRIPTR_RANK "o"
-
-#define SCNu8	"hhu"
-#define SCNu16	"hu"
-#define SCNu32	"u"
-#define SCNu64	__PRI64_RANK "u"
-
-#define SCNuLEAST8	"hhu"
-#define SCNuLEAST16	"hu"
-#define SCNuLEAST32	"u"
-#define SCNuLEAST64	__PRI64_RANK "u"
-
-#define SCNuFAST8	"hhu"
-#define SCNuFAST16	__PRIFAST_RANK "u"
-#define SCNuFAST32	__PRIFAST_RANK "u"
-#define SCNuFAST64	__PRI64_RANK "u"
-
-#define SCNuMAX	 __PRI64_RANK "u"
-#define SCNuPTR  __PRIPTR_RANK "u"
-
-#define SCNx8	"hhx"
-#define SCNx16	"hx"
-#define SCNx32	"x"
-#define SCNx64	__PRI64_RANK "x"
-
-#define SCNxLEAST8	"hhx"
-#define SCNxLEAST16	"hx"
-#define SCNxLEAST32	"x"
-#define SCNxLEAST64	__PRI64_RANK "x"
-
-#define SCNxFAST8	"hhx"
-#define SCNxFAST16	__PRIFAST_RANK "x"
-#define SCNxFAST32	__PRIFAST_RANK "x"
-#define SCNxFAST64	__PRI64_RANK "x"
-
-#define SCNxMAX	 __PRI64_RANK "x"
-#define SCNxPTR  __PRIPTR_RANK "x"
-
-#endif
-
-#endif				/* _INTTYPES_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/include/klibc/extern.h
----------------------------------------------------------------------
diff --git a/libs/baselibc/include/klibc/extern.h b/libs/baselibc/include/klibc/extern.h
deleted file mode 100644
index 7d7c7b8..0000000
--- a/libs/baselibc/include/klibc/extern.h
+++ /dev/null
@@ -1,16 +0,0 @@
-/*
- * klibc/extern.h
- */
-
-#ifndef _KLIBC_EXTERN_H
-#define _KLIBC_EXTERN_H
-
-#ifdef __cplusplus
-#define __extern extern "C"
-#else
-#define __extern extern
-#endif
-
-#define __alias(x) __attribute__((weak, alias(x)))
-
-#endif				/* _KLIBC_EXTERN_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/include/klibc/inline.h
----------------------------------------------------------------------
diff --git a/libs/baselibc/include/klibc/inline.h b/libs/baselibc/include/klibc/inline.h
deleted file mode 100644
index 0e54743..0000000
--- a/libs/baselibc/include/klibc/inline.h
+++ /dev/null
@@ -1,12 +0,0 @@
-/*
- * klibc/inline.h
- */
-
-#ifndef _KLIBC_INLINE_H
-#define _KLIBC_INLINE_H
-
-#ifndef __extern_inline
-#define __extern_inline extern inline __attribute__((gnu_inline))
-#endif
-
-#endif				/* _KLIBC_INLINE_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/include/stdio.h
----------------------------------------------------------------------
diff --git a/libs/baselibc/include/stdio.h b/libs/baselibc/include/stdio.h
deleted file mode 100644
index 3f93340..0000000
--- a/libs/baselibc/include/stdio.h
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * stdio.h
- */
-
-#ifndef _STDIO_H
-#define _STDIO_H
-
-#include <klibc/extern.h>
-#include <klibc/inline.h>
-#include <stdarg.h>
-#include <stddef.h>
-#include <string.h>
-
-/* The File structure is designed to be compatible with ChibiOS/RT type
- * BaseSequentialStream.
- */
-struct File;
-
-typedef struct File FILE;
-
-struct File_methods
-{
-    size_t (*write)(FILE* instance, const char *bp, size_t n);
-    size_t (*read)(FILE* instance, char *bp, size_t n);
-};
-
-struct File
-{
-    const struct File_methods *vmt;
-};
-
-#ifndef EOF
-# define EOF (-1)
-#endif
-
-#ifndef BUFSIZ
-# define BUFSIZ 1
-#endif
-
-/* Standard file descriptors - implement these globals yourself. */
-extern FILE* const stdin;
-extern FILE* const stdout;
-extern FILE* const stderr;
-
-/* Wrappers around stream write and read */
-__extern_inline size_t fread(void *buf, size_t size, size_t nmemb, FILE *stream)
-{
-    if (stream->vmt->read == NULL) return 0;
-    return stream->vmt->read(stream, buf, size*nmemb) / size;
-}
-
-__extern_inline size_t fwrite(const void *buf, size_t size, size_t nmemb, FILE *stream)
-{
-    if (stream->vmt->write == NULL) return 0;
-    return stream->vmt->write(stream, buf, size*nmemb) / size;
-}
-
-__extern_inline int fputs(const char *s, FILE *f)
-{
-	return fwrite(s, 1, strlen(s), f);
-}
-
-__extern_inline int puts(const char *s)
-{
-	return fwrite(s, 1, strlen(s), stdout) + fwrite("\n", 1, 1, stdout);
-}
-
-__extern_inline int fputc(int c, FILE *f)
-{
-	unsigned char ch = c;
-	return fwrite(&ch, 1, 1, f) == 1 ? ch : EOF;
-}
-
-__extern char *fgets(char *, int, FILE *);
-__extern_inline int fgetc(FILE *f)
-{
-	unsigned char ch;
-	return fread(&ch, 1, 1, f) == 1 ? ch : EOF;
-}
-
-__extern int errno;
-__extern_inline char *strerror(int errnum)
-{
-	return "error_str";
-}
-
-#define putc(c,f)  fputc((c),(f))
-#define putchar(c) fputc((c),stdout)
-#define getc(f) fgetc(f)
-#define getchar() fgetc(stdin)
-
-__extern_inline int fflush(FILE *stream)
-{
-	return 0;
-}
-
-__extern int printf(const char *, ...);
-__extern int vprintf(const char *, va_list);
-__extern int fprintf(FILE *, const char *, ...);
-__extern int vfprintf(FILE *, const char *, va_list);
-__extern int sprintf(char *, const char *, ...);
-__extern int vsprintf(char *, const char *, va_list);
-__extern int snprintf(char *, size_t n, const char *, ...);
-__extern int vsnprintf(char *, size_t n, const char *, va_list);
-__extern int asprintf(char **, const char *, ...);
-__extern int vasprintf(char **, const char *, va_list);
-
-__extern int sscanf(const char *, const char *, ...);
-__extern int vsscanf(const char *, const char *, va_list);
-
-/* Open a memory buffer for writing.
- Note: Does not write null terminator.*/
-struct MemFile
-{
-    struct File file;
-    char *buffer;
-    size_t bytes_written;
-    size_t size;
-};
-
-FILE *fmemopen_w(struct MemFile* storage, char *buffer, size_t size);
-
-
-#endif				/* _STDIO_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/include/stdlib.h
----------------------------------------------------------------------
diff --git a/libs/baselibc/include/stdlib.h b/libs/baselibc/include/stdlib.h
deleted file mode 100644
index 847cda7..0000000
--- a/libs/baselibc/include/stdlib.h
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * stdlib.h
- */
-
-#ifndef _STDLIB_H
-#define _STDLIB_H
-
-#include <klibc/extern.h>
-#include <klibc/inline.h>
-#include <stddef.h>
-#include <stdbool.h>
-
-__extern_inline int abs(int __n)
-{
-	return (__n < 0) ? -__n : __n;
-}
-
-__extern int atoi(const char *);
-__extern long atol(const char *);
-__extern long long atoll(const char *);
-
-__extern double atof(const char *str);
-__extern double strtod(const char *nptr, char **endptr);
-
-__extern_inline long labs(long __n)
-{
-	return (__n < 0L) ? -__n : __n;
-}
-
-__extern_inline long long llabs(long long __n)
-{
-	return (__n < 0LL) ? -__n : __n;
-}
-
-__extern void free(void *);
-__extern void *malloc(size_t);
-__extern void *calloc(size_t, size_t);
-__extern void *realloc(void *, size_t);
-
-/* Giving malloc some memory from which to allocate */
-__extern void add_malloc_block(void *, size_t);
-__extern void get_malloc_memory_status(size_t *, size_t *);
-
-/* Malloc locking
- * Until the callbacks are set, malloc doesn't do any locking.
- * malloc_lock() *may* timeout, in which case malloc() will return NULL.
- */
-typedef bool (*malloc_lock_t)();
-typedef void (*malloc_unlock_t)();
-__extern void set_malloc_locking(malloc_lock_t, malloc_unlock_t);
-
-__extern long strtol(const char *, char **, int);
-__extern long long strtoll(const char *, char **, int);
-__extern unsigned long strtoul(const char *, char **, int);
-__extern unsigned long long strtoull(const char *, char **, int);
-
-typedef int (*__comparefunc_t) (const void *, const void *);
-__extern void *bsearch(const void *, const void *, size_t, size_t,
-		       __comparefunc_t);
-__extern void qsort(void *, size_t, size_t, __comparefunc_t);
-
-__extern long jrand48(unsigned short *);
-__extern long mrand48(void);
-__extern long nrand48(unsigned short *);
-__extern long lrand48(void);
-__extern unsigned short *seed48(const unsigned short *);
-__extern void srand48(long);
-
-__extern_inline char *getenv(const char *name)
-{
-	return NULL;
-}
-
-#define EXIT_SUCCESS	0
-#define EXIT_FAILURE	1
-__extern_inline void exit(int err)
-{
-	__extern void _exit(int s);
-
-	_exit(err);
-}
-
-#define RAND_MAX 0x7fffffff
-__extern_inline int rand(void)
-{
-	return (int)lrand48();
-}
-__extern_inline void srand(unsigned int __s)
-{
-	srand48(__s);
-}
-__extern_inline long random(void)
-{
-	return lrand48();
-}
-__extern_inline void srandom(unsigned int __s)
-{
-	srand48(__s);
-}
-
-#endif				/* _STDLIB_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/include/string.h
----------------------------------------------------------------------
diff --git a/libs/baselibc/include/string.h b/libs/baselibc/include/string.h
deleted file mode 100644
index b3c1988..0000000
--- a/libs/baselibc/include/string.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * string.h
- */
-
-#ifndef _STRING_H
-#define _STRING_H
-
-#include <klibc/extern.h>
-#include <stddef.h>
-
-__extern void *memccpy(void *, const void *, int, size_t);
-__extern void *memchr(const void *, int, size_t);
-__extern void *memrchr(const void *, int, size_t);
-__extern int memcmp(const void *, const void *, size_t);
-__extern void *memcpy(void *, const void *, size_t);
-__extern void *memmove(void *, const void *, size_t);
-__extern void *memset(void *, int, size_t);
-__extern void *memmem(const void *, size_t, const void *, size_t);
-__extern void memswap(void *, void *, size_t);
-__extern void bzero(void *, size_t);
-__extern int strcasecmp(const char *, const char *);
-__extern int strncasecmp(const char *, const char *, size_t);
-__extern char *strcat(char *, const char *);
-__extern char *strchr(const char *, int);
-__extern char *index(const char *, int);
-__extern char *strrchr(const char *, int);
-__extern char *rindex(const char *, int);
-__extern int strcmp(const char *, const char *);
-__extern char *strcpy(char *, const char *);
-__extern size_t strcspn(const char *, const char *);
-__extern char *strdup(const char *);
-__extern char *strndup(const char *, size_t);
-__extern size_t strlen(const char *);
-__extern size_t strnlen(const char *, size_t);
-__extern char *strncat(char *, const char *, size_t);
-__extern size_t strlcat(char *, const char *, size_t);
-__extern int strncmp(const char *, const char *, size_t);
-__extern char *strncpy(char *, const char *, size_t);
-__extern size_t strlcpy(char *, const char *, size_t);
-__extern char *strpbrk(const char *, const char *);
-__extern char *strsep(char **, const char *);
-__extern size_t strspn(const char *, const char *);
-__extern char *strstr(const char *, const char *);
-__extern char *strtok(char *, const char *);
-__extern char *strtok_r(char *, const char *, char **);
-
-/* Some dummy functions to avoid errors with C++ cstring */
-inline static int strcoll(const char *s1, const char *s2)
-{
-	return strcmp(s1, s2);
-}
-
-inline static size_t strxfrm(char *dest, const char *src, size_t n)
-{
-	strncpy(dest, src, n);
-	return strlen(src);
-}
-
-#endif				/* _STRING_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/pkg.yml
----------------------------------------------------------------------
diff --git a/libs/baselibc/pkg.yml b/libs/baselibc/pkg.yml
deleted file mode 100644
index d7e3110..0000000
--- a/libs/baselibc/pkg.yml
+++ /dev/null
@@ -1,28 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you 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.
-#
-
-pkg.name: libs/baselibc
-pkg.description: Simple libc for embedded systems.
-pkg.author: "Petteri Aimonen"
-pkg.homepage: "https://github.com/PetteriAimonen/Baselibc"
-pkg.keywords:
-    - libc
-
-pkg.req_apis:
-    - console

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/asprintf.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/asprintf.c b/libs/baselibc/src/asprintf.c
deleted file mode 100644
index a3f5f00..0000000
--- a/libs/baselibc/src/asprintf.c
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * asprintf.c
- */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <stdarg.h>
-
-int asprintf(char **bufp, const char *format, ...)
-{
-	va_list ap, ap1;
-	int rv;
-	int bytes;
-	char *p;
-
-	va_start(ap, format);
-	va_copy(ap1, ap);
-
-	bytes = vsnprintf(NULL, 0, format, ap1) + 1;
-	va_end(ap1);
-
-	*bufp = p = malloc(bytes);
-	if (!p)
-		return -1;
-
-	rv = vsnprintf(p, bytes, format, ap);
-	va_end(ap);
-
-	return rv;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/atoi.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/atoi.c b/libs/baselibc/src/atoi.c
deleted file mode 100644
index a26abee..0000000
--- a/libs/baselibc/src/atoi.c
+++ /dev/null
@@ -1,3 +0,0 @@
-#define TYPE int
-#define NAME atoi
-#include "templates/atox.c.template"

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/atol.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/atol.c b/libs/baselibc/src/atol.c
deleted file mode 100644
index 1139c52..0000000
--- a/libs/baselibc/src/atol.c
+++ /dev/null
@@ -1,3 +0,0 @@
-#define TYPE long
-#define NAME atol
-#include "templates/atox.c.template"

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/atoll.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/atoll.c b/libs/baselibc/src/atoll.c
deleted file mode 100644
index bc8a9fc..0000000
--- a/libs/baselibc/src/atoll.c
+++ /dev/null
@@ -1,3 +0,0 @@
-#define TYPE long long
-#define NAME atoll
-#include "templates/atox.c.template"

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/baselibc_test/printf_tests.c.donotcompile
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/baselibc_test/printf_tests.c.donotcompile b/libs/baselibc/src/baselibc_test/printf_tests.c.donotcompile
deleted file mode 100644
index f9f380f..0000000
--- a/libs/baselibc/src/baselibc_test/printf_tests.c.donotcompile
+++ /dev/null
@@ -1,22 +0,0 @@
-#include "unittests.h"
-
-int main()
-{
-    int status = 0;
-    
-    {
-        COMMENT("Testing basic snprintf functionality");
-        char buf[20];
-        
-        snprintf(buf, sizeof(buf), "%08d", 55);
-        TEST(strcmp(buf, "00000055") == 0);
-        
-        TEST(snprintf(buf, sizeof(buf), "01234567890123456789") == 20);
-        TEST(strcmp(buf, "0123456789012345678") == 0);
-    }
-        
-    if (status != 0)
-        fprintf(stdout, "\n\nSome tests FAILED!\n");
-
-    return status;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/baselibc_test/tests_glue.c.donotcompile
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/baselibc_test/tests_glue.c.donotcompile b/libs/baselibc/src/baselibc_test/tests_glue.c.donotcompile
deleted file mode 100644
index b18a689..0000000
--- a/libs/baselibc/src/baselibc_test/tests_glue.c.donotcompile
+++ /dev/null
@@ -1,33 +0,0 @@
-#include <stdio.h>
-
-#if defined(linux)
-/* Connects the baselibc stdio to normal POSIX stdio */
-size_t write(int fd, const void *buf, size_t count);
-
-static size_t stdio_write(FILE *instance, const char *bp, size_t n)
-{
-    if (instance == stdout)
-        return write(1, bp, n);
-    else
-        return write(2, bp, n);
-}
-#else
-#error No suitable write() implementation.
-#endif
-
-
-static struct File_methods stdio_methods = {
-        &stdio_write, NULL
-};
-
-static struct File _stdout = {
-        &stdio_methods
-};
-
-static struct File _stderr = {
-        &stdio_methods
-};
-
-FILE* const stdout = &_stdout;
-FILE* const stderr = &_stderr;
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/baselibc_test/unittests.h
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/baselibc_test/unittests.h b/libs/baselibc/src/baselibc_test/unittests.h
deleted file mode 100644
index 572f595..0000000
--- a/libs/baselibc/src/baselibc_test/unittests.h
+++ /dev/null
@@ -1,36 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 H_BASELIBC_UNITTESTS_
-#define H_BASELIBC_UNITTESTS_
-
-#include <stdio.h>
-
-#define COMMENT(x) printf("\n----" x "----\n");
-#define STR(x) #x
-#define STR2(x) STR(x)
-#define TEST(x) \
-    if (!(x)) { \
-        fprintf(stderr, "\033[31;1mFAILED:\033[22;39m " __FILE__ ":" STR2(__LINE__) " " #x "\n"); \
-        status = 1; \
-    } else { \
-        printf("\033[32;1mOK:\033[22;39m " #x "\n"); \
-    }
-
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/bsearch.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/bsearch.c b/libs/baselibc/src/bsearch.c
deleted file mode 100644
index 1c8b07f..0000000
--- a/libs/baselibc/src/bsearch.c
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * bsearch.c
- */
-
-#include <stdlib.h>
-
-void *bsearch(const void *key, const void *base, size_t nmemb,
-	      size_t size, int (*cmp) (const void *, const void *))
-{
-	while (nmemb) {
-		size_t mididx = nmemb / 2;
-		const void *midobj = base + mididx * size;
-		int diff = cmp(key, midobj);
-
-		if (diff == 0)
-			return (void *)midobj;
-
-		if (diff > 0) {
-			base = midobj + size;
-			nmemb -= mididx + 1;
-		} else
-			nmemb = mididx;
-	}
-
-	return NULL;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/bzero.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/bzero.c b/libs/baselibc/src/bzero.c
deleted file mode 100644
index aa1c1ff..0000000
--- a/libs/baselibc/src/bzero.c
+++ /dev/null
@@ -1,6 +0,0 @@
-#include <string.h>
-
-void bzero(void *dst, size_t n)
-{
-	memset(dst, 0, n);
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/calloc.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/calloc.c b/libs/baselibc/src/calloc.c
deleted file mode 100644
index 3db7664..0000000
--- a/libs/baselibc/src/calloc.c
+++ /dev/null
@@ -1,20 +0,0 @@
-/*
- * calloc.c
- */
-
-#include <stdlib.h>
-#include <string.h>
-
-/* FIXME: This should look for multiplication overflow */
-
-void *calloc(size_t nmemb, size_t size)
-{
-	void *ptr;
-
-	size *= nmemb;
-	ptr = malloc(size);
-	if (ptr)
-		memset(ptr, 0, size);
-
-	return ptr;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/fgets.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/fgets.c b/libs/baselibc/src/fgets.c
deleted file mode 100644
index 4e9cf68..0000000
--- a/libs/baselibc/src/fgets.c
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * fgets.c
- *
- * This will be very slow due to the implementation of getc(),
- * but we don't have anywhere to put characters we don't need from
- * the input.
- */
-
-#include <stdio.h>
-
-char *fgets(char *s, int n, FILE *f)
-{
-	int ch;
-	char *p = s;
-
-	while (n > 1) {
-		ch = getc(f);
-		if (ch == EOF) {
-			*p = '\0';
-			return NULL;
-		}
-		*p++ = ch;
-		n--;
-		if (ch == '\n')
-			break;
-	}
-	if (n)
-		*p = '\0';
-
-	return s;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/inline.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/inline.c b/libs/baselibc/src/inline.c
deleted file mode 100644
index 2d8d013..0000000
--- a/libs/baselibc/src/inline.c
+++ /dev/null
@@ -1,5 +0,0 @@
-// Make an externally visible symbol out of inlined functions
-#define __extern_inline
-#include <stdlib.h>
-#include <stdio.h>
-#include <ctype.h>

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/jrand48.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/jrand48.c b/libs/baselibc/src/jrand48.c
deleted file mode 100644
index 8e2b3ac..0000000
--- a/libs/baselibc/src/jrand48.c
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * jrand48.c
- */
-
-#include <stdlib.h>
-#include <stdint.h>
-
-long jrand48(unsigned short xsubi[3])
-{
-	uint64_t x;
-
-	/* The xsubi[] array is littleendian by spec */
-	x = (uint64_t) (uint16_t) xsubi[0] +
-	    ((uint64_t) (uint16_t) xsubi[1] << 16) +
-	    ((uint64_t) (uint16_t) xsubi[2] << 32);
-
-	x = (0x5deece66dULL * x) + 0xb;
-
-	xsubi[0] = (unsigned short)(uint16_t) x;
-	xsubi[1] = (unsigned short)(uint16_t) (x >> 16);
-	xsubi[2] = (unsigned short)(uint16_t) (x >> 32);
-
-	return (long)(int32_t) (x >> 16);
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/lrand48.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/lrand48.c b/libs/baselibc/src/lrand48.c
deleted file mode 100644
index a2fc87a..0000000
--- a/libs/baselibc/src/lrand48.c
+++ /dev/null
@@ -1,13 +0,0 @@
-/*
- * lrand48.c
- */
-
-#include <stdlib.h>
-#include <stdint.h>
-
-extern unsigned short __rand48_seed[3];	/* Common with mrand48.c, srand48.c */
-
-long lrand48(void)
-{
-	return (uint32_t) jrand48(__rand48_seed) >> 1;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/malloc.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/malloc.c b/libs/baselibc/src/malloc.c
deleted file mode 100644
index 3ef5089..0000000
--- a/libs/baselibc/src/malloc.c
+++ /dev/null
@@ -1,274 +0,0 @@
-/*
- * malloc.c
- *
- * Very simple linked-list based malloc()/free().
- */
-
-#include <stdbool.h>
-#include <stdlib.h>
-#include <assert.h>
-#include "malloc.h"
-
-/* Both the arena list and the free memory list are double linked
-   list with head node.  This the head node. Note that the arena list
-   is sorted in order of address. */
-static struct free_arena_header __malloc_head = {
-	{
-		ARENA_TYPE_HEAD,
-		0,
-		&__malloc_head,
-		&__malloc_head,
-	},
-	&__malloc_head,
-	&__malloc_head
-};
-
-static bool malloc_lock_nop() {return true;}
-static void malloc_unlock_nop() {}
-
-static malloc_lock_t malloc_lock = &malloc_lock_nop;
-static malloc_unlock_t malloc_unlock = &malloc_unlock_nop;
-
-static inline void mark_block_dead(struct free_arena_header *ah)
-{
-#ifdef DEBUG_MALLOC
-	ah->a.type = ARENA_TYPE_DEAD;
-#endif
-}
-
-static inline void remove_from_main_chain(struct free_arena_header *ah)
-{
-	struct free_arena_header *ap, *an;
-
-	mark_block_dead(ah);
-
-	ap = ah->a.prev;
-	an = ah->a.next;
-	ap->a.next = an;
-	an->a.prev = ap;
-}
-
-static inline void remove_from_free_chain(struct free_arena_header *ah)
-{
-	struct free_arena_header *ap, *an;
-
-	ap = ah->prev_free;
-	an = ah->next_free;
-	ap->next_free = an;
-	an->prev_free = ap;
-}
-
-static inline void remove_from_chains(struct free_arena_header *ah)
-{
-	remove_from_free_chain(ah);
-	remove_from_main_chain(ah);
-}
-
-static void *__malloc_from_block(struct free_arena_header *fp, size_t size)
-{
-	size_t fsize;
-	struct free_arena_header *nfp, *na, *fpn, *fpp;
-
-	fsize = fp->a.size;
-
-	/* We need the 2* to account for the larger requirements of a
-	   free block */
-	if (fsize >= size + 2 * sizeof(struct arena_header)) {
-		/* Bigger block than required -- split block */
-		nfp = (struct free_arena_header *)((char *)fp + size);
-		na = fp->a.next;
-
-		nfp->a.type = ARENA_TYPE_FREE;
-		nfp->a.size = fsize - size;
-		fp->a.type = ARENA_TYPE_USED;
-		fp->a.size = size;
-
-		/* Insert into all-block chain */
-		nfp->a.prev = fp;
-		nfp->a.next = na;
-		na->a.prev = nfp;
-		fp->a.next = nfp;
-
-		/* Replace current block on free chain */
-		nfp->next_free = fpn = fp->next_free;
-		nfp->prev_free = fpp = fp->prev_free;
-		fpn->prev_free = nfp;
-		fpp->next_free = nfp;
-	} else {
-		fp->a.type = ARENA_TYPE_USED; /* Allocate the whole block */
-		remove_from_free_chain(fp);
-	}
-
-	return (void *)(&fp->a + 1);
-}
-
-static struct free_arena_header *__free_block(struct free_arena_header *ah)
-{
-	struct free_arena_header *pah, *nah;
-
-	pah = ah->a.prev;
-	nah = ah->a.next;
-	if (pah->a.type == ARENA_TYPE_FREE &&
-	    (char *)pah + pah->a.size == (char *)ah) {
-		/* Coalesce into the previous block */
-		pah->a.size += ah->a.size;
-		pah->a.next = nah;
-		nah->a.prev = pah;
-		mark_block_dead(ah);
-
-		ah = pah;
-		pah = ah->a.prev;
-	} else {
-		/* Need to add this block to the free chain */
-		ah->a.type = ARENA_TYPE_FREE;
-
-		ah->next_free = __malloc_head.next_free;
-		ah->prev_free = &__malloc_head;
-		__malloc_head.next_free = ah;
-		ah->next_free->prev_free = ah;
-	}
-
-	/* In either of the previous cases, we might be able to merge
-	   with the subsequent block... */
-	if (nah->a.type == ARENA_TYPE_FREE &&
-	    (char *)ah + ah->a.size == (char *)nah) {
-		ah->a.size += nah->a.size;
-
-		/* Remove the old block from the chains */
-		remove_from_chains(nah);
-	}
-
-	/* Return the block that contains the called block */
-	return ah;
-}
-
-void *malloc(size_t size)
-{
-	struct free_arena_header *fp;
-        void *more_mem;
-        extern void *_sbrk(int incr);
-
-	if (size == 0)
-		return NULL;
-
-	/* Add the obligatory arena header, and round up */
-	size = (size + 2 * sizeof(struct arena_header) - 1) & ARENA_SIZE_MASK;
-
-        if (!malloc_lock())
-                return NULL;
-
-        void *result = NULL;
-retry_alloc:
-	for (fp = __malloc_head.next_free; fp->a.type != ARENA_TYPE_HEAD;
-	     fp = fp->next_free) {
-		if (fp->a.size >= size) {
-			/* Found fit -- allocate out of this block */
-			result = __malloc_from_block(fp, size);
-                        break;
-		}
-	}
-        if (result == NULL) {
-            more_mem = _sbrk(size);
-            if (more_mem != (void *)-1) {
-                add_malloc_block(more_mem, size);
-                goto retry_alloc;
-            }
-        }
-        malloc_unlock();
-	return result;
-}
-
-/* Call this to give malloc some memory to allocate from */
-void add_malloc_block(void *buf, size_t size)
-{
-	struct free_arena_header *fp = buf;
-	struct free_arena_header *pah;
-
-	if (size < sizeof(struct free_arena_header))
-		return; // Too small.
-
-	/* Insert the block into the management chains.  We need to set
-	   up the size and the main block list pointer, the rest of
-	   the work is logically identical to free(). */
-	fp->a.type = ARENA_TYPE_FREE;
-	fp->a.size = size;
-
-        if (!malloc_lock())
-            return;
-
-	/* We need to insert this into the main block list in the proper
-	   place -- this list is required to be sorted.  Since we most likely
-	   get memory assignments in ascending order, search backwards for
-	   the proper place. */
-	for (pah = __malloc_head.a.prev; pah->a.type != ARENA_TYPE_HEAD;
-	     pah = pah->a.prev) {
-		if (pah < fp)
-			break;
-	}
-
-	/* Now pah points to the node that should be the predecessor of
-	   the new node */
-	fp->a.next = pah->a.next;
-	fp->a.prev = pah;
-	pah->a.next = fp;
-	fp->a.next->a.prev = fp;
-
-	/* Insert into the free chain and coalesce with adjacent blocks */
-	fp = __free_block(fp);
-
-        malloc_unlock();
-}
-
-void free(void *ptr)
-{
-	struct free_arena_header *ah;
-
-	if (!ptr)
-		return;
-
-	ah = (struct free_arena_header *)
-	    ((struct arena_header *)ptr - 1);
-
-#ifdef DEBUG_MALLOC
-	assert(ah->a.type == ARENA_TYPE_USED);
-#endif
-
-        if (!malloc_lock())
-            return;
-
-	/* Merge into adjacent free blocks */
-	ah = __free_block(ah);
-        malloc_unlock();
-}
-
-void get_malloc_memory_status(size_t *free_bytes, size_t *largest_block)
-{
-    struct free_arena_header *fp;
-    *free_bytes = 0;
-    *largest_block = 0;
-
-    if (!malloc_lock())
-            return;
-
-    for (fp = __malloc_head.next_free; fp->a.type != ARENA_TYPE_HEAD; fp = fp->next_free) {
-        *free_bytes += fp->a.size;
-        if (fp->a.size >= *largest_block) {
-            *largest_block = fp->a.size;
-        }
-    }
-
-    malloc_unlock();
-}
-
-void set_malloc_locking(malloc_lock_t lock, malloc_unlock_t unlock)
-{
-    if (lock)
-        malloc_lock = lock;
-    else
-        malloc_lock = &malloc_lock_nop;
-
-    if (unlock)
-        malloc_unlock = unlock;
-    else
-        malloc_unlock = &malloc_unlock_nop;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/malloc.h
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/malloc.h b/libs/baselibc/src/malloc.h
deleted file mode 100644
index 2bed2a6..0000000
--- a/libs/baselibc/src/malloc.h
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * malloc.h
- *
- * Internals for the memory allocator
- */
-
-#include <stdint.h>
-#include <stddef.h>
-
-/*
- * This structure should be a power of two.  This becomes the
- * alignment unit.
- */
-struct free_arena_header;
-
-struct arena_header {
-	size_t type;
-	size_t size;
-	struct free_arena_header *next, *prev;
-};
-
-#ifdef DEBUG_MALLOC
-#define ARENA_TYPE_USED 0x64e69c70
-#define ARENA_TYPE_FREE 0x012d610a
-#define ARENA_TYPE_HEAD 0x971676b5
-#define ARENA_TYPE_DEAD 0xeeeeeeee
-#else
-#define ARENA_TYPE_USED 0
-#define ARENA_TYPE_FREE 1
-#define ARENA_TYPE_HEAD 2
-#endif
-
-#define ARENA_SIZE_MASK (~(sizeof(struct arena_header)-1))
-
-/*
- * This structure should be no more than twice the size of the
- * previous structure.
- */
-struct free_arena_header {
-	struct arena_header a;
-	struct free_arena_header *next_free, *prev_free;
-};
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/memccpy.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/memccpy.c b/libs/baselibc/src/memccpy.c
deleted file mode 100644
index 83d02c9..0000000
--- a/libs/baselibc/src/memccpy.c
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * memccpy.c
- *
- * memccpy()
- */
-
-#include <stddef.h>
-#include <string.h>
-
-void *memccpy(void *dst, const void *src, int c, size_t n)
-{
-	char *q = dst;
-	const char *p = src;
-	char ch;
-
-	while (n--) {
-		*q++ = ch = *p++;
-		if (ch == (char)c)
-			return q;
-	}
-
-	return NULL;		/* No instance of "c" found */
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/memchr.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/memchr.c b/libs/baselibc/src/memchr.c
deleted file mode 100644
index f1947fb..0000000
--- a/libs/baselibc/src/memchr.c
+++ /dev/null
@@ -1,19 +0,0 @@
-/*
- * memchr.c
- */
-
-#include <stddef.h>
-#include <string.h>
-
-void *memchr(const void *s, int c, size_t n)
-{
-	const unsigned char *sp = s;
-
-	while (n--) {
-		if (*sp == (unsigned char)c)
-			return (void *)sp;
-		sp++;
-	}
-
-	return NULL;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/memcmp.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/memcmp.c b/libs/baselibc/src/memcmp.c
deleted file mode 100644
index 3ce9941..0000000
--- a/libs/baselibc/src/memcmp.c
+++ /dev/null
@@ -1,19 +0,0 @@
-/*
- * memcmp.c
- */
-
-#include <string.h>
-
-int memcmp(const void *s1, const void *s2, size_t n)
-{
-	const unsigned char *c1 = s1, *c2 = s2;
-	int d = 0;
-
-	while (n--) {
-		d = (int)*c1++ - (int)*c2++;
-		if (d)
-			break;
-	}
-
-	return d;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/memcpy.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/memcpy.c b/libs/baselibc/src/memcpy.c
deleted file mode 100644
index 5ce206d..0000000
--- a/libs/baselibc/src/memcpy.c
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * memcpy.c
- */
-
-#include <string.h>
-#include <stdint.h>
-
-void *memcpy(void *dst, const void *src, size_t n)
-{
-	const char *p = src;
-	char *q = dst;
-#if defined(__i386__)
-	size_t nl = n >> 2;
-	asm volatile ("cld ; rep ; movsl ; movl %3,%0 ; rep ; movsb":"+c" (nl),
-		      "+S"(p), "+D"(q)
-		      :"r"(n & 3));
-#elif defined(__x86_64__)
-	size_t nq = n >> 3;
-	asm volatile ("cld ; rep ; movsq ; movl %3,%%ecx ; rep ; movsb":"+c"
-		      (nq), "+S"(p), "+D"(q)
-		      :"r"((uint32_t) (n & 7)));
-#else
-	while (n--) {
-		*q++ = *p++;
-	}
-#endif
-
-	return dst;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/memfile.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/memfile.c b/libs/baselibc/src/memfile.c
deleted file mode 100644
index c915004..0000000
--- a/libs/baselibc/src/memfile.c
+++ /dev/null
@@ -1,33 +0,0 @@
-#include <stdio.h>
-
-size_t memfile_write(FILE *instance, const char *bp, size_t n)
-{
-    struct MemFile *f = (struct MemFile*)instance;
-    size_t i = 0;
-    
-    while (n--)
-    {
-        f->bytes_written++;
-        if (f->bytes_written <= f->size)
-        {
-            *f->buffer++ = *bp++;
-            i++;
-        }
-    }
-    
-    return i;
-}
-
-const struct File_methods MemFile_methods = {
-    &memfile_write,
-    NULL
-};
-
-FILE *fmemopen_w(struct MemFile* storage, char *buffer, size_t size)
-{
-    storage->file.vmt = &MemFile_methods;
-    storage->buffer = buffer;
-    storage->bytes_written = 0;
-    storage->size = size;
-    return (FILE*)storage;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/memmem.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/memmem.c b/libs/baselibc/src/memmem.c
deleted file mode 100644
index 8b5faa0..0000000
--- a/libs/baselibc/src/memmem.c
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * memmem.c
- *
- * Find a byte string inside a longer byte string
- *
- * This uses the "Not So Naive" algorithm, a very simple but
- * usually effective algorithm, see:
- *
- * http://www-igm.univ-mlv.fr/~lecroq/string/
- */
-
-#include <string.h>
-
-void *memmem(const void *haystack, size_t n, const void *needle, size_t m)
-{
-	const unsigned char *y = (const unsigned char *)haystack;
-	const unsigned char *x = (const unsigned char *)needle;
-
-	size_t j, k, l;
-
-	if (m > n || !m || !n)
-		return NULL;
-
-	if (1 != m) {
-		if (x[0] == x[1]) {
-			k = 2;
-			l = 1;
-		} else {
-			k = 1;
-			l = 2;
-		}
-
-		j = 0;
-		while (j <= n - m) {
-			if (x[1] != y[j + 1]) {
-				j += k;
-			} else {
-				if (!memcmp(x + 2, y + j + 2, m - 2)
-				    && x[0] == y[j])
-					return (void *)&y[j];
-				j += l;
-			}
-		}
-	} else
-		do {
-			if (*y == *x)
-				return (void *)y;
-			y++;
-		} while (--n);
-
-	return NULL;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/memmove.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/memmove.c b/libs/baselibc/src/memmove.c
deleted file mode 100644
index a398cd8..0000000
--- a/libs/baselibc/src/memmove.c
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * memmove.c
- */
-
-#include <string.h>
-
-void *memmove(void *dst, const void *src, size_t n)
-{
-	const char *p = src;
-	char *q = dst;
-#if defined(__i386__) || defined(__x86_64__)
-	if (q < p) {
-		asm volatile("cld; rep; movsb"
-			     : "+c" (n), "+S"(p), "+D"(q));
-	} else {
-		p += (n - 1);
-		q += (n - 1);
-		asm volatile("std; rep; movsb; cld"
-			     : "+c" (n), "+S"(p), "+D"(q));
-	}
-#else
-	if (q < p) {
-		while (n--) {
-			*q++ = *p++;
-		}
-	} else {
-		p += n;
-		q += n;
-		while (n--) {
-			*--q = *--p;
-		}
-	}
-#endif
-
-	return dst;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/memrchr.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/memrchr.c b/libs/baselibc/src/memrchr.c
deleted file mode 100644
index ff6d711..0000000
--- a/libs/baselibc/src/memrchr.c
+++ /dev/null
@@ -1,19 +0,0 @@
-/*
- * memrchr.c
- */
-
-#include <stddef.h>
-#include <string.h>
-
-void *memrchr(const void *s, int c, size_t n)
-{
-	const unsigned char *sp = (const unsigned char *)s + n - 1;
-
-	while (n--) {
-		if (*sp == (unsigned char)c)
-			return (void *)sp;
-		sp--;
-	}
-
-	return NULL;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/memset.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/memset.c b/libs/baselibc/src/memset.c
deleted file mode 100644
index aa00b5b..0000000
--- a/libs/baselibc/src/memset.c
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * memset.c
- */
-
-#include <string.h>
-#include <stdint.h>
-
-void *memset(void *dst, int c, size_t n)
-{
-	char *q = dst;
-
-#if defined(__i386__)
-	size_t nl = n >> 2;
-	asm volatile ("cld ; rep ; stosl ; movl %3,%0 ; rep ; stosb"
-		      : "+c" (nl), "+D" (q)
-		      : "a" ((unsigned char)c * 0x01010101U), "r" (n & 3));
-#elif defined(__x86_64__)
-	size_t nq = n >> 3;
-	asm volatile ("cld ; rep ; stosq ; movl %3,%%ecx ; rep ; stosb"
-		      :"+c" (nq), "+D" (q)
-		      : "a" ((unsigned char)c * 0x0101010101010101U),
-			"r" ((uint32_t) n & 7));
-#else
-	while (n--) {
-		*q++ = c;
-	}
-#endif
-
-	return dst;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/memswap.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/memswap.c b/libs/baselibc/src/memswap.c
deleted file mode 100644
index b32315c..0000000
--- a/libs/baselibc/src/memswap.c
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * memswap()
- *
- * Swaps the contents of two nonoverlapping memory areas.
- * This really could be done faster...
- */
-
-#include <string.h>
-
-void memswap(void *m1, void *m2, size_t n)
-{
-	char *p = m1;
-	char *q = m2;
-	char tmp;
-
-	while (n--) {
-		tmp = *p;
-		*p = *q;
-		*q = tmp;
-
-		p++;
-		q++;
-	}
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/mrand48.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/mrand48.c b/libs/baselibc/src/mrand48.c
deleted file mode 100644
index 1a2383b..0000000
--- a/libs/baselibc/src/mrand48.c
+++ /dev/null
@@ -1,13 +0,0 @@
-/*
- * mrand48.c
- */
-
-#include <stdlib.h>
-#include <stdint.h>
-
-extern unsigned short __rand48_seed[3];	/* Common with lrand48.c, srand48.c */
-
-long mrand48(void)
-{
-	return jrand48(__rand48_seed);
-}



[18/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/lstrlib.c
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/lstrlib.c b/libs/elua/elua_base/src/lstrlib.c
deleted file mode 100644
index 50220b2..0000000
--- a/libs/elua/elua_base/src/lstrlib.c
+++ /dev/null
@@ -1,893 +0,0 @@
-/*
-** $Id: lstrlib.c,v 1.132.1.5 2010/05/14 15:34:19 roberto Exp $
-** Standard library for string operations and pattern-matching
-** See Copyright Notice in lua.h
-*/
-
-
-#include <ctype.h>
-#include <stddef.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#define lstrlib_c
-#define LUA_LIB
-
-#include "lua.h"
-
-#include "lauxlib.h"
-#include "lualib.h"
-#include "lrotable.h"
-
-/* macro to `unsign' a character */
-#define uchar(c)        ((unsigned char)(c))
-
-
-
-static int str_len (lua_State *L) {
-  size_t l;
-  luaL_checklstring(L, 1, &l);
-  lua_pushinteger(L, l);
-  return 1;
-}
-
-
-static ptrdiff_t posrelat (ptrdiff_t pos, size_t len) {
-  /* relative string position: negative means back from end */
-  if (pos < 0) pos += (ptrdiff_t)len + 1;
-  return (pos >= 0) ? pos : 0;
-}
-
-
-static int str_sub (lua_State *L) {
-  size_t l;
-  const char *s = luaL_checklstring(L, 1, &l);
-  ptrdiff_t start = posrelat(luaL_checkinteger(L, 2), l);
-  ptrdiff_t end = posrelat(luaL_optinteger(L, 3, -1), l);
-  if (start < 1) start = 1;
-  if (end > (ptrdiff_t)l) end = (ptrdiff_t)l;
-  if (start <= end)
-    lua_pushlstring(L, s+start-1, end-start+1);
-  else lua_pushliteral(L, "");
-  return 1;
-}
-
-
-static int str_reverse (lua_State *L) {
-  size_t l;
-  luaL_Buffer b;
-  const char *s = luaL_checklstring(L, 1, &l);
-  luaL_buffinit(L, &b);
-  while (l--) luaL_addchar(&b, s[l]);
-  luaL_pushresult(&b);
-  return 1;
-}
-
-
-static int str_lower (lua_State *L) {
-  size_t l;
-  size_t i;
-  luaL_Buffer b;
-  const char *s = luaL_checklstring(L, 1, &l);
-  luaL_buffinit(L, &b);
-  for (i=0; i<l; i++)
-    luaL_addchar(&b, tolower(uchar(s[i])));
-  luaL_pushresult(&b);
-  return 1;
-}
-
-
-static int str_upper (lua_State *L) {
-  size_t l;
-  size_t i;
-  luaL_Buffer b;
-  const char *s = luaL_checklstring(L, 1, &l);
-  luaL_buffinit(L, &b);
-  for (i=0; i<l; i++)
-    luaL_addchar(&b, toupper(uchar(s[i])));
-  luaL_pushresult(&b);
-  return 1;
-}
-
-static int str_rep (lua_State *L) {
-  size_t l;
-  luaL_Buffer b;
-  const char *s = luaL_checklstring(L, 1, &l);
-  int n = luaL_checkint(L, 2);
-  luaL_buffinit(L, &b);
-  while (n-- > 0)
-    luaL_addlstring(&b, s, l);
-  luaL_pushresult(&b);
-  return 1;
-}
-
-
-static int str_byte (lua_State *L) {
-  size_t l;
-  const char *s = luaL_checklstring(L, 1, &l);
-  ptrdiff_t posi = posrelat(luaL_optinteger(L, 2, 1), l);
-  ptrdiff_t pose = posrelat(luaL_optinteger(L, 3, posi), l);
-  int n, i;
-  if (posi <= 0) posi = 1;
-  if ((size_t)pose > l) pose = l;
-  if (posi > pose) return 0;  /* empty interval; return no values */
-  n = (int)(pose -  posi + 1);
-  if (posi + n <= pose)  /* overflow? */
-    luaL_error(L, "string slice too long");
-  luaL_checkstack(L, n, "string slice too long");
-  for (i=0; i<n; i++)
-    lua_pushinteger(L, uchar(s[posi+i-1]));
-  return n;
-}
-
-
-static int str_char (lua_State *L) {
-  int n = lua_gettop(L);  /* number of arguments */
-  int i;
-  luaL_Buffer b;
-  luaL_buffinit(L, &b);
-  for (i=1; i<=n; i++) {
-    int c = luaL_checkint(L, i);
-    luaL_argcheck(L, uchar(c) == c, i, "invalid value");
-    luaL_addchar(&b, uchar(c));
-  }
-  luaL_pushresult(&b);
-  return 1;
-}
-
-
-static int writer (lua_State *L, const void* b, size_t size, void* B) {
-  (void)L;
-  luaL_addlstring((luaL_Buffer*) B, (const char *)b, size);
-  return 0;
-}
-
-
-static int str_dump (lua_State *L) {
-  luaL_Buffer b;
-  luaL_checktype(L, 1, LUA_TFUNCTION);
-  lua_settop(L, 1);
-  luaL_buffinit(L,&b);
-  if (lua_dump(L, writer, &b) != 0)
-    luaL_error(L, "unable to dump given function");
-  luaL_pushresult(&b);
-  return 1;
-}
-
-
-
-/*
-** {======================================================
-** PATTERN MATCHING
-** =======================================================
-*/
-
-
-#define CAP_UNFINISHED	(-1)
-#define CAP_POSITION	(-2)
-
-typedef struct MatchState {
-  const char *src_init;  /* init of source string */
-  const char *src_end;  /* end (`\0') of source string */
-  lua_State *L;
-  int level;  /* total number of captures (finished or unfinished) */
-  struct {
-    const char *init;
-    ptrdiff_t len;
-  } capture[LUA_MAXCAPTURES];
-} MatchState;
-
-
-#define L_ESC		'%'
-#define SPECIALS	"^$*+?.([%-"
-
-
-static int check_capture (MatchState *ms, int l) {
-  l -= '1';
-  if (l < 0 || l >= ms->level || ms->capture[l].len == CAP_UNFINISHED)
-    return luaL_error(ms->L, "invalid capture index");
-  return l;
-}
-
-
-static int capture_to_close (MatchState *ms) {
-  int level = ms->level;
-  for (level--; level>=0; level--)
-    if (ms->capture[level].len == CAP_UNFINISHED) return level;
-  return luaL_error(ms->L, "invalid pattern capture");
-}
-
-
-static const char *classend (MatchState *ms, const char *p) {
-  switch (*p++) {
-    case L_ESC: {
-      if (*p == '\0')
-        luaL_error(ms->L, "malformed pattern (ends with " LUA_QL("%%") ")");
-      return p+1;
-    }
-    case '[': {
-      if (*p == '^') p++;
-      do {  /* look for a `]' */
-        if (*p == '\0')
-          luaL_error(ms->L, "malformed pattern (missing " LUA_QL("]") ")");
-        if (*(p++) == L_ESC && *p != '\0')
-          p++;  /* skip escapes (e.g. `%]') */
-      } while (*p != ']');
-      return p+1;
-    }
-    default: {
-      return p;
-    }
-  }
-}
-
-
-static int match_class (int c, int cl) {
-  int res;
-  switch (tolower(cl)) {
-    case 'a' : res = isalpha(c); break;
-    case 'c' : res = iscntrl(c); break;
-    case 'd' : res = isdigit(c); break;
-    case 'l' : res = islower(c); break;
-    case 'p' : res = ispunct(c); break;
-    case 's' : res = isspace(c); break;
-    case 'u' : res = isupper(c); break;
-    case 'w' : res = isalnum(c); break;
-    case 'x' : res = isxdigit(c); break;
-    case 'z' : res = (c == 0); break;
-    default: return (cl == c);
-  }
-  return (islower(cl) ? res : !res);
-}
-
-
-static int matchbracketclass (int c, const char *p, const char *ec) {
-  int sig = 1;
-  if (*(p+1) == '^') {
-    sig = 0;
-    p++;  /* skip the `^' */
-  }
-  while (++p < ec) {
-    if (*p == L_ESC) {
-      p++;
-      if (match_class(c, uchar(*p)))
-        return sig;
-    }
-    else if ((*(p+1) == '-') && (p+2 < ec)) {
-      p+=2;
-      if (uchar(*(p-2)) <= c && c <= uchar(*p))
-        return sig;
-    }
-    else if (uchar(*p) == c) return sig;
-  }
-  return !sig;
-}
-
-
-static int singlematch (int c, const char *p, const char *ep) {
-  switch (*p) {
-    case '.': return 1;  /* matches any char */
-    case L_ESC: return match_class(c, uchar(*(p+1)));
-    case '[': return matchbracketclass(c, p, ep-1);
-    default:  return (uchar(*p) == c);
-  }
-}
-
-
-static const char *match (MatchState *ms, const char *s, const char *p);
-
-
-static const char *matchbalance (MatchState *ms, const char *s,
-                                   const char *p) {
-  if (*p == 0 || *(p+1) == 0)
-    luaL_error(ms->L, "unbalanced pattern");
-  if (*s != *p) return NULL;
-  else {
-    int b = *p;
-    int e = *(p+1);
-    int cont = 1;
-    while (++s < ms->src_end) {
-      if (*s == e) {
-        if (--cont == 0) return s+1;
-      }
-      else if (*s == b) cont++;
-    }
-  }
-  return NULL;  /* string ends out of balance */
-}
-
-
-static const char *max_expand (MatchState *ms, const char *s,
-                                 const char *p, const char *ep) {
-  ptrdiff_t i = 0;  /* counts maximum expand for item */
-  while ((s+i)<ms->src_end && singlematch(uchar(*(s+i)), p, ep))
-    i++;
-  /* keeps trying to match with the maximum repetitions */
-  while (i>=0) {
-    const char *res = match(ms, (s+i), ep+1);
-    if (res) return res;
-    i--;  /* else didn't match; reduce 1 repetition to try again */
-  }
-  return NULL;
-}
-
-
-static const char *min_expand (MatchState *ms, const char *s,
-                                 const char *p, const char *ep) {
-  for (;;) {
-    const char *res = match(ms, s, ep+1);
-    if (res != NULL)
-      return res;
-    else if (s<ms->src_end && singlematch(uchar(*s), p, ep))
-      s++;  /* try with one more repetition */
-    else return NULL;
-  }
-}
-
-
-static const char *start_capture (MatchState *ms, const char *s,
-                                    const char *p, int what) {
-  const char *res;
-  int level = ms->level;
-  if (level >= LUA_MAXCAPTURES) luaL_error(ms->L, "too many captures");
-  ms->capture[level].init = s;
-  ms->capture[level].len = what;
-  ms->level = level+1;
-  if ((res=match(ms, s, p)) == NULL)  /* match failed? */
-    ms->level--;  /* undo capture */
-  return res;
-}
-
-
-static const char *end_capture (MatchState *ms, const char *s,
-                                  const char *p) {
-  int l = capture_to_close(ms);
-  const char *res;
-  ms->capture[l].len = s - ms->capture[l].init;  /* close capture */
-  if ((res = match(ms, s, p)) == NULL)  /* match failed? */
-    ms->capture[l].len = CAP_UNFINISHED;  /* undo capture */
-  return res;
-}
-
-
-static const char *match_capture (MatchState *ms, const char *s, int l) {
-  size_t len;
-  l = check_capture(ms, l);
-  len = ms->capture[l].len;
-  if ((size_t)(ms->src_end-s) >= len &&
-      memcmp(ms->capture[l].init, s, len) == 0)
-    return s+len;
-  else return NULL;
-}
-
-
-static const char *match (MatchState *ms, const char *s, const char *p) {
-  init: /* using goto's to optimize tail recursion */
-  switch (*p) {
-    case '(': {  /* start capture */
-      if (*(p+1) == ')')  /* position capture? */
-        return start_capture(ms, s, p+2, CAP_POSITION);
-      else
-        return start_capture(ms, s, p+1, CAP_UNFINISHED);
-    }
-    case ')': {  /* end capture */
-      return end_capture(ms, s, p+1);
-    }
-    case L_ESC: {
-      switch (*(p+1)) {
-        case 'b': {  /* balanced string? */
-          s = matchbalance(ms, s, p+2);
-          if (s == NULL) return NULL;
-          p+=4; goto init;  /* else return match(ms, s, p+4); */
-        }
-        case 'f': {  /* frontier? */
-          const char *ep; char previous;
-          p += 2;
-          if (*p != '[')
-            luaL_error(ms->L, "missing " LUA_QL("[") " after "
-                               LUA_QL("%%f") " in pattern");
-          ep = classend(ms, p);  /* points to what is next */
-          previous = (s == ms->src_init) ? '\0' : *(s-1);
-          if (matchbracketclass(uchar(previous), p, ep-1) ||
-             !matchbracketclass(uchar(*s), p, ep-1)) return NULL;
-          p=ep; goto init;  /* else return match(ms, s, ep); */
-        }
-        default: {
-          if (isdigit(uchar(*(p+1)))) {  /* capture results (%0-%9)? */
-            s = match_capture(ms, s, uchar(*(p+1)));
-            if (s == NULL) return NULL;
-            p+=2; goto init;  /* else return match(ms, s, p+2) */
-          }
-          goto dflt;  /* case default */
-        }
-      }
-    }
-    case '\0': {  /* end of pattern */
-      return s;  /* match succeeded */
-    }
-    case '$': {
-      if (*(p+1) == '\0')  /* is the `$' the last char in pattern? */
-        return (s == ms->src_end) ? s : NULL;  /* check end of string */
-      else goto dflt;
-    }
-    default: dflt: {  /* it is a pattern item */
-      const char *ep = classend(ms, p);  /* points to what is next */
-      int m = s<ms->src_end && singlematch(uchar(*s), p, ep);
-      switch (*ep) {
-        case '?': {  /* optional */
-          const char *res;
-          if (m && ((res=match(ms, s+1, ep+1)) != NULL))
-            return res;
-          p=ep+1; goto init;  /* else return match(ms, s, ep+1); */
-        }
-        case '*': {  /* 0 or more repetitions */
-          return max_expand(ms, s, p, ep);
-        }
-        case '+': {  /* 1 or more repetitions */
-          return (m ? max_expand(ms, s+1, p, ep) : NULL);
-        }
-        case '-': {  /* 0 or more repetitions (minimum) */
-          return min_expand(ms, s, p, ep);
-        }
-        default: {
-          if (!m) return NULL;
-          s++; p=ep; goto init;  /* else return match(ms, s+1, ep); */
-        }
-      }
-    }
-  }
-}
-
-
-
-static const char *lmemfind (const char *s1, size_t l1,
-                               const char *s2, size_t l2) {
-  if (l2 == 0) return s1;  /* empty strings are everywhere */
-  else if (l2 > l1) return NULL;  /* avoids a negative `l1' */
-  else {
-    const char *init;  /* to search for a `*s2' inside `s1' */
-    l2--;  /* 1st char will be checked by `memchr' */
-    l1 = l1-l2;  /* `s2' cannot be found after that */
-    while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) {
-      init++;   /* 1st char is already checked */
-      if (memcmp(init, s2+1, l2) == 0)
-        return init-1;
-      else {  /* correct `l1' and `s1' to try again */
-        l1 -= init-s1;
-        s1 = init;
-      }
-    }
-    return NULL;  /* not found */
-  }
-}
-
-
-static void push_onecapture (MatchState *ms, int i, const char *s,
-                                                    const char *e) {
-  if (i >= ms->level) {
-    if (i == 0)  /* ms->level == 0, too */
-      lua_pushlstring(ms->L, s, e - s);  /* add whole match */
-    else
-      luaL_error(ms->L, "invalid capture index");
-  }
-  else {
-    ptrdiff_t l = ms->capture[i].len;
-    if (l == CAP_UNFINISHED) luaL_error(ms->L, "unfinished capture");
-    if (l == CAP_POSITION)
-      lua_pushinteger(ms->L, ms->capture[i].init - ms->src_init + 1);
-    else
-      lua_pushlstring(ms->L, ms->capture[i].init, l);
-  }
-}
-
-
-static int push_captures (MatchState *ms, const char *s, const char *e) {
-  int i;
-  int nlevels = (ms->level == 0 && s) ? 1 : ms->level;
-  luaL_checkstack(ms->L, nlevels, "too many captures");
-  for (i = 0; i < nlevels; i++)
-    push_onecapture(ms, i, s, e);
-  return nlevels;  /* number of strings pushed */
-}
-
-
-static int str_find_aux (lua_State *L, int find) {
-  size_t l1, l2;
-  const char *s = luaL_checklstring(L, 1, &l1);
-  const char *p = luaL_checklstring(L, 2, &l2);
-  ptrdiff_t init = posrelat(luaL_optinteger(L, 3, 1), l1) - 1;
-  if (init < 0) init = 0;
-  else if ((size_t)(init) > l1) init = (ptrdiff_t)l1;
-  if (find && (lua_toboolean(L, 4) ||  /* explicit request? */
-      strpbrk(p, SPECIALS) == NULL)) {  /* or no special characters? */
-    /* do a plain search */
-    const char *s2 = lmemfind(s+init, l1-init, p, l2);
-    if (s2) {
-      lua_pushinteger(L, s2-s+1);
-      lua_pushinteger(L, s2-s+l2);
-      return 2;
-    }
-  }
-  else {
-    MatchState ms;
-    int anchor = (*p == '^') ? (p++, 1) : 0;
-    const char *s1=s+init;
-    ms.L = L;
-    ms.src_init = s;
-    ms.src_end = s+l1;
-    do {
-      const char *res;
-      ms.level = 0;
-      if ((res=match(&ms, s1, p)) != NULL) {
-        if (find) {
-          lua_pushinteger(L, s1-s+1);  /* start */
-          lua_pushinteger(L, res-s);   /* end */
-          return push_captures(&ms, NULL, 0) + 2;
-        }
-        else
-          return push_captures(&ms, s1, res);
-      }
-    } while (s1++ < ms.src_end && !anchor);
-  }
-  lua_pushnil(L);  /* not found */
-  return 1;
-}
-
-
-static int str_find (lua_State *L) {
-  return str_find_aux(L, 1);
-}
-
-
-static int str_match (lua_State *L) {
-  return str_find_aux(L, 0);
-}
-
-
-static int gmatch_aux (lua_State *L) {
-  MatchState ms;
-  size_t ls;
-  const char *s = lua_tolstring(L, lua_upvalueindex(1), &ls);
-  const char *p = lua_tostring(L, lua_upvalueindex(2));
-  const char *src;
-  ms.L = L;
-  ms.src_init = s;
-  ms.src_end = s+ls;
-  for (src = s + (size_t)lua_tointeger(L, lua_upvalueindex(3));
-       src <= ms.src_end;
-       src++) {
-    const char *e;
-    ms.level = 0;
-    if ((e = match(&ms, src, p)) != NULL) {
-      lua_Integer newstart = e-s;
-      if (e == src) newstart++;  /* empty match? go at least one position */
-      lua_pushinteger(L, newstart);
-      lua_replace(L, lua_upvalueindex(3));
-      return push_captures(&ms, src, e);
-    }
-  }
-  return 0;  /* not found */
-}
-
-
-static int gmatch (lua_State *L) {
-  luaL_checkstring(L, 1);
-  luaL_checkstring(L, 2);
-  lua_settop(L, 2);
-  lua_pushinteger(L, 0);
-  lua_pushcclosure(L, gmatch_aux, 3);
-  return 1;
-}
-
-#if LUA_OPTIMIZE_MEMORY == 0 || !defined(LUA_COMPAT_GFIND)
-static int gfind_nodef (lua_State *L) {
-  return luaL_error(L, LUA_QL("string.gfind") " was renamed to "
-                       LUA_QL("string.gmatch"));
-}
-#endif
-
-static void add_s (MatchState *ms, luaL_Buffer *b, const char *s,
-                                                   const char *e) {
-  size_t l, i;
-  const char *news = lua_tolstring(ms->L, 3, &l);
-  for (i = 0; i < l; i++) {
-    if (news[i] != L_ESC)
-      luaL_addchar(b, news[i]);
-    else {
-      i++;  /* skip ESC */
-      if (!isdigit(uchar(news[i])))
-        luaL_addchar(b, news[i]);
-      else if (news[i] == '0')
-          luaL_addlstring(b, s, e - s);
-      else {
-        push_onecapture(ms, news[i] - '1', s, e);
-        luaL_addvalue(b);  /* add capture to accumulated result */
-      }
-    }
-  }
-}
-
-
-static void add_value (MatchState *ms, luaL_Buffer *b, const char *s,
-                                                       const char *e) {
-  lua_State *L = ms->L;
-  switch (lua_type(L, 3)) {
-    case LUA_TNUMBER:
-    case LUA_TSTRING: {
-      add_s(ms, b, s, e);
-      return;
-    }
-    case LUA_TFUNCTION:
-    case LUA_TLIGHTFUNCTION: {
-      int n;
-      lua_pushvalue(L, 3);
-      n = push_captures(ms, s, e);
-      lua_call(L, n, 1);
-      break;
-    }
-    case LUA_TTABLE: {
-      push_onecapture(ms, 0, s, e);
-      lua_gettable(L, 3);
-      break;
-    }
-  }
-  if (!lua_toboolean(L, -1)) {  /* nil or false? */
-    lua_pop(L, 1);
-    lua_pushlstring(L, s, e - s);  /* keep original text */
-  }
-  else if (!lua_isstring(L, -1))
-    luaL_error(L, "invalid replacement value (a %s)", luaL_typename(L, -1)); 
-  luaL_addvalue(b);  /* add result to accumulator */
-}
-
-
-static int str_gsub (lua_State *L) {
-  size_t srcl;
-  const char *src = luaL_checklstring(L, 1, &srcl);
-  const char *p = luaL_checkstring(L, 2);
-  int  tr = lua_type(L, 3);
-  int max_s = luaL_optint(L, 4, srcl+1);
-  int anchor = (*p == '^') ? (p++, 1) : 0;
-  int n = 0;
-  MatchState ms;
-  luaL_Buffer b;
-  luaL_argcheck(L, tr == LUA_TNUMBER || tr == LUA_TSTRING ||
-                   tr == LUA_TFUNCTION || tr == LUA_TTABLE ||
-                   tr == LUA_TLIGHTFUNCTION, 3,
-                   "string/function/table/lightfunction expected");
-  luaL_buffinit(L, &b);
-  ms.L = L;
-  ms.src_init = src;
-  ms.src_end = src+srcl;
-  while (n < max_s) {
-    const char *e;
-    ms.level = 0;
-    e = match(&ms, src, p);
-    if (e) {
-      n++;
-      add_value(&ms, &b, src, e);
-    }
-    if (e && e>src) /* non empty match? */
-      src = e;  /* skip it */
-    else if (src < ms.src_end)
-      luaL_addchar(&b, *src++);
-    else break;
-    if (anchor) break;
-  }
-  luaL_addlstring(&b, src, ms.src_end-src);
-  luaL_pushresult(&b);
-  lua_pushinteger(L, n);  /* number of substitutions */
-  return 2;
-}
-
-/* }====================================================== */
-
-
-/* maximum size of each formatted item (> len(format('%99.99f', -1e308))) */
-/* was 512, modified to 128 for eLua */
-#define MAX_ITEM	128
-/* valid flags in a format specification */
-#define FLAGS	"-+ #0"
-/*
-** maximum size of each format specification (such as '%-099.99d')
-** (+10 accounts for %99.99x plus margin of error)
-*/
-#define MAX_FORMAT	(sizeof(FLAGS) + sizeof(LUA_INTFRMLEN) + 10)
-
-
-static void addquoted (lua_State *L, luaL_Buffer *b, int arg) {
-  size_t l;
-  const char *s = luaL_checklstring(L, arg, &l);
-  luaL_addchar(b, '"');
-  while (l--) {
-    switch (*s) {
-      case '"': case '\\': case '\n': {
-        luaL_addchar(b, '\\');
-        luaL_addchar(b, *s);
-        break;
-      }
-      case '\r': {
-        luaL_addlstring(b, "\\r", 2);
-        break;
-      }
-      case '\0': {
-        luaL_addlstring(b, "\\000", 4);
-        break;
-      }
-      default: {
-        luaL_addchar(b, *s);
-        break;
-      }
-    }
-    s++;
-  }
-  luaL_addchar(b, '"');
-}
-
-static const char *scanformat (lua_State *L, const char *strfrmt, char *form) {
-  const char *p = strfrmt;
-  while (*p != '\0' && strchr(FLAGS, *p) != NULL) p++;  /* skip flags */
-  if ((size_t)(p - strfrmt) >= sizeof(FLAGS))
-    luaL_error(L, "invalid format (repeated flags)");
-  if (isdigit(uchar(*p))) p++;  /* skip width */
-  if (isdigit(uchar(*p))) p++;  /* (2 digits at most) */
-  if (*p == '.') {
-    p++;
-    if (isdigit(uchar(*p))) p++;  /* skip precision */
-    if (isdigit(uchar(*p))) p++;  /* (2 digits at most) */
-  }
-  if (isdigit(uchar(*p)))
-    luaL_error(L, "invalid format (width or precision too long)");
-  *(form++) = '%';
-  strncpy(form, strfrmt, p - strfrmt + 1);
-  form += p - strfrmt + 1;
-  *form = '\0';
-  return p;
-}
-
-
-static void addintlen (char *form) {
-  size_t l = strlen(form);
-  char spec = form[l - 1];
-  strcpy(form + l - 1, LUA_INTFRMLEN);
-  form[l + sizeof(LUA_INTFRMLEN) - 2] = spec;
-  form[l + sizeof(LUA_INTFRMLEN) - 1] = '\0';
-}
-
-
-static int str_format (lua_State *L) {
-  int top = lua_gettop(L);
-  int arg = 1;
-  size_t sfl;
-  const char *strfrmt = luaL_checklstring(L, arg, &sfl);
-  const char *strfrmt_end = strfrmt+sfl;
-  luaL_Buffer b;
-  luaL_buffinit(L, &b);
-  while (strfrmt < strfrmt_end) {
-    if (*strfrmt != L_ESC)
-      luaL_addchar(&b, *strfrmt++);
-    else if (*++strfrmt == L_ESC)
-      luaL_addchar(&b, *strfrmt++);  /* %% */
-    else { /* format item */
-      char form[MAX_FORMAT];  /* to store the format (`%...') */
-      char buff[MAX_ITEM];  /* to store the formatted item */
-      if (++arg > top)
-        luaL_argerror(L, arg, "no value");
-      strfrmt = scanformat(L, strfrmt, form);
-      switch (*strfrmt++) {
-        case 'c': {
-          sprintf(buff, form, (int)luaL_checknumber(L, arg));
-          break;
-        }
-        case 'd':  case 'i': {
-          addintlen(form);
-          sprintf(buff, form, (LUA_INTFRM_T)luaL_checknumber(L, arg));
-          break;
-        }
-        case 'o':  case 'u':  case 'x':  case 'X': {
-          addintlen(form);
-          sprintf(buff, form, (unsigned LUA_INTFRM_T)luaL_checknumber(L, arg));
-          break;
-        }
-#if !defined LUA_NUMBER_INTEGRAL        
-        case 'e':  case 'E': case 'f':
-        case 'g': case 'G': {
-          sprintf(buff, form, (double)luaL_checknumber(L, arg));
-          break;
-        }
-#endif
-        case 'q': {
-          addquoted(L, &b, arg);
-          continue;  /* skip the 'addsize' at the end */
-        }
-        case 's': {
-          size_t l;
-          const char *s = luaL_checklstring(L, arg, &l);
-          if (!strchr(form, '.') && l >= 100) {
-            /* no precision and string is too long to be formatted;
-               keep original string */
-            lua_pushvalue(L, arg);
-            luaL_addvalue(&b);
-            continue;  /* skip the `addsize' at the end */
-          }
-          else {
-            sprintf(buff, form, s);
-            break;
-          }
-        }
-        default: {  /* also treat cases `pnLlh' */
-          return luaL_error(L, "invalid option " LUA_QL("%%%c") " to "
-                               LUA_QL("format"), *(strfrmt - 1));
-        }
-      }
-      luaL_addlstring(&b, buff, strlen(buff));
-    }
-  }
-  luaL_pushresult(&b);
-  return 1;
-}
-
-#define MIN_OPT_LEVEL 1
-#include "lrodefs.h"
-const LUA_REG_TYPE strlib[] = {
-  {LSTRKEY("byte"), LFUNCVAL(str_byte)},
-  {LSTRKEY("char"), LFUNCVAL(str_char)},
-  {LSTRKEY("dump"), LFUNCVAL(str_dump)},
-  {LSTRKEY("find"), LFUNCVAL(str_find)},
-  {LSTRKEY("format"), LFUNCVAL(str_format)},
-#if LUA_OPTIMIZE_MEMORY > 0 && defined(LUA_COMPAT_GFIND)
-  {LSTRKEY("gfind"), LFUNCVAL(gmatch)},
-#else
-  {LSTRKEY("gfind"), LFUNCVAL(gfind_nodef)},
-#endif
-  {LSTRKEY("gmatch"), LFUNCVAL(gmatch)},
-  {LSTRKEY("gsub"), LFUNCVAL(str_gsub)},
-  {LSTRKEY("len"), LFUNCVAL(str_len)},
-  {LSTRKEY("lower"), LFUNCVAL(str_lower)},
-  {LSTRKEY("match"), LFUNCVAL(str_match)},
-  {LSTRKEY("rep"), LFUNCVAL(str_rep)},
-  {LSTRKEY("reverse"), LFUNCVAL(str_reverse)},
-  {LSTRKEY("sub"), LFUNCVAL(str_sub)},
-  {LSTRKEY("upper"), LFUNCVAL(str_upper)},
-#if LUA_OPTIMIZE_MEMORY > 0
-  {LSTRKEY("__index"), LROVAL(strlib)},
-#endif
-  {LNILKEY, LNILVAL}
-};
-
-
-#if LUA_OPTIMIZE_MEMORY != 2
-static void createmetatable (lua_State *L) {
-  lua_createtable(L, 0, 1);  /* create metatable for strings */
-  lua_pushliteral(L, "");  /* dummy string */
-  lua_pushvalue(L, -2);
-  lua_setmetatable(L, -2);  /* set string metatable */
-  lua_pop(L, 1);  /* pop dummy string */
-  lua_pushvalue(L, -2);  /* string library... */
-  lua_setfield(L, -2, "__index");  /* ...is the __index metamethod */
-  lua_pop(L, 1);  /* pop metatable */
-}
-#endif
-
-/*
-** Open string library
-*/
-LUALIB_API int luaopen_string (lua_State *L) {
-#if LUA_OPTIMIZE_MEMORY == 0
-  luaL_register(L, LUA_STRLIBNAME, strlib);
-#if defined(LUA_COMPAT_GFIND)
-  lua_getfield(L, -1, "gmatch");
-  lua_setfield(L, -2, "gfind");
-#endif
-  createmetatable(L);
-  return 1;
-#else
-  lua_pushliteral(L,"");
-  lua_pushrotable(L, (void*)strlib);
-  lua_setmetatable(L, -2);
-  lua_pop(L,1);
-  return 0;  
-#endif
-}
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/ltable.c
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/ltable.c b/libs/elua/elua_base/src/ltable.c
deleted file mode 100644
index 8fcf109..0000000
--- a/libs/elua/elua_base/src/ltable.c
+++ /dev/null
@@ -1,759 +0,0 @@
-/*
-** $Id: ltable.c,v 2.32.1.2 2007/12/28 15:32:23 roberto Exp $
-** Lua tables (hash)
-** See Copyright Notice in lua.h
-*/
-
-
-/*
-** Implementation of tables (aka arrays, objects, or hash tables).
-** Tables keep its elements in two parts: an array part and a hash part.
-** Non-negative integer keys are all candidates to be kept in the array
-** part. The actual size of the array is the largest `n' such that at
-** least half the slots between 0 and n are in use.
-** Hash uses a mix of chained scatter table with Brent's variation.
-** A main invariant of these tables is that, if an element is not
-** in its main position (i.e. the `original' position that its hash gives
-** to it), then the colliding element is in its own main position.
-** Hence even when the load factor reaches 100%, performance remains good.
-*/
-
-#include <math.h>
-#include <string.h>
-
-#define ltable_c
-#define LUA_CORE
-
-#include "lua.h"
-
-#include "ldebug.h"
-#include "ldo.h"
-#include "lgc.h"
-#include "lmem.h"
-#include "lobject.h"
-#include "lstate.h"
-#include "ltable.h"
-#include "lrotable.h"
-
-/*
-** max size of array part is 2^MAXBITS
-*/
-#if LUAI_BITSINT > 26
-#define MAXBITS		26
-#else
-#define MAXBITS		(LUAI_BITSINT-2)
-#endif
-
-#define MAXASIZE	(1 << MAXBITS)
-
-
-#define hashpow2(t,n)      (gnode(t, lmod((n), sizenode(t))))
-  
-#define hashstr(t,str)  hashpow2(t, (str)->tsv.hash)
-#define hashboolean(t,p)        hashpow2(t, p)
-
-
-/*
-** for some types, it is better to avoid modulus by power of 2, as
-** they tend to have many 2 factors.
-*/
-#define hashmod(t,n)	(gnode(t, ((n) % ((sizenode(t)-1)|1))))
-
-
-#define hashpointer(t,p)	hashmod(t, IntPoint(p))
-
-
-/*
-** number of ints inside a lua_Number
-*/
-#define numints		cast_int(sizeof(lua_Number)/sizeof(int))
-
-
-
-#define dummynode		(&dummynode_)
-
-static const Node dummynode_ = {
-  {LUA_TVALUE_NIL},  /* value */
-  {LUA_TKEY_NIL}     /* key */
-};
-
-
-/*
-** hash for lua_Numbers
-*/
-static Node *hashnum (const Table *t, lua_Number n) {
-  unsigned int a[numints];
-  int i;
-  if (luai_numeq(n, 0))  /* avoid problems with -0 */
-    return gnode(t, 0);
-  memcpy(a, &n, sizeof(a));
-  for (i = 1; i < numints; i++) a[0] += a[i];
-  return hashmod(t, a[0]);
-}
-
-
-
-/*
-** returns the `main' position of an element in a table (that is, the index
-** of its hash value)
-*/
-static Node *mainposition (const Table *t, const TValue *key) {
-  switch (ttype(key)) {
-    case LUA_TNUMBER:
-      return hashnum(t, nvalue(key));
-    case LUA_TSTRING:
-      return hashstr(t, rawtsvalue(key));
-    case LUA_TBOOLEAN:
-      return hashboolean(t, bvalue(key));
-    case LUA_TLIGHTUSERDATA:
-    case LUA_TROTABLE:
-    case LUA_TLIGHTFUNCTION:
-      return hashpointer(t, pvalue(key));
-    default:
-      return hashpointer(t, gcvalue(key));
-  }
-}
-
-
-/*
-** returns the index for `key' if `key' is an appropriate key to live in
-** the array part of the table, -1 otherwise.
-*/
-static int arrayindex (const TValue *key) {
-  if (ttisnumber(key)) {
-    lua_Number n = nvalue(key);
-    int k;
-    lua_number2int(k, n);
-    if (luai_numeq(cast_num(k), n))
-      return k;
-  }
-  return -1;  /* `key' did not match some condition */
-}
-
-
-/*
-** returns the index of a `key' for table traversals. First goes all
-** elements in the array part, then elements in the hash part. The
-** beginning of a traversal is signalled by -1.
-*/
-static int findindex (lua_State *L, Table *t, StkId key) {
-  int i;
-  if (ttisnil(key)) return -1;  /* first iteration */
-  i = arrayindex(key);
-  if (0 < i && i <= t->sizearray)  /* is `key' inside array part? */
-    return i-1;  /* yes; that's the index (corrected to C) */
-  else {
-    Node *n = mainposition(t, key);
-    do {  /* check whether `key' is somewhere in the chain */
-      /* key may be dead already, but it is ok to use it in `next' */
-      if (luaO_rawequalObj(key2tval(n), key) ||
-            (ttype(gkey(n)) == LUA_TDEADKEY && iscollectable(key) &&
-             gcvalue(gkey(n)) == gcvalue(key))) {
-        i = cast_int(n - gnode(t, 0));  /* key index in hash table */
-        /* hash elements are numbered after array ones */
-        return i + t->sizearray;
-      }
-      else n = gnext(n);
-    } while (n);
-    luaG_runerror(L, "invalid key to " LUA_QL("next"));  /* key not found */
-    return 0;  /* to avoid warnings */
-  }
-}
-
-
-int luaH_next (lua_State *L, Table *t, StkId key) {
-  int i = findindex(L, t, key);  /* find original element */
-  for (i++; i < t->sizearray; i++) {  /* try first array part */
-    if (!ttisnil(&t->array[i])) {  /* a non-nil value? */
-      setnvalue(key, cast_num(i+1));
-      setobj2s(L, key+1, &t->array[i]);
-      return 1;
-    }
-  }
-  for (i -= t->sizearray; i < sizenode(t); i++) {  /* then hash part */
-    if (!ttisnil(gval(gnode(t, i)))) {  /* a non-nil value? */
-      setobj2s(L, key, key2tval(gnode(t, i)));
-      setobj2s(L, key+1, gval(gnode(t, i)));
-      return 1;
-    }
-  }
-  return 0;  /* no more elements */
-}
-
-
-int luaH_next_ro (lua_State *L, void *t, StkId key) {
-  luaR_next(L, t, key, key+1);
-  return ttisnil(key) ? 0 : 1;
-}
-
-
-/*
-** {=============================================================
-** Rehash
-** ==============================================================
-*/
-
-
-static int computesizes (int nums[], int *narray) {
-  int i;
-  int twotoi;  /* 2^i */
-  int a = 0;  /* number of elements smaller than 2^i */
-  int na = 0;  /* number of elements to go to array part */
-  int n = 0;  /* optimal size for array part */
-  for (i = 0, twotoi = 1; twotoi/2 < *narray; i++, twotoi *= 2) {
-    if (nums[i] > 0) {
-      a += nums[i];
-      if (a > twotoi/2) {  /* more than half elements present? */
-        n = twotoi;  /* optimal size (till now) */
-        na = a;  /* all elements smaller than n will go to array part */
-      }
-    }
-    if (a == *narray) break;  /* all elements already counted */
-  }
-  *narray = n;
-  lua_assert(*narray/2 <= na && na <= *narray);
-  return na;
-}
-
-
-static int countint (const TValue *key, int *nums) {
-  int k = arrayindex(key);
-  if (0 < k && k <= MAXASIZE) {  /* is `key' an appropriate array index? */
-    nums[ceillog2(k)]++;  /* count as such */
-    return 1;
-  }
-  else
-    return 0;
-}
-
-
-static int numusearray (const Table *t, int *nums) {
-  int lg;
-  int ttlg;  /* 2^lg */
-  int ause = 0;  /* summation of `nums' */
-  int i = 1;  /* count to traverse all array keys */
-  for (lg=0, ttlg=1; lg<=MAXBITS; lg++, ttlg*=2) {  /* for each slice */
-    int lc = 0;  /* counter */
-    int lim = ttlg;
-    if (lim > t->sizearray) {
-      lim = t->sizearray;  /* adjust upper limit */
-      if (i > lim)
-        break;  /* no more elements to count */
-    }
-    /* count elements in range (2^(lg-1), 2^lg] */
-    for (; i <= lim; i++) {
-      if (!ttisnil(&t->array[i-1]))
-        lc++;
-    }
-    nums[lg] += lc;
-    ause += lc;
-  }
-  return ause;
-}
-
-
-static int numusehash (const Table *t, int *nums, int *pnasize) {
-  int totaluse = 0;  /* total number of elements */
-  int ause = 0;  /* summation of `nums' */
-  int i = sizenode(t);
-  while (i--) {
-    Node *n = &t->node[i];
-    if (!ttisnil(gval(n))) {
-      ause += countint(key2tval(n), nums);
-      totaluse++;
-    }
-  }
-  *pnasize += ause;
-  return totaluse;
-}
-
-
-static void setarrayvector (lua_State *L, Table *t, int size) {
-  int i;
-  luaM_reallocvector(L, t->array, t->sizearray, size, TValue);
-  for (i=t->sizearray; i<size; i++)
-     setnilvalue(&t->array[i]);
-  t->sizearray = size;
-}
-
-
-static Node *getfreepos (Table *t) {
-  while (t->lastfree-- > t->node) {
-    if (ttisnil(gkey(t->lastfree)))
-      return t->lastfree;
-  }
-  return NULL;  /* could not find a free place */
-}
-
-
-static void resizenodevector (lua_State *L, Table *t, int oldsize, int newsize) {
-  int lsize;
-  if (newsize == 0) {  /* no elements to hash part? */
-    t->node = cast(Node *, dummynode);  /* use common `dummynode' */
-    lsize = 0;
-  }
-  else {
-    Node *node = t->node;
-    int i;
-    lsize = ceillog2(newsize);
-    if (lsize > MAXBITS)
-      luaG_runerror(L, "table overflow");
-    newsize = twoto(lsize);
-    if (node == dummynode) {
-      oldsize = 0;
-      node = NULL; /* don't try to realloc `dummynode' pointer. */
-    }
-    luaM_reallocvector(L, node, oldsize, newsize, Node);
-    t->node = node;
-    for (i=oldsize; i<newsize; i++) {
-      Node *n = gnode(t, i);
-      gnext(n) = NULL;
-      setnilvalue(gkey(n));
-      setnilvalue(gval(n));
-    }
-  }
-  t->lsizenode = cast_byte(lsize);
-  t->lastfree = gnode(t, newsize);  /* reset lastfree to end of table. */
-}
-
-
-static Node *find_prev_node(Node *mp, Node *next) {
-  Node *prev = mp;
-  while (prev != NULL && gnext(prev) != next) prev = gnext(prev);
-  return prev;
-}
-
-
-/*
-** move a node from it's old position to it's new position during a rehash;
-** first, check whether the moving node's main position is free. If not, check whether
-** colliding node is in its main position or not: if it is not, move colliding
-** node to an empty place and put moving node in its main position; otherwise
-** (colliding node is in its main position), moving node goes to an empty position. 
-*/
-static int move_node (lua_State *L, Table *t, Node *node) {
-  Node *mp = mainposition(t, key2tval(node));
-  /* if node is in it's main position, don't need to move node. */
-  if (mp == node) return 1;
-  /* if node is in it's main position's chain, don't need to move node. */
-  if (find_prev_node(mp, node) != NULL) return 1;
-  /* is main position is free? */
-  if (!ttisnil(gval(mp)) || mp == dummynode) {
-    /* no; move main position node if it is out of its main position */
-    Node *othermp;
-    othermp = mainposition(t, key2tval(mp));
-    if (othermp != mp) {  /* is colliding node out of its main position? */
-      /* yes; swap colliding node with the node that is being moved. */
-      Node *prev;
-      Node tmp;
-      tmp = *node;
-      prev = find_prev_node(othermp, mp);  /* find previous */
-      if (prev != NULL) gnext(prev) = node;  /* redo the chain with `n' in place of `mp' */
-      *node = *mp;  /* copy colliding node into free pos. (mp->next also goes) */
-      *mp = tmp;
-      return (prev != NULL) ? 1 : 0; /* is colliding node part of its main position chain? */
-    }
-    else {  /* colliding node is in its own main position */
-      /* add node to main position's chain. */
-      gnext(node) = gnext(mp);  /* chain new position */
-      gnext(mp) = node;
-    }
-  }
-  else { /* main position is free, move node */
-    *mp = *node;
-    gnext(node) = NULL;
-    setnilvalue(gkey(node));
-    setnilvalue(gval(node));
-  }
-  return 1;
-}
-
-
-static int move_number (lua_State *L, Table *t, Node *node) {
-  int key;
-  lua_Number n = nvalue(key2tval(node));
-  lua_number2int(key, n);
-  if (luai_numeq(cast_num(key), nvalue(key2tval(node)))) {/* index is int? */
-    /* (1 <= key && key <= t->sizearray) */
-    if (cast(unsigned int, key-1) < cast(unsigned int, t->sizearray)) {
-      setobjt2t(L, &t->array[key-1], gval(node));
-      setnilvalue(gkey(node));
-      setnilvalue(gval(node));
-      return 1;
-    }
-  }
-  return 0;
-}
-
-
-static void resize_hashpart (lua_State *L, Table *t, int nhsize) {
-  int i;
-  int lsize=0;
-  int oldhsize = (t->node != dummynode) ? twoto(t->lsizenode) : 0;
-  if (nhsize > 0) { /* round new hashpart size up to next power of two. */
-    lsize=ceillog2(nhsize);
-    if (lsize > MAXBITS)
-      luaG_runerror(L, "table overflow");
-  }
-  nhsize = twoto(lsize);
-  /* grow hash part to new size. */
-  if (oldhsize < nhsize)
-    resizenodevector(L, t, oldhsize, nhsize);
-  else { /* hash part might be shrinking */
-    if (nhsize > 0) {
-      t->lsizenode = cast_byte(lsize);
-      t->lastfree = gnode(t, nhsize);  /* reset lastfree back to end of table. */
-    }
-    else { /* new hashpart size is zero. */
-      resizenodevector(L, t, oldhsize, nhsize);
-      return;
-    }
-  }
-  /* break old chains, try moving int keys to array part and compact keys into new hashpart */
-  for (i = 0; i < oldhsize; i++) {
-    Node *old = gnode(t, i);
-    gnext(old) = NULL;
-    if (ttisnil(gval(old))) { /* clear nodes with nil values. */
-      setnilvalue(gkey(old));
-      continue;
-    }
-    if (ttisnumber(key2tval(old))) { /* try moving the int keys into array part. */
-      if(move_number(L, t, old))
-        continue;
-    }
-    if (i >= nhsize) { /* move all valid keys to indices < nhsize. */
-      Node *n = getfreepos(t);  /* get a free place */
-      lua_assert(n != dummynode && n != NULL);
-      *n = *old;
-    }
-  }
-  /* shrink hash part */
-  if (oldhsize > nhsize)
-    resizenodevector(L, t, oldhsize, nhsize);
-  /* move nodes to their new mainposition and re-create node chains */
-  for (i = 0; i < nhsize; i++) {
-    Node *curr = gnode(t, i);
-    if (!ttisnil(gval(curr)))
-      while (move_node(L, t, curr) == 0);
-  }
-}
-
-
-static void resize (lua_State *L, Table *t, int nasize, int nhsize) {
-  int i;
-  int oldasize = t->sizearray;
-  if (nasize > oldasize)  /* array part must grow? */
-    setarrayvector(L, t, nasize);
-  resize_hashpart(L, t, nhsize);
-  if (nasize < oldasize) {  /* array part must shrink? */
-    t->sizearray = nasize;
-    /* re-insert elements from vanishing slice */
-    for (i=nasize; i<oldasize; i++) {
-      if (!ttisnil(&t->array[i]))
-        setobjt2t(L, luaH_setnum(L, t, i+1), &t->array[i]);
-    }
-    /* shrink array */
-    luaM_reallocvector(L, t->array, oldasize, nasize, TValue);
-  }
-}
-
-
-void luaH_resizearray (lua_State *L, Table *t, int nasize) {
-  int nsize = (t->node == dummynode) ? 0 : sizenode(t);
-  resize(L, t, nasize, nsize);
-}
-
-
-static void rehash (lua_State *L, Table *t, const TValue *ek) {
-  int nasize, na;
-  int nums[MAXBITS+1];  /* nums[i] = number of keys between 2^(i-1) and 2^i */
-  int i;
-  int totaluse;
-  for (i=0; i<=MAXBITS; i++) nums[i] = 0;  /* reset counts */
-  nasize = numusearray(t, nums);  /* count keys in array part */
-  totaluse = nasize;  /* all those keys are integer keys */
-  totaluse += numusehash(t, nums, &nasize);  /* count keys in hash part */
-  /* count extra key */
-  nasize += countint(ek, nums);
-  totaluse++;
-  /* compute new size for array part */
-  na = computesizes(nums, &nasize);
-  /* resize the table to new computed sizes */
-  resize(L, t, nasize, totaluse - na);
-}
-
-
-
-/*
-** }=============================================================
-*/
-
-
-Table *luaH_new (lua_State *L, int narray, int nhash) {
-  Table *t = luaM_new(L, Table);
-  luaC_link(L, obj2gco(t), LUA_TTABLE);
-  sethvalue2s(L, L->top, t); /* put table on stack */
-  incr_top(L);
-  t->metatable = NULL;
-  t->flags = cast_byte(~0);
-  /* temporary values (kept only if some malloc fails) */
-  t->array = NULL;
-  t->sizearray = 0;
-  t->lsizenode = 0;
-  t->node = cast(Node *, dummynode);
-  setarrayvector(L, t, narray);
-  resizenodevector(L, t, 0, nhash);
-  L->top--; /* remove table from stack */
-  return t;
-}
-
-
-void luaH_free (lua_State *L, Table *t) {
-  if (t->node != dummynode)
-    luaM_freearray(L, t->node, sizenode(t), Node);
-  luaM_freearray(L, t->array, t->sizearray, TValue);
-  luaM_free(L, t);
-}
-
-
-
-/*
-** inserts a new key into a hash table; first, check whether key's main 
-** position is free. If not, check whether colliding node is in its main 
-** position or not: if it is not, move colliding node to an empty place and 
-** put new key in its main position; otherwise (colliding node is in its main 
-** position), new key goes to an empty position. 
-*/
-static TValue *newkey (lua_State *L, Table *t, const TValue *key) {
-  Node *mp = mainposition(t, key);
-  if (!ttisnil(gval(mp)) || mp == dummynode) {
-    Node *othern;
-    Node *n = getfreepos(t);  /* get a free place */
-    if (n == NULL) {  /* cannot find a free place? */
-      rehash(L, t, key);  /* grow table */
-      return luaH_set(L, t, key);  /* re-insert key into grown table */
-    }
-    lua_assert(n != dummynode);
-    othern = mainposition(t, key2tval(mp));
-    if (othern != mp) {  /* is colliding node out of its main position? */
-      /* yes; move colliding node into free position */
-      while (gnext(othern) != mp) othern = gnext(othern);  /* find previous */
-      gnext(othern) = n;  /* redo the chain with `n' in place of `mp' */
-      *n = *mp;  /* copy colliding node into free pos. (mp->next also goes) */
-      gnext(mp) = NULL;  /* now `mp' is free */
-      setnilvalue(gval(mp));
-    }
-    else {  /* colliding node is in its own main position */
-      /* new node will go into free position */
-      gnext(n) = gnext(mp);  /* chain new position */
-      gnext(mp) = n;
-      mp = n;
-    }
-  }
-  setobj2t(L, gkey(mp), key);
-  luaC_barriert(L, t, key);
-  lua_assert(ttisnil(gval(mp)));
-  return gval(mp);
-}
-
-
-/*
-** search function for integers
-*/
-const TValue *luaH_getnum (Table *t, int key) {
-  /* (1 <= key && key <= t->sizearray) */
-  if (cast(unsigned int, key-1) < cast(unsigned int, t->sizearray))
-    return &t->array[key-1];
-  else {
-    lua_Number nk = cast_num(key);
-    Node *n = hashnum(t, nk);
-    do {  /* check whether `key' is somewhere in the chain */
-      if (ttisnumber(gkey(n)) && luai_numeq(nvalue(gkey(n)), nk))
-        return gval(n);  /* that's it */
-      else n = gnext(n);
-    } while (n);
-    return luaO_nilobject;
-  }
-}
-
-/* same thing for rotables */
-const TValue *luaH_getnum_ro (void *t, int key) {
-  const TValue *res = luaR_findentry(t, NULL, key, NULL);
-  return res ? res : luaO_nilobject;
-}
-
-
-/*
-** search function for strings
-*/
-const TValue *luaH_getstr (Table *t, TString *key) {
-  Node *n = hashstr(t, key);
-  do {  /* check whether `key' is somewhere in the chain */
-    if (ttisstring(gkey(n)) && rawtsvalue(gkey(n)) == key)
-      return gval(n);  /* that's it */
-    else n = gnext(n);
-  } while (n);
-  return luaO_nilobject;
-}
-
-/* same thing for rotables */
-const TValue *luaH_getstr_ro (void *t, TString *key) {
-  char keyname[LUA_MAX_ROTABLE_NAME + 1];
-  const TValue *res;  
-  if (!t)
-    return luaO_nilobject;
-  luaR_getcstr(keyname, key, LUA_MAX_ROTABLE_NAME);   
-  res = luaR_findentry(t, keyname, 0, NULL);
-  return res ? res : luaO_nilobject;
-}
-
-
-/*
-** main search function
-*/
-const TValue *luaH_get (Table *t, const TValue *key) {
-  switch (ttype(key)) {
-    case LUA_TNIL: return luaO_nilobject;
-    case LUA_TSTRING: return luaH_getstr(t, rawtsvalue(key));
-    case LUA_TNUMBER: {
-      int k;
-      lua_Number n = nvalue(key);
-      lua_number2int(k, n);
-      if (luai_numeq(cast_num(k), nvalue(key))) /* index is int? */
-        return luaH_getnum(t, k);  /* use specialized version */
-      /* else go through */
-    }
-    default: {
-      Node *n = mainposition(t, key);
-      do {  /* check whether `key' is somewhere in the chain */
-        if (luaO_rawequalObj(key2tval(n), key))
-          return gval(n);  /* that's it */
-        else n = gnext(n);
-      } while (n);
-      return luaO_nilobject;
-    }
-  }
-}
-
-/* same thing for rotables */
-const TValue *luaH_get_ro (void *t, const TValue *key) {
-  switch (ttype(key)) {
-    case LUA_TNIL: return luaO_nilobject;
-    case LUA_TSTRING: return luaH_getstr_ro(t, rawtsvalue(key));
-    case LUA_TNUMBER: {
-      int k;
-      lua_Number n = nvalue(key);
-      lua_number2int(k, n);
-      if (luai_numeq(cast_num(k), nvalue(key))) /* index is int? */
-        return luaH_getnum_ro(t, k);  /* use specialized version */
-      /* else go through */
-    }
-    default: {
-      return luaO_nilobject;
-    }
-  }
-}
-
-
-TValue *luaH_set (lua_State *L, Table *t, const TValue *key) {
-  const TValue *p = luaH_get(t, key);
-  t->flags = 0;
-  if (p != luaO_nilobject)
-    return cast(TValue *, p);
-  else {
-    if (ttisnil(key)) luaG_runerror(L, "table index is nil");
-    else if (ttisnumber(key) && luai_numisnan(nvalue(key)))
-      luaG_runerror(L, "table index is NaN");
-    return newkey(L, t, key);
-  }
-}
-
-
-TValue *luaH_setnum (lua_State *L, Table *t, int key) {
-  const TValue *p = luaH_getnum(t, key);
-  if (p != luaO_nilobject)
-    return cast(TValue *, p);
-  else {
-    TValue k;
-    setnvalue(&k, cast_num(key));
-    return newkey(L, t, &k);
-  }
-}
-
-
-TValue *luaH_setstr (lua_State *L, Table *t, TString *key) {
-  const TValue *p = luaH_getstr(t, key);
-  if (p != luaO_nilobject)
-    return cast(TValue *, p);
-  else {
-    TValue k;
-    setsvalue(L, &k, key);
-    return newkey(L, t, &k);
-  }
-}
-
-
-static int unbound_search (Table *t, unsigned int j) {
-  unsigned int i = j;  /* i is zero or a present index */
-  j++;
-  /* find `i' and `j' such that i is present and j is not */
-  while (!ttisnil(luaH_getnum(t, j))) {
-    i = j;
-    j *= 2;
-    if (j > cast(unsigned int, MAX_INT)) {  /* overflow? */
-      /* table was built with bad purposes: resort to linear search */
-      i = 1;
-      while (!ttisnil(luaH_getnum(t, i))) i++;
-      return i - 1;
-    }
-  }
-  /* now do a binary search between them */
-  while (j - i > 1) {
-    unsigned int m = (i+j)/2;
-    if (ttisnil(luaH_getnum(t, m))) j = m;
-    else i = m;
-  }
-  return i;
-}
-
-
-/*
-** Try to find a boundary in table `t'. A `boundary' is an integer index
-** such that t[i] is non-nil and t[i+1] is nil (and 0 if t[1] is nil).
-*/
-int luaH_getn (Table *t) {
-  unsigned int j = t->sizearray;
-  if (j > 0 && ttisnil(&t->array[j - 1])) {
-    /* there is a boundary in the array part: (binary) search for it */
-    unsigned int i = 0;
-    while (j - i > 1) {
-      unsigned int m = (i+j)/2;
-      if (ttisnil(&t->array[m - 1])) j = m;
-      else i = m;
-    }
-    return i;
-  }
-  /* else must find a boundary in hash part */
-  else if (t->node == dummynode)  /* hash part is empty? */
-    return j;  /* that is easy... */
-  else return unbound_search(t, j);
-}
-
-/* same thing for rotables */
-int luaH_getn_ro (void *t) {
-  int i = 1, len=0;
-  
-  while(luaR_findentry(t, NULL, i ++, NULL))
-    len ++;
-  return len;
-}
-
-#if defined(LUA_DEBUG)
-
-Node *luaH_mainposition (const Table *t, const TValue *key) {
-  return mainposition(t, key);
-}
-
-int luaH_isdummy (Node *n) { return n == dummynode; }
-
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/ltable.h
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/ltable.h b/libs/elua/elua_base/src/ltable.h
deleted file mode 100644
index 4835f2c..0000000
--- a/libs/elua/elua_base/src/ltable.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
-** $Id: ltable.h,v 2.10.1.1 2007/12/27 13:02:25 roberto Exp $
-** Lua tables (hash)
-** See Copyright Notice in lua.h
-*/
-
-#ifndef ltable_h
-#define ltable_h
-
-#include "lobject.h"
-
-
-#define gnode(t,i)	(&(t)->node[i])
-#define gkey(n)		(&(n)->i_key.tvk)
-#define gval(n)		(&(n)->i_val)
-#define gnext(n)	((n)->i_key.nk.next)
-
-#define key2tval(n)	(&(n)->i_key.tvk)
-
-
-LUAI_FUNC const TValue *luaH_getnum (Table *t, int key);
-LUAI_FUNC const TValue *luaH_getnum_ro (void *t, int key);
-LUAI_FUNC TValue *luaH_setnum (lua_State *L, Table *t, int key);
-LUAI_FUNC const TValue *luaH_getstr (Table *t, TString *key);
-LUAI_FUNC const TValue *luaH_getstr_ro (void *t, TString *key);
-LUAI_FUNC TValue *luaH_setstr (lua_State *L, Table *t, TString *key);
-LUAI_FUNC const TValue *luaH_get (Table *t, const TValue *key);
-LUAI_FUNC const TValue *luaH_get_ro (void *t, const TValue *key);
-LUAI_FUNC TValue *luaH_set (lua_State *L, Table *t, const TValue *key);
-LUAI_FUNC Table *luaH_new (lua_State *L, int narray, int lnhash);
-LUAI_FUNC void luaH_resizearray (lua_State *L, Table *t, int nasize);
-LUAI_FUNC void luaH_free (lua_State *L, Table *t);
-LUAI_FUNC int luaH_next (lua_State *L, Table *t, StkId key);
-LUAI_FUNC int luaH_next_ro (lua_State *L, void *t, StkId key);
-LUAI_FUNC int luaH_getn (Table *t);
-LUAI_FUNC int luaH_getn_ro (void *t);
-
-#if defined(LUA_DEBUG)
-LUAI_FUNC Node *luaH_mainposition (const Table *t, const TValue *key);
-LUAI_FUNC int luaH_isdummy (Node *n);
-#endif
-
-
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/ltablib.c
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/ltablib.c b/libs/elua/elua_base/src/ltablib.c
deleted file mode 100644
index 4d20745..0000000
--- a/libs/elua/elua_base/src/ltablib.c
+++ /dev/null
@@ -1,287 +0,0 @@
-/*
-** $Id: ltablib.c,v 1.38.1.3 2008/02/14 16:46:58 roberto Exp $
-** Library for Table Manipulation
-** See Copyright Notice in lua.h
-*/
-
-
-#include <stddef.h>
-
-#define ltablib_c
-#define LUA_LIB
-
-#include "lua.h"
-
-#include "lauxlib.h"
-#include "lualib.h"
-#include "lrotable.h"
-
-
-#define aux_getn(L,n)	(luaL_checktype(L, n, LUA_TTABLE), luaL_getn(L, n))
-
-
-static int foreachi (lua_State *L) {
-  int i;
-  int n = aux_getn(L, 1);
-  luaL_checkanyfunction(L, 2);
-  for (i=1; i <= n; i++) {
-    lua_pushvalue(L, 2);  /* function */
-    lua_pushinteger(L, i);  /* 1st argument */
-    lua_rawgeti(L, 1, i);  /* 2nd argument */
-    lua_call(L, 2, 1);
-    if (!lua_isnil(L, -1))
-      return 1;
-    lua_pop(L, 1);  /* remove nil result */
-  }
-  return 0;
-}
-
-
-static int foreach (lua_State *L) {
-  luaL_checktype(L, 1, LUA_TTABLE);
-  luaL_checkanyfunction(L, 2);
-  lua_pushnil(L);  /* first key */
-  while (lua_next(L, 1)) {
-    lua_pushvalue(L, 2);  /* function */
-    lua_pushvalue(L, -3);  /* key */
-    lua_pushvalue(L, -3);  /* value */
-    lua_call(L, 2, 1);
-    if (!lua_isnil(L, -1))
-      return 1;
-    lua_pop(L, 2);  /* remove value and result */
-  }
-  return 0;
-}
-
-
-static int maxn (lua_State *L) {
-  lua_Number max = 0;
-  luaL_checktype(L, 1, LUA_TTABLE);
-  lua_pushnil(L);  /* first key */
-  while (lua_next(L, 1)) {
-    lua_pop(L, 1);  /* remove value */
-    if (lua_type(L, -1) == LUA_TNUMBER) {
-      lua_Number v = lua_tonumber(L, -1);
-      if (v > max) max = v;
-    }
-  }
-  lua_pushnumber(L, max);
-  return 1;
-}
-
-
-static int getn (lua_State *L) {
-  lua_pushinteger(L, aux_getn(L, 1));
-  return 1;
-}
-
-
-static int setn (lua_State *L) {
-  luaL_checktype(L, 1, LUA_TTABLE);
-#ifndef luaL_setn
-  luaL_setn(L, 1, luaL_checkint(L, 2));
-#else
-  luaL_error(L, LUA_QL("setn") " is obsolete");
-#endif
-  lua_pushvalue(L, 1);
-  return 1;
-}
-
-
-static int tinsert (lua_State *L) {
-  int e = aux_getn(L, 1) + 1;  /* first empty element */
-  int pos;  /* where to insert new element */
-  switch (lua_gettop(L)) {
-    case 2: {  /* called with only 2 arguments */
-      pos = e;  /* insert new element at the end */
-      break;
-    }
-    case 3: {
-      int i;
-      pos = luaL_checkint(L, 2);  /* 2nd argument is the position */
-      if (pos > e) e = pos;  /* `grow' array if necessary */
-      for (i = e; i > pos; i--) {  /* move up elements */
-        lua_rawgeti(L, 1, i-1);
-        lua_rawseti(L, 1, i);  /* t[i] = t[i-1] */
-      }
-      break;
-    }
-    default: {
-      return luaL_error(L, "wrong number of arguments to " LUA_QL("insert"));
-    }
-  }
-  luaL_setn(L, 1, e);  /* new size */
-  lua_rawseti(L, 1, pos);  /* t[pos] = v */
-  return 0;
-}
-
-
-static int tremove (lua_State *L) {
-  int e = aux_getn(L, 1);
-  int pos = luaL_optint(L, 2, e);
-  if (!(1 <= pos && pos <= e))  /* position is outside bounds? */
-   return 0;  /* nothing to remove */
-  luaL_setn(L, 1, e - 1);  /* t.n = n-1 */
-  lua_rawgeti(L, 1, pos);  /* result = t[pos] */
-  for ( ;pos<e; pos++) {
-    lua_rawgeti(L, 1, pos+1);
-    lua_rawseti(L, 1, pos);  /* t[pos] = t[pos+1] */
-  }
-  lua_pushnil(L);
-  lua_rawseti(L, 1, e);  /* t[e] = nil */
-  return 1;
-}
-
-
-static void addfield (lua_State *L, luaL_Buffer *b, int i) {
-  lua_rawgeti(L, 1, i);
-  if (!lua_isstring(L, -1))
-    luaL_error(L, "invalid value (%s) at index %d in table for "
-                  LUA_QL("concat"), luaL_typename(L, -1), i);
-    luaL_addvalue(b);
-}
-
-
-static int tconcat (lua_State *L) {
-  luaL_Buffer b;
-  size_t lsep;
-  int i, last;
-  const char *sep = luaL_optlstring(L, 2, "", &lsep);
-  luaL_checktype(L, 1, LUA_TTABLE);
-  i = luaL_optint(L, 3, 1);
-  last = luaL_opt(L, luaL_checkint, 4, luaL_getn(L, 1));
-  luaL_buffinit(L, &b);
-  for (; i < last; i++) {
-    addfield(L, &b, i);
-    luaL_addlstring(&b, sep, lsep);
-  }
-  if (i == last)  /* add last value (if interval was not empty) */
-    addfield(L, &b, i);
-  luaL_pushresult(&b);
-  return 1;
-}
-
-
-
-/*
-** {======================================================
-** Quicksort
-** (based on `Algorithms in MODULA-3', Robert Sedgewick;
-**  Addison-Wesley, 1993.)
-*/
-
-
-static void set2 (lua_State *L, int i, int j) {
-  lua_rawseti(L, 1, i);
-  lua_rawseti(L, 1, j);
-}
-
-static int sort_comp (lua_State *L, int a, int b) {
-  if (!lua_isnil(L, 2)) {  /* function? */
-    int res;
-    lua_pushvalue(L, 2);
-    lua_pushvalue(L, a-1);  /* -1 to compensate function */
-    lua_pushvalue(L, b-2);  /* -2 to compensate function and `a' */
-    lua_call(L, 2, 1);
-    res = lua_toboolean(L, -1);
-    lua_pop(L, 1);
-    return res;
-  }
-  else  /* a < b? */
-    return lua_lessthan(L, a, b);
-}
-
-static void auxsort (lua_State *L, int l, int u) {
-  while (l < u) {  /* for tail recursion */
-    int i, j;
-    /* sort elements a[l], a[(l+u)/2] and a[u] */
-    lua_rawgeti(L, 1, l);
-    lua_rawgeti(L, 1, u);
-    if (sort_comp(L, -1, -2))  /* a[u] < a[l]? */
-      set2(L, l, u);  /* swap a[l] - a[u] */
-    else
-      lua_pop(L, 2);
-    if (u-l == 1) break;  /* only 2 elements */
-    i = (l+u)/2;
-    lua_rawgeti(L, 1, i);
-    lua_rawgeti(L, 1, l);
-    if (sort_comp(L, -2, -1))  /* a[i]<a[l]? */
-      set2(L, i, l);
-    else {
-      lua_pop(L, 1);  /* remove a[l] */
-      lua_rawgeti(L, 1, u);
-      if (sort_comp(L, -1, -2))  /* a[u]<a[i]? */
-        set2(L, i, u);
-      else
-        lua_pop(L, 2);
-    }
-    if (u-l == 2) break;  /* only 3 elements */
-    lua_rawgeti(L, 1, i);  /* Pivot */
-    lua_pushvalue(L, -1);
-    lua_rawgeti(L, 1, u-1);
-    set2(L, i, u-1);
-    /* a[l] <= P == a[u-1] <= a[u], only need to sort from l+1 to u-2 */
-    i = l; j = u-1;
-    for (;;) {  /* invariant: a[l..i] <= P <= a[j..u] */
-      /* repeat ++i until a[i] >= P */
-      while (lua_rawgeti(L, 1, ++i), sort_comp(L, -1, -2)) {
-        if (i>u) luaL_error(L, "invalid order function for sorting");
-        lua_pop(L, 1);  /* remove a[i] */
-      }
-      /* repeat --j until a[j] <= P */
-      while (lua_rawgeti(L, 1, --j), sort_comp(L, -3, -1)) {
-        if (j<l) luaL_error(L, "invalid order function for sorting");
-        lua_pop(L, 1);  /* remove a[j] */
-      }
-      if (j<i) {
-        lua_pop(L, 3);  /* pop pivot, a[i], a[j] */
-        break;
-      }
-      set2(L, i, j);
-    }
-    lua_rawgeti(L, 1, u-1);
-    lua_rawgeti(L, 1, i);
-    set2(L, u-1, i);  /* swap pivot (a[u-1]) with a[i] */
-    /* a[l..i-1] <= a[i] == P <= a[i+1..u] */
-    /* adjust so that smaller half is in [j..i] and larger one in [l..u] */
-    if (i-l < u-i) {
-      j=l; i=i-1; l=i+2;
-    }
-    else {
-      j=i+1; i=u; u=j-2;
-    }
-    auxsort(L, j, i);  /* call recursively the smaller one */
-  }  /* repeat the routine for the larger one */
-}
-
-static int sort (lua_State *L) {
-  int n = aux_getn(L, 1);
-  luaL_checkstack(L, 40, "");  /* assume array is smaller than 2^40 */
-  if (!lua_isnoneornil(L, 2))  /* is there a 2nd argument? */
-    luaL_checktype(L, 2, LUA_TFUNCTION);
-  lua_settop(L, 2);  /* make sure there is two arguments */
-  auxsort(L, 1, n);
-  return 0;
-}
-
-/* }====================================================== */
-
-
-#define MIN_OPT_LEVEL 1
-#include "lrodefs.h"
-const LUA_REG_TYPE tab_funcs[] = {
-  {LSTRKEY("concat"), LFUNCVAL(tconcat)},
-  {LSTRKEY("foreach"), LFUNCVAL(foreach)},
-  {LSTRKEY("foreachi"), LFUNCVAL(foreachi)},
-  {LSTRKEY("getn"), LFUNCVAL(getn)},
-  {LSTRKEY("maxn"), LFUNCVAL(maxn)},
-  {LSTRKEY("insert"), LFUNCVAL(tinsert)},
-  {LSTRKEY("remove"), LFUNCVAL(tremove)},
-  {LSTRKEY("setn"), LFUNCVAL(setn)},
-  {LSTRKEY("sort"), LFUNCVAL(sort)},
-  {LNILKEY, LNILVAL}
-};
-
-LUALIB_API int luaopen_table (lua_State *L) {
-  LREGISTER(L, LUA_TABLIBNAME, tab_funcs);
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/ltm.c
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/ltm.c b/libs/elua/elua_base/src/ltm.c
deleted file mode 100644
index a15e5f6..0000000
--- a/libs/elua/elua_base/src/ltm.c
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
-** $Id: ltm.c,v 2.8.1.1 2007/12/27 13:02:25 roberto Exp $
-** Tag methods
-** See Copyright Notice in lua.h
-*/
-
-
-#include <string.h>
-
-#define ltm_c
-#define LUA_CORE
-
-#include "lua.h"
-
-#include "lobject.h"
-#include "lstate.h"
-#include "lstring.h"
-#include "ltable.h"
-#include "ltm.h"
-#include "lrotable.h"
-
-
-
-const char *const luaT_typenames[] = {
-  "nil", "boolean", "romtable", "lightfunction", "userdata", "number",
-  "string", "table", "function", "userdata", "thread",
-  "proto", "upval"
-};
-
-
-void luaT_init (lua_State *L) {
-  static const char *const luaT_eventname[] = {  /* ORDER TM */
-    "__index", "__newindex",
-    "__gc", "__mode", "__eq",
-    "__add", "__sub", "__mul", "__div", "__mod",
-    "__pow", "__unm", "__len", "__lt", "__le",
-    "__concat", "__call"
-  };
-  int i;
-  for (i=0; i<TM_N; i++) {
-    G(L)->tmname[i] = luaS_new(L, luaT_eventname[i]);
-    luaS_fix(G(L)->tmname[i]);  /* never collect these names */
-  }
-}
-
-
-/*
-** function to be used with macro "fasttm": optimized for absence of
-** tag methods
-*/
-const TValue *luaT_gettm (Table *events, TMS event, TString *ename) {
-  const TValue *tm = luaR_isrotable(events) ? luaH_getstr_ro(events, ename) : luaH_getstr(events, ename); 
-  lua_assert(event <= TM_EQ);
-  if (ttisnil(tm)) {  /* no tag method? */
-    if (!luaR_isrotable(events))
-      events->flags |= cast_byte(1u<<event);  /* cache this fact */
-    return NULL;
-  }
-  else return tm;
-}
-
-
-const TValue *luaT_gettmbyobj (lua_State *L, const TValue *o, TMS event) {
-  Table *mt;
-  switch (ttype(o)) {
-    case LUA_TTABLE:
-      mt = hvalue(o)->metatable;
-      break;
-    case LUA_TROTABLE:
-      mt = (Table*)luaR_getmeta(rvalue(o));
-      break;
-    case LUA_TUSERDATA:
-      mt = uvalue(o)->metatable;
-      break;
-    default:
-      mt = G(L)->mt[ttype(o)];
-  }
-  if (!mt)
-    return luaO_nilobject;
-  else if (luaR_isrotable(mt))
-    return luaH_getstr_ro(mt, G(L)->tmname[event]);
-  else
-    return luaH_getstr(mt, G(L)->tmname[event]);
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/ltm.h
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/ltm.h b/libs/elua/elua_base/src/ltm.h
deleted file mode 100644
index 662fa2a..0000000
--- a/libs/elua/elua_base/src/ltm.h
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
-** $Id: ltm.h,v 2.6.1.1 2007/12/27 13:02:25 roberto Exp $
-** Tag methods
-** See Copyright Notice in lua.h
-*/
-
-#ifndef ltm_h
-#define ltm_h
-
-
-#include "lobject.h"
-
-
-/*
-* WARNING: if you change the order of this enumeration,
-* grep "ORDER TM"
-*/
-typedef enum {
-  TM_INDEX,
-  TM_NEWINDEX,
-  TM_GC,
-  TM_MODE,
-  TM_EQ,  /* last tag method with `fast' access */
-  TM_ADD,
-  TM_SUB,
-  TM_MUL,
-  TM_DIV,
-  TM_MOD,
-  TM_POW,
-  TM_UNM,
-  TM_LEN,
-  TM_LT,
-  TM_LE,
-  TM_CONCAT,
-  TM_CALL,
-  TM_N		/* number of elements in the enum */
-} TMS;
-
-
-
-#define gfasttm(g,et,e) ((et) == NULL ? NULL : \
-  !luaR_isrotable(et) && ((et)->flags & (1u<<(e))) ? NULL : luaT_gettm(et, e, (g)->tmname[e]))
-
-#define fasttm(l,et,e)	gfasttm(G(l), et, e)
-
-LUAI_DATA const char *const luaT_typenames[];
-
-
-LUAI_FUNC const TValue *luaT_gettm (Table *events, TMS event, TString *ename);
-LUAI_FUNC const TValue *luaT_gettmbyobj (lua_State *L, const TValue *o,
-                                                       TMS event);
-LUAI_FUNC void luaT_init (lua_State *L);
-
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/lua.c
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/lua.c b/libs/elua/elua_base/src/lua.c
deleted file mode 100644
index 835a344..0000000
--- a/libs/elua/elua_base/src/lua.c
+++ /dev/null
@@ -1,420 +0,0 @@
-/*
-** $Id: lua.c,v 1.160.1.2 2007/12/28 15:32:23 roberto Exp $
-** Lua stand-alone interpreter
-** See Copyright Notice in lua.h
-*/
-
-
-#include <signal.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#ifdef MYNEWT
-#include <console/console.h>
-#endif
-
-#define lua_c
-
-#include "lua.h"
-
-#include "lauxlib.h"
-#include "lualib.h"
-
-
-
-static lua_State *globalL = NULL;
-
-static const char *progname = LUA_PROGNAME;
-
-
-
-static void lstop (lua_State *L, lua_Debug *ar) {
-  (void)ar;  /* unused arg. */
-  lua_sethook(L, NULL, 0, 0);
-  luaL_error(L, "interrupted!");
-}
-
-
-static void laction (int i) {
-  signal(i, SIG_DFL); /* if another SIGINT happens before lstop,
-                              terminate process (default action) */
-  lua_sethook(globalL, lstop, LUA_MASKCALL | LUA_MASKRET | LUA_MASKCOUNT, 1);
-}
-
-
-static void print_usage (void) {
-#ifndef MYNEWT
-  fprintf(stderr,
-#else
-  console_printf(
-#endif
-  "usage: %s [options] [script [args]].\n"
-  "Available options are:\n"
-  "  -e stat  execute string " LUA_QL("stat") "\n"
-  "  -l name  require library " LUA_QL("name") "\n"
-  "  -m limit set memory limit. (units are in Kbytes)\n"
-  "  -i       enter interactive mode after executing " LUA_QL("script") "\n"
-  "  -v       show version information\n"
-  "  --       stop handling options\n"
-  "  -        execute stdin and stop handling options\n"
-  ,
-  progname);
-#ifndef MYNEWT
-  fflush(stderr);
-#endif
-}
-
-
-static void l_message (const char *pname, const char *msg) {
-#ifndef MYNEWT
-  if (pname) fprintf(stderr, "%s: ", pname);
-  fprintf(stderr, "%s\n", msg);
-  fflush(stderr);
-#else
-  if (pname) console_printf("%s: ", pname);
-  console_printf("%s\n", msg);
-#endif
-}
-
-
-static int report (lua_State *L, int status) {
-  if (status && !lua_isnil(L, -1)) {
-    const char *msg = lua_tostring(L, -1);
-    if (msg == NULL) msg = "(error object is not a string)";
-    l_message(progname, msg);
-    lua_pop(L, 1);
-  }
-  return status;
-}
-
-
-static int traceback (lua_State *L) {
-  if (!lua_isstring(L, 1))  /* 'message' not a string? */
-    return 1;  /* keep it intact */
-  lua_getfield(L, LUA_GLOBALSINDEX, "debug");
-  if (!lua_istable(L, -1) && !lua_isrotable(L, -1)) {
-    lua_pop(L, 1);
-    return 1;
-  }
-  lua_getfield(L, -1, "traceback");
-  if (!lua_isfunction(L, -1) && !lua_islightfunction(L, -1)) {
-    lua_pop(L, 2);
-    return 1;
-  }
-  lua_pushvalue(L, 1);  /* pass error message */
-  lua_pushinteger(L, 2);  /* skip this function and traceback */
-  lua_call(L, 2, 1);  /* call debug.traceback */
-  return 1;
-}
-
-
-static int docall (lua_State *L, int narg, int clear) {
-  int status;
-  int base = lua_gettop(L) - narg;  /* function index */
-  lua_pushcfunction(L, traceback);  /* push traceback function */
-  lua_insert(L, base);  /* put it under chunk and args */
-  signal(SIGINT, laction);
-  status = lua_pcall(L, narg, (clear ? 0 : LUA_MULTRET), base);
-  signal(SIGINT, SIG_DFL);
-  lua_remove(L, base);  /* remove traceback function */
-  /* force a complete garbage collection in case of errors */
-  if (status != 0) lua_gc(L, LUA_GCCOLLECT, 0);
-  return status;
-}
-
-
-static void print_version (void) {
-  l_message(NULL, LUA_RELEASE "  " LUA_COPYRIGHT);
-}
-
-
-static int getargs (lua_State *L, char **argv, int n) {
-  int narg;
-  int i;
-  int argc = 0;
-  while (argv[argc]) argc++;  /* count total number of arguments */
-  narg = argc - (n + 1);  /* number of arguments to the script */
-  luaL_checkstack(L, narg + 3, "too many arguments to script");
-  for (i=n+1; i < argc; i++)
-    lua_pushstring(L, argv[i]);
-  lua_createtable(L, narg, n + 1);
-  for (i=0; i < argc; i++) {
-    lua_pushstring(L, argv[i]);
-    lua_rawseti(L, -2, i - n);
-  }
-  return narg;
-}
-
-
-static int dofile (lua_State *L, const char *name) {
-  int status = luaL_loadfile(L, name) || docall(L, 0, 1);
-  return report(L, status);
-}
-
-
-static int dostring (lua_State *L, const char *s, const char *name) {
-  int status = luaL_loadbuffer(L, s, strlen(s), name) || docall(L, 0, 1);
-  return report(L, status);
-}
-
-
-static int dolibrary (lua_State *L, const char *name) {
-  lua_getglobal(L, "require");
-  lua_pushstring(L, name);
-  return report(L, docall(L, 1, 1));
-}
-
-
-static const char *get_prompt (lua_State *L, int firstline) {
-  const char *p;
-  lua_getfield(L, LUA_GLOBALSINDEX, firstline ? "_PROMPT" : "_PROMPT2");
-  p = lua_tostring(L, -1);
-  if (p == NULL) p = (firstline ? LUA_PROMPT : LUA_PROMPT2);
-  lua_pop(L, 1);  /* remove global */
-  return p;
-}
-
-
-static int incomplete (lua_State *L, int status) {
-  if (status == LUA_ERRSYNTAX) {
-    size_t lmsg;
-    const char *msg = lua_tolstring(L, -1, &lmsg);
-    const char *tp = msg + lmsg - (sizeof(LUA_QL("<eof>")) - 1);
-    if (strstr(msg, LUA_QL("<eof>")) == tp) {
-      lua_pop(L, 1);
-      return 1;
-    }
-  }
-  return 0;  /* else... */
-}
-
-
-static int pushline (lua_State *L, int firstline) {
-  char buffer[LUA_MAXINPUT];
-  char *b = buffer;
-  size_t l;
-  const char *prmt = get_prompt(L, firstline);
-  if (lua_readline(L, b, prmt) == 0)
-    return 0;  /* no input */
-  l = strlen(b);
-  if (l > 0 && b[l-1] == '\n')  /* line ends with newline? */
-    b[l-1] = '\0';  /* remove it */
-  if (firstline && b[0] == '=')  /* first line starts with `=' ? */
-    lua_pushfstring(L, "return %s", b+1);  /* change it to `return' */
-  else
-    lua_pushstring(L, b);
-  lua_freeline(L, b);
-  return 1;
-}
-
-
-static int loadline (lua_State *L) {
-  int status;
-  lua_settop(L, 0);
-  if (!pushline(L, 1))
-    return -1;  /* no input */
-  for (;;) {  /* repeat until gets a complete line */
-    status = luaL_loadbuffer(L, lua_tostring(L, 1), lua_strlen(L, 1), "=stdin");
-    if (!incomplete(L, status)) break;  /* cannot try to add lines? */
-    if (!pushline(L, 0))  /* no more input? */
-      return -1;
-    lua_pushliteral(L, "\n");  /* add a new line... */
-    lua_insert(L, -2);  /* ...between the two lines */
-    lua_concat(L, 3);  /* join them */
-  }
-  lua_saveline(L, 1);
-  lua_remove(L, 1);  /* remove line */
-  return status;
-}
-
-
-static void dotty (lua_State *L) {
-  int status;
-  const char *oldprogname = progname;
-  progname = NULL;
-  while ((status = loadline(L)) != -1) {
-    if (status == 0) status = docall(L, 0, 0);
-    report(L, status);
-    if (status == 0 && lua_gettop(L) > 0) {  /* any result to print? */
-      lua_getglobal(L, "print");
-      lua_insert(L, 1);
-      if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != 0)
-        l_message(progname, lua_pushfstring(L,
-                               "error calling " LUA_QL("print") " (%s)",
-                               lua_tostring(L, -1)));
-    }
-  }
-  lua_settop(L, 0);  /* clear stack */
-  fputs("\n", stdout);
-  fflush(stdout);
-  progname = oldprogname;
-}
-
-
-static int handle_script (lua_State *L, char **argv, int n) {
-  int status;
-  const char *fname;
-  int narg = getargs(L, argv, n);  /* collect arguments */
-  lua_setglobal(L, "arg");
-  fname = argv[n];
-  if (strcmp(fname, "-") == 0 && strcmp(argv[n-1], "--") != 0) 
-    fname = NULL;  /* stdin */
-  status = luaL_loadfile(L, fname);
-  lua_insert(L, -(narg+1));
-  if (status == 0)
-    status = docall(L, narg, 0);
-  else
-    lua_pop(L, narg);      
-  return report(L, status);
-}
-
-
-/* check that argument has no extra characters at the end */
-#define notail(x)	{if ((x)[2] != '\0') return -1;}
-
-
-static int collectargs (char **argv, int *pi, int *pv, int *pe) {
-  int i;
-  for (i = 1; argv[i] != NULL; i++) {
-    if (argv[i][0] != '-')  /* not an option? */
-        return i;
-    switch (argv[i][1]) {  /* option */
-      case '-':
-        notail(argv[i]);
-        return (argv[i+1] != NULL ? i+1 : 0);
-      case '\0':
-        return i;
-      case 'i':
-        notail(argv[i]);
-        *pi = 1;  /* go through */
-      case 'v':
-        notail(argv[i]);
-        *pv = 1;
-        break;
-      case 'e':
-        *pe = 1;  /* go through */
-      case 'm':   /* go through */
-      case 'l':
-        if (argv[i][2] == '\0') {
-          i++;
-          if (argv[i] == NULL) return -1;
-        }
-        break;
-      default: return -1;  /* invalid option */
-    }
-  }
-  return 0;
-}
-
-
-static int runargs (lua_State *L, char **argv, int n) {
-  int i;
-  for (i = 1; i < n; i++) {
-    if (argv[i] == NULL) continue;
-    lua_assert(argv[i][0] == '-');
-    switch (argv[i][1]) {  /* option */
-      case 'e': {
-        const char *chunk = argv[i] + 2;
-        if (*chunk == '\0') chunk = argv[++i];
-        lua_assert(chunk != NULL);
-        if (dostring(L, chunk, "=(command line)") != 0)
-          return 1;
-        break;
-      }
-      case 'm': {
-        const char *limit = argv[i] + 2;
-        int memlimit=0;
-        if (*limit == '\0') limit = argv[++i];
-        lua_assert(limit != NULL);
-        memlimit = atoi(limit);
-        lua_gc(L, LUA_GCSETMEMLIMIT, memlimit);
-        break;
-      }
-      case 'l': {
-        const char *filename = argv[i] + 2;
-        if (*filename == '\0') filename = argv[++i];
-        lua_assert(filename != NULL);
-        if (dolibrary(L, filename))
-          return 1;  /* stop if file fails */
-        break;
-      }
-      default: break;
-    }
-  }
-  return 0;
-}
-
-
-static int handle_luainit (lua_State *L) {
-  const char *init = getenv(LUA_INIT);
-  if (init == NULL) return 0;  /* status OK */
-  else if (init[0] == '@')
-    return dofile(L, init+1);
-  else
-    return dostring(L, init, "=" LUA_INIT);
-}
-
-
-struct Smain {
-  int argc;
-  char **argv;
-  int status;
-};
-
-
-static int pmain (lua_State *L) {
-  struct Smain *s = (struct Smain *)lua_touserdata(L, 1);
-  char **argv = s->argv;
-  int script;
-  int has_i = 0, has_v = 0, has_e = 0;
-  globalL = L;
-  if (argv[0] && argv[0][0]) progname = argv[0];
-  lua_gc(L, LUA_GCSTOP, 0);  /* stop collector during initialization */
-  luaL_openlibs(L);  /* open libraries */
-  lua_gc(L, LUA_GCRESTART, 0);
-  s->status = handle_luainit(L);
-  if (s->status != 0) return 0;
-  script = collectargs(argv, &has_i, &has_v, &has_e);
-  if (script < 0) {  /* invalid args? */
-    print_usage();
-    s->status = 1;
-    return 0;
-  }
-  if (has_v) print_version();
-  s->status = runargs(L, argv, (script > 0) ? script : s->argc);
-  if (s->status != 0) return 0;
-  if (script)
-    s->status = handle_script(L, argv, script);
-  if (s->status != 0) return 0;
-  if (has_i)
-    dotty(L);
-  else if (script == 0 && !has_e && !has_v) {
-    if (lua_stdin_is_tty()) {
-      print_version();
-      dotty(L);
-    }
-    else dofile(L, NULL);  /* executes stdin as a file */
-  }
-  return 0;
-}
-
-#ifdef LUA_RPC
-int main (int argc, char **argv) {
-#else
-int lua_main (int argc, char **argv) {
-#endif
-  int status;
-  struct Smain s;
-  lua_State *L = lua_open();  /* create state */
-  if (L == NULL) {
-    l_message(argv[0], "cannot create state: not enough memory");
-    return EXIT_FAILURE;
-  }
-  s.argc = argc;
-  s.argv = argv;
-  status = lua_cpcall(L, &pmain, &s);
-  report(L, status);
-  lua_close(L);
-  return (status || s.status) ? EXIT_FAILURE : EXIT_SUCCESS;
-}
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/lua.h
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/lua.h b/libs/elua/elua_base/src/lua.h
deleted file mode 100644
index bf9145c..0000000
--- a/libs/elua/elua_base/src/lua.h
+++ /dev/null
@@ -1,399 +0,0 @@
-/*
-** $Id: lua.h,v 1.218.1.5 2008/08/06 13:30:12 roberto Exp $
-** Lua - An Extensible Extension Language
-** Lua.org, PUC-Rio, Brazil (http://www.lua.org)
-** See Copyright Notice at the end of this file
-*/
-
-
-#ifndef lua_h
-#define lua_h
-
-#include <stdarg.h>
-#include <stddef.h>
-
-
-#include "luaconf.h"
-
-
-#define LUA_VERSION	"Lua 5.1"
-#define LUA_RELEASE	"Lua 5.1.4"
-#define LUA_VERSION_NUM	501
-#define LUA_COPYRIGHT	"Copyright (C) 1994-2011 Lua.org, PUC-Rio"
-#define LUA_AUTHORS 	"R. Ierusalimschy, L. H. de Figueiredo & W. Celes"
-
-
-/* mark for precompiled code (`<esc>Lua') */
-#define	LUA_SIGNATURE	"\033Lua"
-
-/* option for multiple returns in `lua_pcall' and `lua_call' */
-#define LUA_MULTRET	(-1)
-
-
-/*
-** pseudo-indices
-*/
-#define LUA_REGISTRYINDEX	(-10000)
-#define LUA_ENVIRONINDEX	(-10001)
-#define LUA_GLOBALSINDEX	(-10002)
-#define lua_upvalueindex(i)	(LUA_GLOBALSINDEX-(i))
-
-
-/* thread status; 0 is OK */
-#define LUA_YIELD	1
-#define LUA_ERRRUN	2
-#define LUA_ERRSYNTAX	3
-#define LUA_ERRMEM	4
-#define LUA_ERRERR	5
-
-
-typedef struct lua_State lua_State;
-
-typedef int (*lua_CFunction) (lua_State *L);
-
-
-/*
-** functions that read/write blocks when loading/dumping Lua chunks
-*/
-typedef const char * (*lua_Reader) (lua_State *L, void *ud, size_t *sz);
-
-typedef int (*lua_Writer) (lua_State *L, const void* p, size_t sz, void* ud);
-
-
-/*
-** prototype for memory-allocation functions
-*/
-typedef void * (*lua_Alloc) (void *ud, void *ptr, size_t osize, size_t nsize);
-
-
-/*
-** basic types
-*/
-#define LUA_TNONE		(-1)
-
-#define LUA_TNIL		0
-#define LUA_TBOOLEAN		1
-#define LUA_TROTABLE  2
-#define LUA_TLIGHTFUNCTION  3
-#define LUA_TLIGHTUSERDATA	4
-#define LUA_TNUMBER		5
-#define LUA_TSTRING		6
-#define LUA_TTABLE		7
-#define LUA_TFUNCTION		8
-#define LUA_TUSERDATA		9
-#define LUA_TTHREAD		10
-
-/* minimum Lua stack available to a C function */
-#define LUA_MINSTACK	20
-
-
-/*
-** generic extra include file
-*/
-#if defined(LUA_USER_H)
-#include LUA_USER_H
-#endif
-
-
-/* type of numbers in Lua */
-typedef LUA_NUMBER lua_Number;
-
-
-/* type for integer functions */
-typedef LUA_INTEGER lua_Integer;
-
-
-
-/*
-** state manipulation
-*/
-LUA_API lua_State *(lua_newstate) (lua_Alloc f, void *ud);
-LUA_API void       (lua_close) (lua_State *L);
-LUA_API lua_State *(lua_newthread) (lua_State *L);
-
-LUA_API lua_CFunction (lua_atpanic) (lua_State *L, lua_CFunction panicf);
-
-
-/*
-** basic stack manipulation
-*/
-LUA_API int   (lua_gettop) (lua_State *L);
-LUA_API void  (lua_settop) (lua_State *L, int idx);
-LUA_API void  (lua_pushvalue) (lua_State *L, int idx);
-LUA_API void  (lua_remove) (lua_State *L, int idx);
-LUA_API void  (lua_insert) (lua_State *L, int idx);
-LUA_API void  (lua_replace) (lua_State *L, int idx);
-LUA_API int   (lua_checkstack) (lua_State *L, int sz);
-
-LUA_API void  (lua_xmove) (lua_State *from, lua_State *to, int n);
-
-
-/*
-** access functions (stack -> C)
-*/
-
-LUA_API int             (lua_isnumber) (lua_State *L, int idx);
-LUA_API int             (lua_isstring) (lua_State *L, int idx);
-LUA_API int             (lua_iscfunction) (lua_State *L, int idx);
-LUA_API int             (lua_isuserdata) (lua_State *L, int idx);
-LUA_API int             (lua_type) (lua_State *L, int idx);
-LUA_API const char     *(lua_typename) (lua_State *L, int tp);
-
-LUA_API int            (lua_equal) (lua_State *L, int idx1, int idx2);
-LUA_API int            (lua_rawequal) (lua_State *L, int idx1, int idx2);
-LUA_API int            (lua_lessthan) (lua_State *L, int idx1, int idx2);
-
-LUA_API lua_Number      (lua_tonumber) (lua_State *L, int idx);
-LUA_API lua_Integer     (lua_tointeger) (lua_State *L, int idx);
-LUA_API int             (lua_toboolean) (lua_State *L, int idx);
-LUA_API const char     *(lua_tolstring) (lua_State *L, int idx, size_t *len);
-LUA_API size_t          (lua_objlen) (lua_State *L, int idx);
-LUA_API lua_CFunction   (lua_tocfunction) (lua_State *L, int idx);
-LUA_API void	       *(lua_touserdata) (lua_State *L, int idx);
-LUA_API lua_State      *(lua_tothread) (lua_State *L, int idx);
-LUA_API const void     *(lua_topointer) (lua_State *L, int idx);
-
-
-/*
-** push functions (C -> stack)
-*/
-LUA_API void  (lua_pushnil) (lua_State *L);
-LUA_API void  (lua_pushnumber) (lua_State *L, lua_Number n);
-LUA_API void  (lua_pushinteger) (lua_State *L, lua_Integer n);
-LUA_API void  (lua_pushlstring) (lua_State *L, const char *s, size_t l);
-LUA_API void  (lua_pushrolstring) (lua_State *L, const char *s, size_t l);
-LUA_API void  (lua_pushstring) (lua_State *L, const char *s);
-LUA_API const char *(lua_pushvfstring) (lua_State *L, const char *fmt,
-                                                      va_list argp);
-LUA_API const char *(lua_pushfstring) (lua_State *L, const char *fmt, ...);
-LUA_API void  (lua_pushcclosure) (lua_State *L, lua_CFunction fn, int n);
-LUA_API void  (lua_pushboolean) (lua_State *L, int b);
-LUA_API void  (lua_pushlightuserdata) (lua_State *L, void *p);
-LUA_API void  (lua_pushlightfunction) (lua_State *L, void *p);
-LUA_API void  (lua_pushrotable) (lua_State *L, void *p);
-LUA_API int   (lua_pushthread) (lua_State *L);
-
-
-/*
-** get functions (Lua -> stack)
-*/
-LUA_API void  (lua_gettable) (lua_State *L, int idx);
-LUA_API void  (lua_getfield) (lua_State *L, int idx, const char *k);
-LUA_API void  (lua_rawget) (lua_State *L, int idx);
-LUA_API void  (lua_rawgeti) (lua_State *L, int idx, int n);
-LUA_API void  (lua_createtable) (lua_State *L, int narr, int nrec);
-LUA_API void *(lua_newuserdata) (lua_State *L, size_t sz);
-LUA_API int   (lua_getmetatable) (lua_State *L, int objindex);
-LUA_API void  (lua_getfenv) (lua_State *L, int idx);
-
-
-/*
-** set functions (stack -> Lua)
-*/
-LUA_API void  (lua_settable) (lua_State *L, int idx);
-LUA_API void  (lua_setfield) (lua_State *L, int idx, const char *k);
-LUA_API void  (lua_rawset) (lua_State *L, int idx);
-LUA_API void  (lua_rawseti) (lua_State *L, int idx, int n);
-LUA_API int   (lua_setmetatable) (lua_State *L, int objindex);
-LUA_API int   (lua_setfenv) (lua_State *L, int idx);
-
-
-/*
-** `load' and `call' functions (load and run Lua code)
-*/
-LUA_API void  (lua_call) (lua_State *L, int nargs, int nresults);
-LUA_API int   (lua_pcall) (lua_State *L, int nargs, int nresults, int errfunc);
-LUA_API int   (lua_cpcall) (lua_State *L, lua_CFunction func, void *ud);
-LUA_API int   (lua_load) (lua_State *L, lua_Reader reader, void *dt,
-                                        const char *chunkname);
-
-LUA_API int (lua_dump) (lua_State *L, lua_Writer writer, void *data);
-
-
-/*
-** coroutine functions
-*/
-LUA_API int  (lua_yield) (lua_State *L, int nresults);
-LUA_API int  (lua_resume) (lua_State *L, int narg);
-LUA_API int  (lua_status) (lua_State *L);
-
-/*
-** garbage-collection function and options
-*/
-
-#define LUA_GCSTOP		0
-#define LUA_GCRESTART		1
-#define LUA_GCCOLLECT		2
-#define LUA_GCCOUNT		3
-#define LUA_GCCOUNTB		4
-#define LUA_GCSTEP		5
-#define LUA_GCSETPAUSE		6
-#define LUA_GCSETSTEPMUL	7
-#define LUA_GCSETMEMLIMIT	8
-#define LUA_GCGETMEMLIMIT	9
-
-LUA_API int (lua_gc) (lua_State *L, int what, int data);
-
-
-/*
-** miscellaneous functions
-*/
-
-LUA_API int   (lua_error) (lua_State *L);
-
-LUA_API int   (lua_next) (lua_State *L, int idx);
-
-LUA_API void  (lua_concat) (lua_State *L, int n);
-
-LUA_API lua_Alloc (lua_getallocf) (lua_State *L, void **ud);
-LUA_API void lua_setallocf (lua_State *L, lua_Alloc f, void *ud);
-
-
-
-/* 
-** ===============================================================
-** some useful macros
-** ===============================================================
-*/
-
-#define lua_pop(L,n)		lua_settop(L, -(n)-1)
-
-#define lua_newtable(L)		lua_createtable(L, 0, 0)
-
-#define lua_register(L,n,f) (lua_pushcfunction(L, (f)), lua_setglobal(L, (n)))
-
-#define lua_pushcfunction(L,f)	lua_pushcclosure(L, (f), 0)
-
-#define lua_strlen(L,i)		lua_objlen(L, (i))
-
-#define lua_isfunction(L,n)	(lua_type(L, (n)) == LUA_TFUNCTION)
-#define lua_islightfunction(L,n) (lua_type(L, (n)) == LUA_TLIGHTFUNCTION)
-#define lua_istable(L,n)	(lua_type(L, (n)) == LUA_TTABLE)
-#define lua_isrotable(L,n)	(lua_type(L, (n)) == LUA_TROTABLE)
-#define lua_islightuserdata(L,n)	(lua_type(L, (n)) == LUA_TLIGHTUSERDATA)
-#define lua_isnil(L,n)		(lua_type(L, (n)) == LUA_TNIL)
-#define lua_isboolean(L,n)	(lua_type(L, (n)) == LUA_TBOOLEAN)
-#define lua_isthread(L,n)	(lua_type(L, (n)) == LUA_TTHREAD)
-#define lua_isnone(L,n)		(lua_type(L, (n)) == LUA_TNONE)
-#define lua_isnoneornil(L, n)	(lua_type(L, (n)) <= 0)
-
-#define lua_pushliteral(L, s)	\
-	lua_pushlstring(L, "" s, (sizeof(s)/sizeof(char))-1)
-
-#define lua_setglobal(L,s)	lua_setfield(L, LUA_GLOBALSINDEX, (s))
-#define lua_getglobal(L,s)	lua_getfield(L, LUA_GLOBALSINDEX, (s))
-
-#define lua_tostring(L,i)	lua_tolstring(L, (i), NULL)
-
-
-
-/*
-** compatibility macros and functions
-*/
-
-// BogdanM: modified for eLua interrupt support
-//#define lua_open()	luaL_newstate()
-lua_State* lua_open(void);
-lua_State* lua_getstate(void);
-
-#define lua_getregistry(L)	lua_pushvalue(L, LUA_REGISTRYINDEX)
-
-#define lua_getgccount(L)	lua_gc(L, LUA_GCCOUNT, 0)
-
-#define lua_Chunkreader		lua_Reader
-#define lua_Chunkwriter		lua_Writer
-
-
-/* hack */
-LUA_API void lua_setlevel	(lua_State *from, lua_State *to);
-
-
-/*
-** {======================================================================
-** Debug API
-** =======================================================================
-*/
-
-
-/*
-** Event codes
-*/
-#define LUA_HOOKCALL	0
-#define LUA_HOOKRET	1
-#define LUA_HOOKLINE	2
-#define LUA_HOOKCOUNT	3
-#define LUA_HOOKTAILRET 4
-
-
-/*
-** Event masks
-*/
-#define LUA_MASKCALL	(1 << LUA_HOOKCALL)
-#define LUA_MASKRET	(1 << LUA_HOOKRET)
-#define LUA_MASKLINE	(1 << LUA_HOOKLINE)
-#define LUA_MASKCOUNT	(1 << LUA_HOOKCOUNT)
-
-typedef struct lua_Debug lua_Debug;  /* activation record */
-
-
-/* Functions to be called by the debuger in specific events */
-typedef void (*lua_Hook) (lua_State *L, lua_Debug *ar);
-
-
-LUA_API int lua_getstack (lua_State *L, int level, lua_Debug *ar);
-LUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar);
-LUA_API const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n);
-LUA_API const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n);
-LUA_API const char *lua_getupvalue (lua_State *L, int funcindex, int n);
-LUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n);
-
-LUA_API int lua_sethook (lua_State *L, lua_Hook func, int mask, int count);
-LUA_API lua_Hook lua_gethook (lua_State *L);
-LUA_API int lua_gethookmask (lua_State *L);
-LUA_API int lua_gethookcount (lua_State *L);
-
-
-struct lua_Debug {
-  int event;
-  const char *name;	/* (n) */
-  const char *namewhat;	/* (n) `global', `local', `field', `method' */
-  const char *what;	/* (S) `Lua', `C', `main', `tail' */
-  const char *source;	/* (S) */
-  int currentline;	/* (l) */
-  int nups;		/* (u) number of upvalues */
-  int linedefined;	/* (S) */
-  int lastlinedefined;	/* (S) */
-  char short_src[LUA_IDSIZE]; /* (S) */
-  /* private part */
-  int i_ci;  /* active function */
-};
-
-/* }====================================================================== */
-
-int lua_main( int argc, char **argv );
-
-/******************************************************************************
-* Copyright (C) 1994-2008 Lua.org, PUC-Rio.  All rights reserved.
-*
-* Permission is hereby granted, free of charge, to any person obtaining
-* a copy of this software and associated documentation files (the
-* "Software"), to deal in the Software without restriction, including
-* without limitation the rights to use, copy, modify, merge, publish,
-* distribute, sublicense, and/or sell copies of the Software, and to
-* permit persons to whom the Software is furnished to do so, subject to
-* the following conditions:
-*
-* The above copyright notice and this permission notice shall be
-* included in all copies or substantial portions of the Software.
-*
-* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
-* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
-* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
-* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
-* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-******************************************************************************/
-
-
-#endif


[38/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/hw/cmsis-core/src/ext/core_cm4_simd.h
----------------------------------------------------------------------
diff --git a/hw/cmsis-core/src/ext/core_cm4_simd.h b/hw/cmsis-core/src/ext/core_cm4_simd.h
new file mode 100644
index 0000000..83db95b
--- /dev/null
+++ b/hw/cmsis-core/src/ext/core_cm4_simd.h
@@ -0,0 +1,673 @@
+/**************************************************************************//**
+ * @file     core_cm4_simd.h
+ * @brief    CMSIS Cortex-M4 SIMD Header File
+ * @version  V3.20
+ * @date     25. February 2013
+ *
+ * @note
+ *
+ ******************************************************************************/
+/* Copyright (c) 2009 - 2013 ARM LIMITED
+
+   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 ARM 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 COPYRIGHT HOLDERS AND 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.
+   ---------------------------------------------------------------------------*/
+
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+#ifndef __CORE_CM4_SIMD_H
+#define __CORE_CM4_SIMD_H
+
+
+/*******************************************************************************
+ *                Hardware Abstraction Layer
+ ******************************************************************************/
+
+
+/* ###################  Compiler specific Intrinsics  ########################### */
+/** \defgroup CMSIS_SIMD_intrinsics CMSIS SIMD Intrinsics
+  Access to dedicated SIMD instructions
+  @{
+*/
+
+#if   defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/
+/* ARM armcc specific functions */
+
+/*------ CM4 SIMD Intrinsics -----------------------------------------------------*/
+#define __SADD8                           __sadd8
+#define __QADD8                           __qadd8
+#define __SHADD8                          __shadd8
+#define __UADD8                           __uadd8
+#define __UQADD8                          __uqadd8
+#define __UHADD8                          __uhadd8
+#define __SSUB8                           __ssub8
+#define __QSUB8                           __qsub8
+#define __SHSUB8                          __shsub8
+#define __USUB8                           __usub8
+#define __UQSUB8                          __uqsub8
+#define __UHSUB8                          __uhsub8
+#define __SADD16                          __sadd16
+#define __QADD16                          __qadd16
+#define __SHADD16                         __shadd16
+#define __UADD16                          __uadd16
+#define __UQADD16                         __uqadd16
+#define __UHADD16                         __uhadd16
+#define __SSUB16                          __ssub16
+#define __QSUB16                          __qsub16
+#define __SHSUB16                         __shsub16
+#define __USUB16                          __usub16
+#define __UQSUB16                         __uqsub16
+#define __UHSUB16                         __uhsub16
+#define __SASX                            __sasx
+#define __QASX                            __qasx
+#define __SHASX                           __shasx
+#define __UASX                            __uasx
+#define __UQASX                           __uqasx
+#define __UHASX                           __uhasx
+#define __SSAX                            __ssax
+#define __QSAX                            __qsax
+#define __SHSAX                           __shsax
+#define __USAX                            __usax
+#define __UQSAX                           __uqsax
+#define __UHSAX                           __uhsax
+#define __USAD8                           __usad8
+#define __USADA8                          __usada8
+#define __SSAT16                          __ssat16
+#define __USAT16                          __usat16
+#define __UXTB16                          __uxtb16
+#define __UXTAB16                         __uxtab16
+#define __SXTB16                          __sxtb16
+#define __SXTAB16                         __sxtab16
+#define __SMUAD                           __smuad
+#define __SMUADX                          __smuadx
+#define __SMLAD                           __smlad
+#define __SMLADX                          __smladx
+#define __SMLALD                          __smlald
+#define __SMLALDX                         __smlaldx
+#define __SMUSD                           __smusd
+#define __SMUSDX                          __smusdx
+#define __SMLSD                           __smlsd
+#define __SMLSDX                          __smlsdx
+#define __SMLSLD                          __smlsld
+#define __SMLSLDX                         __smlsldx
+#define __SEL                             __sel
+#define __QADD                            __qadd
+#define __QSUB                            __qsub
+
+#define __PKHBT(ARG1,ARG2,ARG3)          ( ((((uint32_t)(ARG1))          ) & 0x0000FFFFUL) |  \
+                                           ((((uint32_t)(ARG2)) << (ARG3)) & 0xFFFF0000UL)  )
+
+#define __PKHTB(ARG1,ARG2,ARG3)          ( ((((uint32_t)(ARG1))          ) & 0xFFFF0000UL) |  \
+                                           ((((uint32_t)(ARG2)) >> (ARG3)) & 0x0000FFFFUL)  )
+
+#define __SMMLA(ARG1,ARG2,ARG3)          ( (int32_t)((((int64_t)(ARG1) * (ARG2)) + \
+                                                      ((int64_t)(ARG3) << 32)      ) >> 32))
+
+/*-- End CM4 SIMD Intrinsics -----------------------------------------------------*/
+
+
+
+#elif defined ( __ICCARM__ ) /*------------------ ICC Compiler -------------------*/
+/* IAR iccarm specific functions */
+
+/*------ CM4 SIMD Intrinsics -----------------------------------------------------*/
+#include <cmsis_iar.h>
+
+/*-- End CM4 SIMD Intrinsics -----------------------------------------------------*/
+
+
+
+#elif defined ( __TMS470__ ) /*---------------- TI CCS Compiler ------------------*/
+/* TI CCS specific functions */
+
+/*------ CM4 SIMD Intrinsics -----------------------------------------------------*/
+#include <cmsis_ccs.h>
+
+/*-- End CM4 SIMD Intrinsics -----------------------------------------------------*/
+
+
+
+#elif defined ( __GNUC__ ) /*------------------ GNU Compiler ---------------------*/
+/* GNU gcc specific functions */
+
+/*------ CM4 SIMD Intrinsics -----------------------------------------------------*/
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SADD8(uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("sadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD8(uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("qadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHADD8(uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("shadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UADD8(uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("uadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQADD8(uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("uqadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHADD8(uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("uhadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSUB8(uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("ssub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB8(uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("qsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSUB8(uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("shsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USUB8(uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("usub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSUB8(uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("uqsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSUB8(uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("uhsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SADD16(uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("sadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD16(uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("qadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHADD16(uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("shadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UADD16(uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("uadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQADD16(uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("uqadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHADD16(uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("uhadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSUB16(uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("ssub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB16(uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("qsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSUB16(uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("shsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USUB16(uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("usub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSUB16(uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("uqsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSUB16(uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("uhsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SASX(uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("sasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QASX(uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("qasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHASX(uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("shasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UASX(uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("uasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQASX(uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("uqasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHASX(uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("uhasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSAX(uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("ssax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSAX(uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("qsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSAX(uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("shsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USAX(uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("usax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSAX(uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("uqsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSAX(uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("uhsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USAD8(uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("usad8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USADA8(uint32_t op1, uint32_t op2, uint32_t op3)
+{
+  uint32_t result;
+
+  __ASM volatile ("usada8 %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) );
+  return(result);
+}
+
+#define __SSAT16(ARG1,ARG2) \
+({                          \
+  uint32_t __RES, __ARG1 = (ARG1); \
+  __ASM ("ssat16 %0, %1, %2" : "=r" (__RES) :  "I" (ARG2), "r" (__ARG1) ); \
+  __RES; \
+ })
+
+#define __USAT16(ARG1,ARG2) \
+({                          \
+  uint32_t __RES, __ARG1 = (ARG1); \
+  __ASM ("usat16 %0, %1, %2" : "=r" (__RES) :  "I" (ARG2), "r" (__ARG1) ); \
+  __RES; \
+ })
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UXTB16(uint32_t op1)
+{
+  uint32_t result;
+
+  __ASM volatile ("uxtb16 %0, %1" : "=r" (result) : "r" (op1));
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UXTAB16(uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("uxtab16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SXTB16(uint32_t op1)
+{
+  uint32_t result;
+
+  __ASM volatile ("sxtb16 %0, %1" : "=r" (result) : "r" (op1));
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SXTAB16(uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("sxtab16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUAD  (uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("smuad %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUADX (uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("smuadx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLAD (uint32_t op1, uint32_t op2, uint32_t op3)
+{
+  uint32_t result;
+
+  __ASM volatile ("smlad %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) );
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLADX (uint32_t op1, uint32_t op2, uint32_t op3)
+{
+  uint32_t result;
+
+  __ASM volatile ("smladx %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) );
+  return(result);
+}
+
+#define __SMLALD(ARG1,ARG2,ARG3) \
+({ \
+  uint32_t __ARG1 = (ARG1), __ARG2 = (ARG2), __ARG3_H = (uint32_t)((uint64_t)(ARG3) >> 32), __ARG3_L = (uint32_t)((uint64_t)(ARG3) & 0xFFFFFFFFUL); \
+  __ASM volatile ("smlald %0, %1, %2, %3" : "=r" (__ARG3_L), "=r" (__ARG3_H) : "r" (__ARG1), "r" (__ARG2), "0" (__ARG3_L), "1" (__ARG3_H) ); \
+  (uint64_t)(((uint64_t)__ARG3_H << 32) | __ARG3_L); \
+ })
+
+#define __SMLALDX(ARG1,ARG2,ARG3) \
+({ \
+  uint32_t __ARG1 = (ARG1), __ARG2 = (ARG2), __ARG3_H = (uint32_t)((uint64_t)(ARG3) >> 32), __ARG3_L = (uint32_t)((uint64_t)(ARG3) & 0xFFFFFFFFUL); \
+  __ASM volatile ("smlaldx %0, %1, %2, %3" : "=r" (__ARG3_L), "=r" (__ARG3_H) : "r" (__ARG1), "r" (__ARG2), "0" (__ARG3_L), "1" (__ARG3_H) ); \
+  (uint64_t)(((uint64_t)__ARG3_H << 32) | __ARG3_L); \
+ })
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUSD  (uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("smusd %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUSDX (uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("smusdx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLSD (uint32_t op1, uint32_t op2, uint32_t op3)
+{
+  uint32_t result;
+
+  __ASM volatile ("smlsd %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) );
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLSDX (uint32_t op1, uint32_t op2, uint32_t op3)
+{
+  uint32_t result;
+
+  __ASM volatile ("smlsdx %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) );
+  return(result);
+}
+
+#define __SMLSLD(ARG1,ARG2,ARG3) \
+({ \
+  uint32_t __ARG1 = (ARG1), __ARG2 = (ARG2), __ARG3_H = (uint32_t)((ARG3) >> 32), __ARG3_L = (uint32_t)((ARG3) & 0xFFFFFFFFUL); \
+  __ASM volatile ("smlsld %0, %1, %2, %3" : "=r" (__ARG3_L), "=r" (__ARG3_H) : "r" (__ARG1), "r" (__ARG2), "0" (__ARG3_L), "1" (__ARG3_H) ); \
+  (uint64_t)(((uint64_t)__ARG3_H << 32) | __ARG3_L); \
+ })
+
+#define __SMLSLDX(ARG1,ARG2,ARG3) \
+({ \
+  uint32_t __ARG1 = (ARG1), __ARG2 = (ARG2), __ARG3_H = (uint32_t)((ARG3) >> 32), __ARG3_L = (uint32_t)((ARG3) & 0xFFFFFFFFUL); \
+  __ASM volatile ("smlsldx %0, %1, %2, %3" : "=r" (__ARG3_L), "=r" (__ARG3_H) : "r" (__ARG1), "r" (__ARG2), "0" (__ARG3_L), "1" (__ARG3_H) ); \
+  (uint64_t)(((uint64_t)__ARG3_H << 32) | __ARG3_L); \
+ })
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SEL  (uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("sel %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD(uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("qadd %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB(uint32_t op1, uint32_t op2)
+{
+  uint32_t result;
+
+  __ASM volatile ("qsub %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
+  return(result);
+}
+
+#define __PKHBT(ARG1,ARG2,ARG3) \
+({                          \
+  uint32_t __RES, __ARG1 = (ARG1), __ARG2 = (ARG2); \
+  __ASM ("pkhbt %0, %1, %2, lsl %3" : "=r" (__RES) :  "r" (__ARG1), "r" (__ARG2), "I" (ARG3)  ); \
+  __RES; \
+ })
+
+#define __PKHTB(ARG1,ARG2,ARG3) \
+({                          \
+  uint32_t __RES, __ARG1 = (ARG1), __ARG2 = (ARG2); \
+  if (ARG3 == 0) \
+    __ASM ("pkhtb %0, %1, %2" : "=r" (__RES) :  "r" (__ARG1), "r" (__ARG2)  ); \
+  else \
+    __ASM ("pkhtb %0, %1, %2, asr %3" : "=r" (__RES) :  "r" (__ARG1), "r" (__ARG2), "I" (ARG3)  ); \
+  __RES; \
+ })
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMMLA (int32_t op1, int32_t op2, int32_t op3)
+{
+ int32_t result;
+
+ __ASM volatile ("smmla %0, %1, %2, %3" : "=r" (result): "r"  (op1), "r" (op2), "r" (op3) );
+ return(result);
+}
+
+/*-- End CM4 SIMD Intrinsics -----------------------------------------------------*/
+
+
+
+#elif defined ( __TASKING__ ) /*------------------ TASKING Compiler --------------*/
+/* TASKING carm specific functions */
+
+
+/*------ CM4 SIMD Intrinsics -----------------------------------------------------*/
+/* not yet supported */
+/*-- End CM4 SIMD Intrinsics -----------------------------------------------------*/
+
+
+#endif
+
+/*@} end of group CMSIS_SIMD_intrinsics */
+
+
+#endif /* __CORE_CM4_SIMD_H */
+
+#ifdef __cplusplus
+}
+#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/hw/cmsis-core/src/ext/core_cmFunc.h
----------------------------------------------------------------------
diff --git a/hw/cmsis-core/src/ext/core_cmFunc.h b/hw/cmsis-core/src/ext/core_cmFunc.h
new file mode 100644
index 0000000..0a18faf
--- /dev/null
+++ b/hw/cmsis-core/src/ext/core_cmFunc.h
@@ -0,0 +1,636 @@
+/**************************************************************************//**
+ * @file     core_cmFunc.h
+ * @brief    CMSIS Cortex-M Core Function Access Header File
+ * @version  V3.20
+ * @date     25. February 2013
+ *
+ * @note
+ *
+ ******************************************************************************/
+/* Copyright (c) 2009 - 2013 ARM LIMITED
+
+   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 ARM 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 COPYRIGHT HOLDERS AND 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.
+   ---------------------------------------------------------------------------*/
+
+
+#ifndef __CORE_CMFUNC_H
+#define __CORE_CMFUNC_H
+
+
+/* ###########################  Core Function Access  ########################### */
+/** \ingroup  CMSIS_Core_FunctionInterface
+    \defgroup CMSIS_Core_RegAccFunctions CMSIS Core Register Access Functions
+  @{
+ */
+
+#if   defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/
+/* ARM armcc specific functions */
+
+#if (__ARMCC_VERSION < 400677)
+  #error "Please use ARM Compiler Toolchain V4.0.677 or later!"
+#endif
+
+/* intrinsic void __enable_irq();     */
+/* intrinsic void __disable_irq();    */
+
+/** \brief  Get Control Register
+
+    This function returns the content of the Control Register.
+
+    \return               Control Register value
+ */
+__STATIC_INLINE uint32_t __get_CONTROL(void)
+{
+  register uint32_t __regControl         __ASM("control");
+  return(__regControl);
+}
+
+
+/** \brief  Set Control Register
+
+    This function writes the given value to the Control Register.
+
+    \param [in]    control  Control Register value to set
+ */
+__STATIC_INLINE void __set_CONTROL(uint32_t control)
+{
+  register uint32_t __regControl         __ASM("control");
+  __regControl = control;
+}
+
+
+/** \brief  Get IPSR Register
+
+    This function returns the content of the IPSR Register.
+
+    \return               IPSR Register value
+ */
+__STATIC_INLINE uint32_t __get_IPSR(void)
+{
+  register uint32_t __regIPSR          __ASM("ipsr");
+  return(__regIPSR);
+}
+
+
+/** \brief  Get APSR Register
+
+    This function returns the content of the APSR Register.
+
+    \return               APSR Register value
+ */
+__STATIC_INLINE uint32_t __get_APSR(void)
+{
+  register uint32_t __regAPSR          __ASM("apsr");
+  return(__regAPSR);
+}
+
+
+/** \brief  Get xPSR Register
+
+    This function returns the content of the xPSR Register.
+
+    \return               xPSR Register value
+ */
+__STATIC_INLINE uint32_t __get_xPSR(void)
+{
+  register uint32_t __regXPSR          __ASM("xpsr");
+  return(__regXPSR);
+}
+
+
+/** \brief  Get Process Stack Pointer
+
+    This function returns the current value of the Process Stack Pointer (PSP).
+
+    \return               PSP Register value
+ */
+__STATIC_INLINE uint32_t __get_PSP(void)
+{
+  register uint32_t __regProcessStackPointer  __ASM("psp");
+  return(__regProcessStackPointer);
+}
+
+
+/** \brief  Set Process Stack Pointer
+
+    This function assigns the given value to the Process Stack Pointer (PSP).
+
+    \param [in]    topOfProcStack  Process Stack Pointer value to set
+ */
+__STATIC_INLINE void __set_PSP(uint32_t topOfProcStack)
+{
+  register uint32_t __regProcessStackPointer  __ASM("psp");
+  __regProcessStackPointer = topOfProcStack;
+}
+
+
+/** \brief  Get Main Stack Pointer
+
+    This function returns the current value of the Main Stack Pointer (MSP).
+
+    \return               MSP Register value
+ */
+__STATIC_INLINE uint32_t __get_MSP(void)
+{
+  register uint32_t __regMainStackPointer     __ASM("msp");
+  return(__regMainStackPointer);
+}
+
+
+/** \brief  Set Main Stack Pointer
+
+    This function assigns the given value to the Main Stack Pointer (MSP).
+
+    \param [in]    topOfMainStack  Main Stack Pointer value to set
+ */
+__STATIC_INLINE void __set_MSP(uint32_t topOfMainStack)
+{
+  register uint32_t __regMainStackPointer     __ASM("msp");
+  __regMainStackPointer = topOfMainStack;
+}
+
+
+/** \brief  Get Priority Mask
+
+    This function returns the current state of the priority mask bit from the Priority Mask Register.
+
+    \return               Priority Mask value
+ */
+__STATIC_INLINE uint32_t __get_PRIMASK(void)
+{
+  register uint32_t __regPriMask         __ASM("primask");
+  return(__regPriMask);
+}
+
+
+/** \brief  Set Priority Mask
+
+    This function assigns the given value to the Priority Mask Register.
+
+    \param [in]    priMask  Priority Mask
+ */
+__STATIC_INLINE void __set_PRIMASK(uint32_t priMask)
+{
+  register uint32_t __regPriMask         __ASM("primask");
+  __regPriMask = (priMask);
+}
+
+
+#if       (__CORTEX_M >= 0x03)
+
+/** \brief  Enable FIQ
+
+    This function enables FIQ interrupts by clearing the F-bit in the CPSR.
+    Can only be executed in Privileged modes.
+ */
+#define __enable_fault_irq                __enable_fiq
+
+
+/** \brief  Disable FIQ
+
+    This function disables FIQ interrupts by setting the F-bit in the CPSR.
+    Can only be executed in Privileged modes.
+ */
+#define __disable_fault_irq               __disable_fiq
+
+
+/** \brief  Get Base Priority
+
+    This function returns the current value of the Base Priority register.
+
+    \return               Base Priority register value
+ */
+__STATIC_INLINE uint32_t  __get_BASEPRI(void)
+{
+  register uint32_t __regBasePri         __ASM("basepri");
+  return(__regBasePri);
+}
+
+
+/** \brief  Set Base Priority
+
+    This function assigns the given value to the Base Priority register.
+
+    \param [in]    basePri  Base Priority value to set
+ */
+__STATIC_INLINE void __set_BASEPRI(uint32_t basePri)
+{
+  register uint32_t __regBasePri         __ASM("basepri");
+  __regBasePri = (basePri & 0xff);
+}
+
+
+/** \brief  Get Fault Mask
+
+    This function returns the current value of the Fault Mask register.
+
+    \return               Fault Mask register value
+ */
+__STATIC_INLINE uint32_t __get_FAULTMASK(void)
+{
+  register uint32_t __regFaultMask       __ASM("faultmask");
+  return(__regFaultMask);
+}
+
+
+/** \brief  Set Fault Mask
+
+    This function assigns the given value to the Fault Mask register.
+
+    \param [in]    faultMask  Fault Mask value to set
+ */
+__STATIC_INLINE void __set_FAULTMASK(uint32_t faultMask)
+{
+  register uint32_t __regFaultMask       __ASM("faultmask");
+  __regFaultMask = (faultMask & (uint32_t)1);
+}
+
+#endif /* (__CORTEX_M >= 0x03) */
+
+
+#if       (__CORTEX_M == 0x04)
+
+/** \brief  Get FPSCR
+
+    This function returns the current value of the Floating Point Status/Control register.
+
+    \return               Floating Point Status/Control register value
+ */
+__STATIC_INLINE uint32_t __get_FPSCR(void)
+{
+#if (__FPU_PRESENT == 1) && (__FPU_USED == 1)
+  register uint32_t __regfpscr         __ASM("fpscr");
+  return(__regfpscr);
+#else
+   return(0);
+#endif
+}
+
+
+/** \brief  Set FPSCR
+
+    This function assigns the given value to the Floating Point Status/Control register.
+
+    \param [in]    fpscr  Floating Point Status/Control value to set
+ */
+__STATIC_INLINE void __set_FPSCR(uint32_t fpscr)
+{
+#if (__FPU_PRESENT == 1) && (__FPU_USED == 1)
+  register uint32_t __regfpscr         __ASM("fpscr");
+  __regfpscr = (fpscr);
+#endif
+}
+
+#endif /* (__CORTEX_M == 0x04) */
+
+
+#elif defined ( __ICCARM__ ) /*------------------ ICC Compiler -------------------*/
+/* IAR iccarm specific functions */
+
+#include <cmsis_iar.h>
+
+
+#elif defined ( __TMS470__ ) /*---------------- TI CCS Compiler ------------------*/
+/* TI CCS specific functions */
+
+#include <cmsis_ccs.h>
+
+
+#elif defined ( __GNUC__ ) /*------------------ GNU Compiler ---------------------*/
+/* GNU gcc specific functions */
+
+/** \brief  Enable IRQ Interrupts
+
+  This function enables IRQ interrupts by clearing the I-bit in the CPSR.
+  Can only be executed in Privileged modes.
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_irq(void)
+{
+  __ASM volatile ("cpsie i" : : : "memory");
+}
+
+
+/** \brief  Disable IRQ Interrupts
+
+  This function disables IRQ interrupts by setting the I-bit in the CPSR.
+  Can only be executed in Privileged modes.
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_irq(void)
+{
+  __ASM volatile ("cpsid i" : : : "memory");
+}
+
+
+/** \brief  Get Control Register
+
+    This function returns the content of the Control Register.
+
+    \return               Control Register value
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_CONTROL(void)
+{
+  uint32_t result;
+
+  __ASM volatile ("MRS %0, control" : "=r" (result) );
+  return(result);
+}
+
+
+/** \brief  Set Control Register
+
+    This function writes the given value to the Control Register.
+
+    \param [in]    control  Control Register value to set
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_CONTROL(uint32_t control)
+{
+  __ASM volatile ("MSR control, %0" : : "r" (control) : "memory");
+}
+
+
+/** \brief  Get IPSR Register
+
+    This function returns the content of the IPSR Register.
+
+    \return               IPSR Register value
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_IPSR(void)
+{
+  uint32_t result;
+
+  __ASM volatile ("MRS %0, ipsr" : "=r" (result) );
+  return(result);
+}
+
+
+/** \brief  Get APSR Register
+
+    This function returns the content of the APSR Register.
+
+    \return               APSR Register value
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_APSR(void)
+{
+  uint32_t result;
+
+  __ASM volatile ("MRS %0, apsr" : "=r" (result) );
+  return(result);
+}
+
+
+/** \brief  Get xPSR Register
+
+    This function returns the content of the xPSR Register.
+
+    \return               xPSR Register value
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_xPSR(void)
+{
+  uint32_t result;
+
+  __ASM volatile ("MRS %0, xpsr" : "=r" (result) );
+  return(result);
+}
+
+
+/** \brief  Get Process Stack Pointer
+
+    This function returns the current value of the Process Stack Pointer (PSP).
+
+    \return               PSP Register value
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_PSP(void)
+{
+  register uint32_t result;
+
+  __ASM volatile ("MRS %0, psp\n"  : "=r" (result) );
+  return(result);
+}
+
+
+/** \brief  Set Process Stack Pointer
+
+    This function assigns the given value to the Process Stack Pointer (PSP).
+
+    \param [in]    topOfProcStack  Process Stack Pointer value to set
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_PSP(uint32_t topOfProcStack)
+{
+  __ASM volatile ("MSR psp, %0\n" : : "r" (topOfProcStack) : "sp");
+}
+
+
+/** \brief  Get Main Stack Pointer
+
+    This function returns the current value of the Main Stack Pointer (MSP).
+
+    \return               MSP Register value
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_MSP(void)
+{
+  register uint32_t result;
+
+  __ASM volatile ("MRS %0, msp\n" : "=r" (result) );
+  return(result);
+}
+
+
+/** \brief  Set Main Stack Pointer
+
+    This function assigns the given value to the Main Stack Pointer (MSP).
+
+    \param [in]    topOfMainStack  Main Stack Pointer value to set
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_MSP(uint32_t topOfMainStack)
+{
+  __ASM volatile ("MSR msp, %0\n" : : "r" (topOfMainStack) : "sp");
+}
+
+
+/** \brief  Get Priority Mask
+
+    This function returns the current state of the priority mask bit from the Priority Mask Register.
+
+    \return               Priority Mask value
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_PRIMASK(void)
+{
+  uint32_t result;
+
+  __ASM volatile ("MRS %0, primask" : "=r" (result) );
+  return(result);
+}
+
+
+/** \brief  Set Priority Mask
+
+    This function assigns the given value to the Priority Mask Register.
+
+    \param [in]    priMask  Priority Mask
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_PRIMASK(uint32_t priMask)
+{
+  __ASM volatile ("MSR primask, %0" : : "r" (priMask) : "memory");
+}
+
+
+#if       (__CORTEX_M >= 0x03)
+
+/** \brief  Enable FIQ
+
+    This function enables FIQ interrupts by clearing the F-bit in the CPSR.
+    Can only be executed in Privileged modes.
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_fault_irq(void)
+{
+  __ASM volatile ("cpsie f" : : : "memory");
+}
+
+
+/** \brief  Disable FIQ
+
+    This function disables FIQ interrupts by setting the F-bit in the CPSR.
+    Can only be executed in Privileged modes.
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_fault_irq(void)
+{
+  __ASM volatile ("cpsid f" : : : "memory");
+}
+
+
+/** \brief  Get Base Priority
+
+    This function returns the current value of the Base Priority register.
+
+    \return               Base Priority register value
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_BASEPRI(void)
+{
+  uint32_t result;
+
+  __ASM volatile ("MRS %0, basepri_max" : "=r" (result) );
+  return(result);
+}
+
+
+/** \brief  Set Base Priority
+
+    This function assigns the given value to the Base Priority register.
+
+    \param [in]    basePri  Base Priority value to set
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_BASEPRI(uint32_t value)
+{
+  __ASM volatile ("MSR basepri, %0" : : "r" (value) : "memory");
+}
+
+
+/** \brief  Get Fault Mask
+
+    This function returns the current value of the Fault Mask register.
+
+    \return               Fault Mask register value
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_FAULTMASK(void)
+{
+  uint32_t result;
+
+  __ASM volatile ("MRS %0, faultmask" : "=r" (result) );
+  return(result);
+}
+
+
+/** \brief  Set Fault Mask
+
+    This function assigns the given value to the Fault Mask register.
+
+    \param [in]    faultMask  Fault Mask value to set
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_FAULTMASK(uint32_t faultMask)
+{
+  __ASM volatile ("MSR faultmask, %0" : : "r" (faultMask) : "memory");
+}
+
+#endif /* (__CORTEX_M >= 0x03) */
+
+
+#if       (__CORTEX_M == 0x04)
+
+/** \brief  Get FPSCR
+
+    This function returns the current value of the Floating Point Status/Control register.
+
+    \return               Floating Point Status/Control register value
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_FPSCR(void)
+{
+#if (__FPU_PRESENT == 1) && (__FPU_USED == 1)
+  uint32_t result;
+
+  /* Empty asm statement works as a scheduling barrier */
+  __ASM volatile ("");
+  __ASM volatile ("VMRS %0, fpscr" : "=r" (result) );
+  __ASM volatile ("");
+  return(result);
+#else
+   return(0);
+#endif
+}
+
+
+/** \brief  Set FPSCR
+
+    This function assigns the given value to the Floating Point Status/Control register.
+
+    \param [in]    fpscr  Floating Point Status/Control value to set
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_FPSCR(uint32_t fpscr)
+{
+#if (__FPU_PRESENT == 1) && (__FPU_USED == 1)
+  /* Empty asm statement works as a scheduling barrier */
+  __ASM volatile ("");
+  __ASM volatile ("VMSR fpscr, %0" : : "r" (fpscr) : "vfpcc");
+  __ASM volatile ("");
+#endif
+}
+
+#endif /* (__CORTEX_M == 0x04) */
+
+
+#elif defined ( __TASKING__ ) /*------------------ TASKING Compiler --------------*/
+/* TASKING carm specific functions */
+
+/*
+ * The CMSIS functions have been implemented as intrinsics in the compiler.
+ * Please use "carm -?i" to get an up to date list of all instrinsics,
+ * Including the CMSIS ones.
+ */
+
+#endif
+
+/*@} end of CMSIS_Core_RegAccFunctions */
+
+
+#endif /* __CORE_CMFUNC_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/hw/cmsis-core/src/ext/core_cmInstr.h
----------------------------------------------------------------------
diff --git a/hw/cmsis-core/src/ext/core_cmInstr.h b/hw/cmsis-core/src/ext/core_cmInstr.h
new file mode 100644
index 0000000..d213f0e
--- /dev/null
+++ b/hw/cmsis-core/src/ext/core_cmInstr.h
@@ -0,0 +1,688 @@
+/**************************************************************************//**
+ * @file     core_cmInstr.h
+ * @brief    CMSIS Cortex-M Core Instruction Access Header File
+ * @version  V3.20
+ * @date     05. March 2013
+ *
+ * @note
+ *
+ ******************************************************************************/
+/* Copyright (c) 2009 - 2013 ARM LIMITED
+
+   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 ARM 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 COPYRIGHT HOLDERS AND 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.
+   ---------------------------------------------------------------------------*/
+
+
+#ifndef __CORE_CMINSTR_H
+#define __CORE_CMINSTR_H
+
+
+/* ##########################  Core Instruction Access  ######################### */
+/** \defgroup CMSIS_Core_InstructionInterface CMSIS Core Instruction Interface
+  Access to dedicated instructions
+  @{
+*/
+
+#if   defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/
+/* ARM armcc specific functions */
+
+#if (__ARMCC_VERSION < 400677)
+  #error "Please use ARM Compiler Toolchain V4.0.677 or later!"
+#endif
+
+
+/** \brief  No Operation
+
+    No Operation does nothing. This instruction can be used for code alignment purposes.
+ */
+#define __NOP                             __nop
+
+
+/** \brief  Wait For Interrupt
+
+    Wait For Interrupt is a hint instruction that suspends execution
+    until one of a number of events occurs.
+ */
+#define __WFI                             __wfi
+
+
+/** \brief  Wait For Event
+
+    Wait For Event is a hint instruction that permits the processor to enter
+    a low-power state until one of a number of events occurs.
+ */
+#define __WFE                             __wfe
+
+
+/** \brief  Send Event
+
+    Send Event is a hint instruction. It causes an event to be signaled to the CPU.
+ */
+#define __SEV                             __sev
+
+
+/** \brief  Instruction Synchronization Barrier
+
+    Instruction Synchronization Barrier flushes the pipeline in the processor,
+    so that all instructions following the ISB are fetched from cache or
+    memory, after the instruction has been completed.
+ */
+#define __ISB()                           __isb(0xF)
+
+
+/** \brief  Data Synchronization Barrier
+
+    This function acts as a special kind of Data Memory Barrier.
+    It completes when all explicit memory accesses before this instruction complete.
+ */
+#define __DSB()                           __dsb(0xF)
+
+
+/** \brief  Data Memory Barrier
+
+    This function ensures the apparent order of the explicit memory operations before
+    and after the instruction, without ensuring their completion.
+ */
+#define __DMB()                           __dmb(0xF)
+
+
+/** \brief  Reverse byte order (32 bit)
+
+    This function reverses the byte order in integer value.
+
+    \param [in]    value  Value to reverse
+    \return               Reversed value
+ */
+#define __REV                             __rev
+
+
+/** \brief  Reverse byte order (16 bit)
+
+    This function reverses the byte order in two unsigned short values.
+
+    \param [in]    value  Value to reverse
+    \return               Reversed value
+ */
+#ifndef __NO_EMBEDDED_ASM
+__attribute__((section(".rev16_text"))) __STATIC_INLINE __ASM uint32_t __REV16(uint32_t value)
+{
+  rev16 r0, r0
+  bx lr
+}
+#endif
+
+/** \brief  Reverse byte order in signed short value
+
+    This function reverses the byte order in a signed short value with sign extension to integer.
+
+    \param [in]    value  Value to reverse
+    \return               Reversed value
+ */
+#ifndef __NO_EMBEDDED_ASM
+__attribute__((section(".revsh_text"))) __STATIC_INLINE __ASM int32_t __REVSH(int32_t value)
+{
+  revsh r0, r0
+  bx lr
+}
+#endif
+
+
+/** \brief  Rotate Right in unsigned value (32 bit)
+
+    This function Rotate Right (immediate) provides the value of the contents of a register rotated by a variable number of bits.
+
+    \param [in]    value  Value to rotate
+    \param [in]    value  Number of Bits to rotate
+    \return               Rotated value
+ */
+#define __ROR                             __ror
+
+
+/** \brief  Breakpoint
+
+    This function causes the processor to enter Debug state.
+    Debug tools can use this to investigate system state when the instruction at a particular address is reached.
+
+    \param [in]    value  is ignored by the processor.
+                   If required, a debugger can use it to store additional information about the breakpoint.
+ */
+#define __BKPT(value)                       __breakpoint(value)
+
+
+#if       (__CORTEX_M >= 0x03)
+
+/** \brief  Reverse bit order of value
+
+    This function reverses the bit order of the given value.
+
+    \param [in]    value  Value to reverse
+    \return               Reversed value
+ */
+#define __RBIT                            __rbit
+
+
+/** \brief  LDR Exclusive (8 bit)
+
+    This function performs a exclusive LDR command for 8 bit value.
+
+    \param [in]    ptr  Pointer to data
+    \return             value of type uint8_t at (*ptr)
+ */
+#define __LDREXB(ptr)                     ((uint8_t ) __ldrex(ptr))
+
+
+/** \brief  LDR Exclusive (16 bit)
+
+    This function performs a exclusive LDR command for 16 bit values.
+
+    \param [in]    ptr  Pointer to data
+    \return        value of type uint16_t at (*ptr)
+ */
+#define __LDREXH(ptr)                     ((uint16_t) __ldrex(ptr))
+
+
+/** \brief  LDR Exclusive (32 bit)
+
+    This function performs a exclusive LDR command for 32 bit values.
+
+    \param [in]    ptr  Pointer to data
+    \return        value of type uint32_t at (*ptr)
+ */
+#define __LDREXW(ptr)                     ((uint32_t ) __ldrex(ptr))
+
+
+/** \brief  STR Exclusive (8 bit)
+
+    This function performs a exclusive STR command for 8 bit values.
+
+    \param [in]  value  Value to store
+    \param [in]    ptr  Pointer to location
+    \return          0  Function succeeded
+    \return          1  Function failed
+ */
+#define __STREXB(value, ptr)              __strex(value, ptr)
+
+
+/** \brief  STR Exclusive (16 bit)
+
+    This function performs a exclusive STR command for 16 bit values.
+
+    \param [in]  value  Value to store
+    \param [in]    ptr  Pointer to location
+    \return          0  Function succeeded
+    \return          1  Function failed
+ */
+#define __STREXH(value, ptr)              __strex(value, ptr)
+
+
+/** \brief  STR Exclusive (32 bit)
+
+    This function performs a exclusive STR command for 32 bit values.
+
+    \param [in]  value  Value to store
+    \param [in]    ptr  Pointer to location
+    \return          0  Function succeeded
+    \return          1  Function failed
+ */
+#define __STREXW(value, ptr)              __strex(value, ptr)
+
+
+/** \brief  Remove the exclusive lock
+
+    This function removes the exclusive lock which is created by LDREX.
+
+ */
+#define __CLREX                           __clrex
+
+
+/** \brief  Signed Saturate
+
+    This function saturates a signed value.
+
+    \param [in]  value  Value to be saturated
+    \param [in]    sat  Bit position to saturate to (1..32)
+    \return             Saturated value
+ */
+#define __SSAT                            __ssat
+
+
+/** \brief  Unsigned Saturate
+
+    This function saturates an unsigned value.
+
+    \param [in]  value  Value to be saturated
+    \param [in]    sat  Bit position to saturate to (0..31)
+    \return             Saturated value
+ */
+#define __USAT                            __usat
+
+
+/** \brief  Count leading zeros
+
+    This function counts the number of leading zeros of a data value.
+
+    \param [in]  value  Value to count the leading zeros
+    \return             number of leading zeros in value
+ */
+#define __CLZ                             __clz
+
+#endif /* (__CORTEX_M >= 0x03) */
+
+
+
+#elif defined ( __ICCARM__ ) /*------------------ ICC Compiler -------------------*/
+/* IAR iccarm specific functions */
+
+#include <cmsis_iar.h>
+
+
+#elif defined ( __TMS470__ ) /*---------------- TI CCS Compiler ------------------*/
+/* TI CCS specific functions */
+
+#include <cmsis_ccs.h>
+
+
+#elif defined ( __GNUC__ ) /*------------------ GNU Compiler ---------------------*/
+/* GNU gcc specific functions */
+
+/* Define macros for porting to both thumb1 and thumb2.
+ * For thumb1, use low register (r0-r7), specified by constrant "l"
+ * Otherwise, use general registers, specified by constrant "r" */
+#if defined (__thumb__) && !defined (__thumb2__)
+#define __CMSIS_GCC_OUT_REG(r) "=l" (r)
+#define __CMSIS_GCC_USE_REG(r) "l" (r)
+#else
+#define __CMSIS_GCC_OUT_REG(r) "=r" (r)
+#define __CMSIS_GCC_USE_REG(r) "r" (r)
+#endif
+
+/** \brief  No Operation
+
+    No Operation does nothing. This instruction can be used for code alignment purposes.
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __NOP(void)
+{
+  __ASM volatile ("nop");
+}
+
+
+/** \brief  Wait For Interrupt
+
+    Wait For Interrupt is a hint instruction that suspends execution
+    until one of a number of events occurs.
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __WFI(void)
+{
+  __ASM volatile ("wfi");
+}
+
+
+/** \brief  Wait For Event
+
+    Wait For Event is a hint instruction that permits the processor to enter
+    a low-power state until one of a number of events occurs.
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __WFE(void)
+{
+  __ASM volatile ("wfe");
+}
+
+
+/** \brief  Send Event
+
+    Send Event is a hint instruction. It causes an event to be signaled to the CPU.
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __SEV(void)
+{
+  __ASM volatile ("sev");
+}
+
+
+/** \brief  Instruction Synchronization Barrier
+
+    Instruction Synchronization Barrier flushes the pipeline in the processor,
+    so that all instructions following the ISB are fetched from cache or
+    memory, after the instruction has been completed.
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __ISB(void)
+{
+  __ASM volatile ("isb");
+}
+
+
+/** \brief  Data Synchronization Barrier
+
+    This function acts as a special kind of Data Memory Barrier.
+    It completes when all explicit memory accesses before this instruction complete.
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __DSB(void)
+{
+  __ASM volatile ("dsb");
+}
+
+
+/** \brief  Data Memory Barrier
+
+    This function ensures the apparent order of the explicit memory operations before
+    and after the instruction, without ensuring their completion.
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __DMB(void)
+{
+  __ASM volatile ("dmb");
+}
+
+
+/** \brief  Reverse byte order (32 bit)
+
+    This function reverses the byte order in integer value.
+
+    \param [in]    value  Value to reverse
+    \return               Reversed value
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __REV(uint32_t value)
+{
+#if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5)
+  return __builtin_bswap32(value);
+#else
+  uint32_t result;
+
+  __ASM volatile ("rev %0, %1" : __CMSIS_GCC_OUT_REG (result) : __CMSIS_GCC_USE_REG (value) );
+  return(result);
+#endif
+}
+
+
+/** \brief  Reverse byte order (16 bit)
+
+    This function reverses the byte order in two unsigned short values.
+
+    \param [in]    value  Value to reverse
+    \return               Reversed value
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __REV16(uint32_t value)
+{
+  uint32_t result;
+
+  __ASM volatile ("rev16 %0, %1" : __CMSIS_GCC_OUT_REG (result) : __CMSIS_GCC_USE_REG (value) );
+  return(result);
+}
+
+
+/** \brief  Reverse byte order in signed short value
+
+    This function reverses the byte order in a signed short value with sign extension to integer.
+
+    \param [in]    value  Value to reverse
+    \return               Reversed value
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE int32_t __REVSH(int32_t value)
+{
+#if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)
+  return (short)__builtin_bswap16(value);
+#else
+  uint32_t result;
+
+  __ASM volatile ("revsh %0, %1" : __CMSIS_GCC_OUT_REG (result) : __CMSIS_GCC_USE_REG (value) );
+  return(result);
+#endif
+}
+
+
+/** \brief  Rotate Right in unsigned value (32 bit)
+
+    This function Rotate Right (immediate) provides the value of the contents of a register rotated by a variable number of bits.
+
+    \param [in]    value  Value to rotate
+    \param [in]    value  Number of Bits to rotate
+    \return               Rotated value
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __ROR(uint32_t op1, uint32_t op2)
+{
+  return (op1 >> op2) | (op1 << (32 - op2)); 
+}
+
+
+/** \brief  Breakpoint
+
+    This function causes the processor to enter Debug state.
+    Debug tools can use this to investigate system state when the instruction at a particular address is reached.
+
+    \param [in]    value  is ignored by the processor.
+                   If required, a debugger can use it to store additional information about the breakpoint.
+ */
+#define __BKPT(value)                       __ASM volatile ("bkpt "#value)
+
+
+#if       (__CORTEX_M >= 0x03)
+
+/** \brief  Reverse bit order of value
+
+    This function reverses the bit order of the given value.
+
+    \param [in]    value  Value to reverse
+    \return               Reversed value
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __RBIT(uint32_t value)
+{
+  uint32_t result;
+
+   __ASM volatile ("rbit %0, %1" : "=r" (result) : "r" (value) );
+   return(result);
+}
+
+
+/** \brief  LDR Exclusive (8 bit)
+
+    This function performs a exclusive LDR command for 8 bit value.
+
+    \param [in]    ptr  Pointer to data
+    \return             value of type uint8_t at (*ptr)
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint8_t __LDREXB(volatile uint8_t *addr)
+{
+    uint32_t result;
+
+#if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)
+   __ASM volatile ("ldrexb %0, %1" : "=r" (result) : "Q" (*addr) );
+#else
+    /* Prior to GCC 4.8, "Q" will be expanded to [rx, #0] which is not
+       accepted by assembler. So has to use following less efficient pattern.
+    */
+   __ASM volatile ("ldrexb %0, [%1]" : "=r" (result) : "r" (addr) : "memory" );
+#endif
+   return(result);
+}
+
+
+/** \brief  LDR Exclusive (16 bit)
+
+    This function performs a exclusive LDR command for 16 bit values.
+
+    \param [in]    ptr  Pointer to data
+    \return        value of type uint16_t at (*ptr)
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint16_t __LDREXH(volatile uint16_t *addr)
+{
+    uint32_t result;
+
+#if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)
+   __ASM volatile ("ldrexh %0, %1" : "=r" (result) : "Q" (*addr) );
+#else
+    /* Prior to GCC 4.8, "Q" will be expanded to [rx, #0] which is not
+       accepted by assembler. So has to use following less efficient pattern.
+    */
+   __ASM volatile ("ldrexh %0, [%1]" : "=r" (result) : "r" (addr) : "memory" );
+#endif
+   return(result);
+}
+
+
+/** \brief  LDR Exclusive (32 bit)
+
+    This function performs a exclusive LDR command for 32 bit values.
+
+    \param [in]    ptr  Pointer to data
+    \return        value of type uint32_t at (*ptr)
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __LDREXW(volatile uint32_t *addr)
+{
+    uint32_t result;
+
+   __ASM volatile ("ldrex %0, %1" : "=r" (result) : "Q" (*addr) );
+   return(result);
+}
+
+
+/** \brief  STR Exclusive (8 bit)
+
+    This function performs a exclusive STR command for 8 bit values.
+
+    \param [in]  value  Value to store
+    \param [in]    ptr  Pointer to location
+    \return          0  Function succeeded
+    \return          1  Function failed
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __STREXB(uint8_t value, volatile uint8_t *addr)
+{
+   uint32_t result;
+
+   __ASM volatile ("strexb %0, %2, %1" : "=&r" (result), "=Q" (*addr) : "r" (value) );
+   return(result);
+}
+
+
+/** \brief  STR Exclusive (16 bit)
+
+    This function performs a exclusive STR command for 16 bit values.
+
+    \param [in]  value  Value to store
+    \param [in]    ptr  Pointer to location
+    \return          0  Function succeeded
+    \return          1  Function failed
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __STREXH(uint16_t value, volatile uint16_t *addr)
+{
+   uint32_t result;
+
+   __ASM volatile ("strexh %0, %2, %1" : "=&r" (result), "=Q" (*addr) : "r" (value) );
+   return(result);
+}
+
+
+/** \brief  STR Exclusive (32 bit)
+
+    This function performs a exclusive STR command for 32 bit values.
+
+    \param [in]  value  Value to store
+    \param [in]    ptr  Pointer to location
+    \return          0  Function succeeded
+    \return          1  Function failed
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __STREXW(uint32_t value, volatile uint32_t *addr)
+{
+   uint32_t result;
+
+   __ASM volatile ("strex %0, %2, %1" : "=&r" (result), "=Q" (*addr) : "r" (value) );
+   return(result);
+}
+
+
+/** \brief  Remove the exclusive lock
+
+    This function removes the exclusive lock which is created by LDREX.
+
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __CLREX(void)
+{
+  __ASM volatile ("clrex" ::: "memory");
+}
+
+
+/** \brief  Signed Saturate
+
+    This function saturates a signed value.
+
+    \param [in]  value  Value to be saturated
+    \param [in]    sat  Bit position to saturate to (1..32)
+    \return             Saturated value
+ */
+#define __SSAT(ARG1,ARG2) \
+({                          \
+  uint32_t __RES, __ARG1 = (ARG1); \
+  __ASM ("ssat %0, %1, %2" : "=r" (__RES) :  "I" (ARG2), "r" (__ARG1) ); \
+  __RES; \
+ })
+
+
+/** \brief  Unsigned Saturate
+
+    This function saturates an unsigned value.
+
+    \param [in]  value  Value to be saturated
+    \param [in]    sat  Bit position to saturate to (0..31)
+    \return             Saturated value
+ */
+#define __USAT(ARG1,ARG2) \
+({                          \
+  uint32_t __RES, __ARG1 = (ARG1); \
+  __ASM ("usat %0, %1, %2" : "=r" (__RES) :  "I" (ARG2), "r" (__ARG1) ); \
+  __RES; \
+ })
+
+
+/** \brief  Count leading zeros
+
+    This function counts the number of leading zeros of a data value.
+
+    \param [in]  value  Value to count the leading zeros
+    \return             number of leading zeros in value
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint8_t __CLZ(uint32_t value)
+{
+   uint32_t result;
+
+  __ASM volatile ("clz %0, %1" : "=r" (result) : "r" (value) );
+  return(result);
+}
+
+#endif /* (__CORTEX_M >= 0x03) */
+
+
+
+
+#elif defined ( __TASKING__ ) /*------------------ TASKING Compiler --------------*/
+/* TASKING carm specific functions */
+
+/*
+ * The CMSIS functions have been implemented as intrinsics in the compiler.
+ * Please use "carm -?i" to get an up to date list of all intrinsics,
+ * Including the CMSIS ones.
+ */
+
+#endif
+
+/*@}*/ /* end of group CMSIS_Core_InstructionInterface */
+
+#endif /* __CORE_CMINSTR_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/hw/drivers/adc/adc_stm32f4/include/adc_stm32f4/adc_stm32f4.h
----------------------------------------------------------------------
diff --git a/hw/drivers/adc/adc_stm32f4/include/adc_stm32f4/adc_stm32f4.h b/hw/drivers/adc/adc_stm32f4/include/adc_stm32f4/adc_stm32f4.h
new file mode 100644
index 0000000..31f0bb4
--- /dev/null
+++ b/hw/drivers/adc/adc_stm32f4/include/adc_stm32f4/adc_stm32f4.h
@@ -0,0 +1,62 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 __ADC_STM32F4_H__
+#define __ADC_STM32F4_H__
+
+#include <adc/adc.h>
+
+/* Mynewt HAL Port pin mapping */
+#define ADC123_CH0_PIN    0
+#define ADC123_CH1_PIN    1
+#define ADC123_CH2_PIN    2
+#define ADC123_CH3_PIN    3
+#define ADC12_CH4_PIN     4
+#define ADC12_CH5_PIN     5
+#define ADC12_CH6_PIN     6
+#define ADC12_CH7_PIN     7
+#define ADC12_CH8_PIN     16
+#define ADC12_CH9_PIN     17
+#define ADC3_CH4_PIN      86
+#define ADC3_CH5_PIN      87
+#define ADC3_CH6_PIN      88
+#define ADC3_CH7_PIN      89
+#define ADC3_CH8_PIN      90
+#define ADC3_CH9_PIN      83
+#define ADC123_CH10_PIN   32
+#define ADC123_CH11_PIN   33
+#define ADC123_CH12_PIN   34
+#define ADC123_CH13_PIN   35
+#define ADC12_CH14_PIN    36
+#define ADC12_CH15_PIN    37
+#define ADC3_CH14_PIN     84
+#define ADC3_CH15_PIN     85
+
+struct stm32f4_adc_dev_cfg {
+    uint8_t sac_chan_count;
+    void *sac_chans;
+    void *primarybuf;
+    void *secondarybuf;
+    int buflen;
+    ADC_HandleTypeDef *sac_adc_handle;
+};
+
+int stm32f4_adc_dev_init(struct os_dev *, void *);
+
+#endif /* __ADC_H__ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/hw/drivers/adc/adc_stm32f4/pkg.yml
----------------------------------------------------------------------
diff --git a/hw/drivers/adc/adc_stm32f4/pkg.yml b/hw/drivers/adc/adc_stm32f4/pkg.yml
new file mode 100644
index 0000000..0242101
--- /dev/null
+++ b/hw/drivers/adc/adc_stm32f4/pkg.yml
@@ -0,0 +1,34 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+#
+
+pkg.name: hw/drivers/adc/adc_stm32f4
+pkg.description: ADC driver for the STM32F4 series of processors.
+pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
+pkg.homepage: "http://mynewt.apache.org/"
+pkg.keywords:
+pkg.features:
+    - ADC_STM32F4
+pkg.apis:
+    - ADC_HW_IMPL
+pkg.deps:
+   - hw/drivers/adc
+pkg.deps.TEST:
+   - hw/hal
+   - hw/mcu/stm/stm32f4xx
+   - test/testutil

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/hw/drivers/adc/adc_stm32f4/src/adc_stm32f4.c
----------------------------------------------------------------------
diff --git a/hw/drivers/adc/adc_stm32f4/src/adc_stm32f4.c b/hw/drivers/adc/adc_stm32f4/src/adc_stm32f4.c
new file mode 100644
index 0000000..fba9dd2
--- /dev/null
+++ b/hw/drivers/adc/adc_stm32f4/src/adc_stm32f4.c
@@ -0,0 +1,735 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+
+#include <hal/hal_bsp.h>
+#include <assert.h>
+#include <os/os.h>
+#include <bsp/cmsis_nvic.h>
+#include "stm32f4xx_hal_dma.h"
+#include "stm32f4xx_hal_adc.h"
+#include "stm32f4xx_hal_rcc.h"
+#include "stm32f4xx_hal_cortex.h"
+#include "stm32f4xx_hal.h"
+#include "adc_stm32f4/adc_stm32f4.h"
+#include "stm32f4xx_hal_dma.h"
+#include "mcu/stm32f4xx_mynewt_hal.h"
+#include "syscfg/syscfg.h"
+
+#if MYNEWT_VAL(ADC_1)||MYNEWT_VAL(ADC_2)||MYNEWT_VAL(ADC_3)
+#include <adc/adc.h>
+#endif
+
+#define STM32F4_IS_DMA_ADC_CHANNEL(CHANNEL) ((CHANNEL) <= DMA_CHANNEL_2)
+
+static DMA_HandleTypeDef *dma_handle[5];
+static struct adc_dev *adc_dma[5];
+
+struct stm32f4_adc_stats {
+    uint16_t adc_events;
+    uint16_t adc_error;
+    uint16_t adc_dma_xfer_failed;
+    uint16_t adc_dma_xfer_aborted;
+    uint16_t adc_dma_xfer_complete;
+    uint16_t adc_dma_start_error;
+    uint16_t adc_dma_overrun;
+    uint16_t adc_internal_error;
+};
+
+static struct stm32f4_adc_stats stm32f4_adc_stats;
+
+static void
+stm32f4_adc_clk_enable(ADC_HandleTypeDef *hadc) {
+    uintptr_t adc_addr = (uintptr_t)hadc->Instance;
+
+    switch (adc_addr) {
+        case (uintptr_t)ADC1:
+            __HAL_RCC_ADC1_CLK_ENABLE();
+            break;
+        case (uintptr_t)ADC2:
+            __HAL_RCC_ADC2_CLK_ENABLE();
+            break;
+        case (uintptr_t)ADC3:
+            __HAL_RCC_ADC3_CLK_ENABLE();
+            break;
+        default:
+            assert(0);
+    }
+}
+
+static void
+stm32f4_adc_clk_disable(ADC_HandleTypeDef *hadc) {
+    uintptr_t adc_addr = (uintptr_t)hadc->Instance;
+
+    switch (adc_addr) {
+        case (uintptr_t)ADC1:
+            __HAL_RCC_ADC1_CLK_DISABLE();
+            break;
+        case (uintptr_t)ADC2:
+            __HAL_RCC_ADC2_CLK_DISABLE();
+            break;
+        case (uintptr_t)ADC3:
+            __HAL_RCC_ADC3_CLK_DISABLE();
+            break;
+        default:
+            assert(0);
+    }
+}
+
+static int
+stm32f4_resolve_adc_gpio(ADC_HandleTypeDef *adc, uint8_t cnum, GPIO_InitTypeDef *gpio)
+{
+    uintptr_t adc_addr = (uintptr_t)adc->Instance;
+    uint32_t pin;
+    int rc;
+
+    rc = OS_OK;
+    switch (adc_addr) {
+        case (uintptr_t)ADC1:
+        case (uintptr_t)ADC2:
+            switch(cnum) {
+                case ADC_CHANNEL_4:
+                    pin = ADC12_CH4_PIN;
+                    goto done;
+                case ADC_CHANNEL_5:
+                    pin = ADC12_CH5_PIN;
+                    goto done;
+                case ADC_CHANNEL_6:
+                    pin = ADC12_CH6_PIN;
+                    goto done;
+                case ADC_CHANNEL_7:
+                    pin = ADC12_CH7_PIN;
+                    goto done;
+                case ADC_CHANNEL_8:
+                    pin = ADC12_CH8_PIN;
+                    goto done;
+                case ADC_CHANNEL_9:
+                    pin = ADC12_CH9_PIN;
+                    goto done;
+                case ADC_CHANNEL_14:
+                    pin = ADC12_CH14_PIN;
+                    goto done;
+                case ADC_CHANNEL_15:
+                    pin = ADC12_CH15_PIN;
+                    goto done;
+            }
+        /*
+         * Falling through intentionally as ADC_3 contains seperate pins for
+         * Channels that ADC_1 and ADC_2 contain as well.
+         */
+        case (uintptr_t)ADC3:
+            switch(cnum) {
+                case ADC_CHANNEL_0:
+                    pin = ADC123_CH0_PIN;
+                    goto done;
+                case ADC_CHANNEL_1:
+                    pin = ADC123_CH1_PIN;
+                    goto done;
+                case ADC_CHANNEL_2:
+                    pin = ADC123_CH2_PIN;
+                    goto done;
+                case ADC_CHANNEL_3:
+                    pin = ADC123_CH3_PIN;
+                    goto done;
+                case ADC_CHANNEL_4:
+                    pin = ADC3_CH4_PIN;
+                    goto done;
+                case ADC_CHANNEL_5:
+                    pin = ADC3_CH5_PIN;
+                    goto done;
+                case ADC_CHANNEL_6:
+                    pin = ADC3_CH6_PIN;
+                    goto done;
+                case ADC_CHANNEL_7:
+                    pin = ADC3_CH7_PIN;
+                    goto done;
+                case ADC_CHANNEL_8:
+                    pin = ADC3_CH8_PIN;
+                    goto done;
+                case ADC_CHANNEL_9:
+                    pin = ADC3_CH9_PIN;
+                    goto done;
+                case ADC_CHANNEL_10:
+                    pin = ADC123_CH10_PIN;
+                    goto done;
+                case ADC_CHANNEL_11:
+                    pin = ADC123_CH11_PIN;
+                    goto done;
+                case ADC_CHANNEL_12:
+                    pin = ADC123_CH12_PIN;
+                    goto done;
+                case ADC_CHANNEL_13:
+                    pin = ADC123_CH13_PIN;
+                    goto done;
+                case ADC_CHANNEL_14:
+                    pin = ADC3_CH14_PIN;
+                    goto done;
+                case ADC_CHANNEL_15:
+                    pin = ADC3_CH15_PIN;
+                    goto done;
+            }
+        default:
+            rc = OS_EINVAL;
+            return rc;
+    }
+done:
+    *gpio = (GPIO_InitTypeDef) {
+        .Pin = pin,
+        .Mode = GPIO_MODE_ANALOG,
+        .Pull = GPIO_NOPULL,
+        .Alternate = pin
+    };
+    return rc;
+}
+
+static IRQn_Type
+stm32f4_resolve_adc_dma_irq(DMA_HandleTypeDef *hdma)
+{
+    uintptr_t stream_addr = (uintptr_t)hdma->Instance;
+
+    assert(STM32F4_IS_DMA_ADC_CHANNEL(hdma->Init.Channel));
+
+    switch(stream_addr) {
+        /* DMA2 */
+        case (uintptr_t)DMA2_Stream0:
+            return DMA2_Stream0_IRQn;
+        case (uintptr_t)DMA2_Stream1:
+            return DMA2_Stream1_IRQn;
+        case (uintptr_t)DMA2_Stream2:
+            return DMA2_Stream2_IRQn;
+        case (uintptr_t)DMA2_Stream3:
+            return DMA2_Stream3_IRQn;
+        case (uintptr_t)DMA2_Stream4:
+            return DMA2_Stream4_IRQn;
+        default:
+            assert(0);
+    }
+}
+
+static void
+dma2_stream0_irq_handler(void)
+{
+    HAL_DMA_IRQHandler(dma_handle[0]);
+}
+
+static void
+dma2_stream1_irq_handler(void)
+{
+    HAL_DMA_IRQHandler(dma_handle[1]);
+}
+
+static void
+dma2_stream2_irq_handler(void)
+{
+    HAL_DMA_IRQHandler(dma_handle[2]);
+}
+
+static void
+dma2_stream3_irq_handler(void)
+{
+    HAL_DMA_IRQHandler(dma_handle[3]);
+}
+
+static void
+dma2_stream4_irq_handler(void)
+{
+    HAL_DMA_IRQHandler(dma_handle[4]);
+}
+
+uint32_t
+stm32f4_resolve_adc_dma_irq_handler(DMA_HandleTypeDef *hdma)
+{
+    switch((uintptr_t)hdma->Instance) {
+        /* DMA2 */
+        case (uintptr_t)DMA2_Stream0:
+            return (uint32_t)&dma2_stream0_irq_handler;
+        case (uintptr_t)DMA2_Stream1:
+            return (uint32_t)&dma2_stream1_irq_handler;
+        case (uintptr_t)DMA2_Stream2:
+            return (uint32_t)&dma2_stream2_irq_handler;
+        case (uintptr_t)DMA2_Stream3:
+            return (uint32_t)&dma2_stream3_irq_handler;
+        case (uintptr_t)DMA2_Stream4:
+            return (uint32_t)&dma2_stream4_irq_handler;
+        default:
+            assert(0);
+    }
+}
+
+static int
+stm32f4_resolve_dma_handle_idx(DMA_HandleTypeDef *hdma)
+{
+    uintptr_t stream_addr = (uintptr_t)hdma->Instance;
+    return ((stream_addr & 0xFF) - ((uintptr_t)DMA2_Stream0_BASE & 0xFF))/0x18;
+}
+
+void
+HAL_ADC_ErrorCallback(ADC_HandleTypeDef *hadc)
+{
+    ++stm32f4_adc_stats.adc_error;
+
+    if (hadc->ErrorCode & HAL_ADC_ERROR_DMA) {
+        /* DMA transfer error */
+        ++stm32f4_adc_stats.adc_dma_xfer_failed;
+    } else if (hadc->ErrorCode & HAL_ADC_ERROR_OVR) {
+        /* DMA transfer overrun */
+        ++stm32f4_adc_stats.adc_dma_overrun;
+    } else if (hadc->ErrorCode & HAL_ADC_ERROR_INTERNAL) {
+       /* ADC IP Internal Error */
+        ++stm32f4_adc_stats.adc_internal_error;
+    }
+}
+
+/**
+ * Callback that gets called by the HAL when ADC conversion is complete and
+ * the DMA buffer is full. If a secondary buffer exists it will the buffers.
+ *
+ * @param ADC Handle
+ */
+void
+HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef *hadc)
+{
+    int rc;
+    struct adc_dev *adc;
+    DMA_HandleTypeDef *hdma;
+    struct stm32f4_adc_dev_cfg *cfg;
+    void *buf;
+
+    assert(hadc);
+    hdma = hadc->DMA_Handle;
+
+    ++stm32f4_adc_stats.adc_dma_xfer_complete;
+
+    adc = adc_dma[stm32f4_resolve_dma_handle_idx(hdma)];
+    cfg  = (struct stm32f4_adc_dev_cfg *)adc->ad_dev.od_init_arg;
+
+    buf = cfg->primarybuf;
+    /**
+     * If primary buffer gets full and secondary buffer exists, swap the
+     * buffers and start ADC conversion with DMA with the now primary
+     * buffer(former secondary buffer)
+     * If the secondary buffer(former primary buffer) doesn't get processed
+     * by the application in sampling period required for the primary/secondary buffer
+     * i,e; (sample itvl * ADC_NUMBER_SAMPLES), the buffers would get swapped resulting
+     * in new sample data.
+     */
+    if (cfg->secondarybuf) {
+        cfg->primarybuf = cfg->secondarybuf;
+        cfg->secondarybuf = buf;
+
+        if (HAL_ADC_Start_DMA(hadc, cfg->primarybuf, cfg->buflen) != HAL_OK) {
+            ++stm32f4_adc_stats.adc_dma_start_error;
+        }
+    }
+
+    rc = adc->ad_event_handler_func(adc, NULL, ADC_EVENT_RESULT, buf,
+                                    cfg->buflen);
+
+    if (rc) {
+        ++stm32f4_adc_stats.adc_error;
+    }
+}
+
+static void
+stm32f4_adc_dma_init(ADC_HandleTypeDef* hadc)
+{
+
+    DMA_HandleTypeDef *hdma;
+
+    assert(hadc);
+    hdma = hadc->DMA_Handle;
+
+    stm32f4_adc_clk_enable(hadc);
+    __HAL_RCC_DMA2_CLK_ENABLE();
+
+    HAL_DMA_Init(hdma);
+    dma_handle[stm32f4_resolve_dma_handle_idx(hdma)] = hdma;
+
+    NVIC_SetPriority(stm32f4_resolve_adc_dma_irq(hdma),
+                     NVIC_EncodePriority(NVIC_GetPriorityGrouping(), 0, 0));
+    NVIC_SetVector(stm32f4_resolve_adc_dma_irq(hdma),
+                   stm32f4_resolve_adc_dma_irq_handler(hdma));
+    NVIC_EnableIRQ(stm32f4_resolve_adc_dma_irq(hdma));
+
+}
+
+static void
+stm32f4_adc_init(struct adc_dev *dev)
+{
+    struct stm32f4_adc_dev_cfg *adc_config;
+    ADC_HandleTypeDef *hadc;
+
+    assert(dev);
+
+    adc_config = (struct stm32f4_adc_dev_cfg *)dev->ad_dev.od_init_arg;
+    hadc = adc_config->sac_adc_handle;
+
+    stm32f4_adc_dma_init(hadc);
+
+    if (HAL_ADC_Init(hadc) != HAL_OK) {
+        assert(0);
+    }
+}
+
+static void
+stm32f4_adc_uninit(struct adc_dev *dev)
+{
+    GPIO_InitTypeDef gpio_td;
+    DMA_HandleTypeDef *hdma;
+    ADC_HandleTypeDef *hadc;
+    struct stm32f4_adc_dev_cfg *cfg;
+    uint8_t cnum;
+
+    assert(dev);
+    cfg  = (struct stm32f4_adc_dev_cfg *)dev->ad_dev.od_init_arg;
+    hadc = cfg->sac_adc_handle;
+    hdma = hadc->DMA_Handle;
+    cnum = dev->ad_chans->c_cnum;
+
+    __HAL_RCC_DMA2_CLK_DISABLE();
+    if (HAL_DMA_DeInit(hdma) != HAL_OK) {
+        assert(0);
+    }
+    stm32f4_adc_clk_disable(hadc);
+
+    NVIC_DisableIRQ(stm32f4_resolve_adc_dma_irq(hdma));
+
+    if (stm32f4_resolve_adc_gpio(hadc, cnum, &gpio_td)) {
+        goto err;
+    }
+
+    if(hal_gpio_deinit_stm(gpio_td.Pin, &gpio_td)) {
+        goto err;
+    }
+
+err:
+    return;
+}
+
+/**
+ * Open the STM32F4 ADC device
+ *
+ * This function locks the device for access from other tasks.
+ *
+ * @param odev The OS device to open
+ * @param wait The time in MS to wait.  If 0 specified, returns immediately
+ *             if resource unavailable.  If OS_WAIT_FOREVER specified, blocks
+ *             until resource is available.
+ * @param arg  Argument provided by higher layer to open.
+ *
+ * @return 0 on success, non-zero on failure.
+ */
+static int
+stm32f4_adc_open(struct os_dev *odev, uint32_t wait, void *arg)
+{
+    DMA_HandleTypeDef *hdma;
+    ADC_HandleTypeDef *hadc;
+    struct stm32f4_adc_dev_cfg *cfg;
+    struct adc_dev *dev;
+    int rc;
+
+    assert(odev);
+    rc = OS_OK;
+    dev = (struct adc_dev *) odev;
+
+    if (os_started()) {
+        rc = os_mutex_pend(&dev->ad_lock, wait);
+        if (rc != OS_OK) {
+            goto err;
+        }
+    }
+
+    if (odev->od_flags & OS_DEV_F_STATUS_OPEN) {
+        os_mutex_release(&dev->ad_lock);
+        rc = OS_EBUSY;
+        goto err;
+    }
+
+    stm32f4_adc_init(dev);
+
+    cfg  = (struct stm32f4_adc_dev_cfg *)dev->ad_dev.od_init_arg;
+    hadc = cfg->sac_adc_handle;
+    hdma = hadc->DMA_Handle;
+
+    adc_dma[stm32f4_resolve_dma_handle_idx(hdma)] = dev;
+
+    return (OS_OK);
+err:
+    return (rc);
+}
+
+
+/**
+ * Close the STM32F4 ADC device.
+ *
+ * This function unlocks the device.
+ *
+ * @param odev The device to close.
+ */
+static int
+stm32f4_adc_close(struct os_dev *odev)
+{
+    struct adc_dev *dev;
+
+    dev = (struct adc_dev *) odev;
+
+    stm32f4_adc_uninit(dev);
+
+    if (os_started()) {
+        os_mutex_release(&dev->ad_lock);
+    }
+
+    return (OS_OK);
+}
+
+/**
+ * Configure an ADC channel on the STM32F4 ADC.
+ *
+ * @param dev The ADC device to configure
+ * @param cnum The channel on the ADC device to configure
+ * @param cfgdata An opaque pointer to channel config, expected to be
+ *                a ADC_ChannelConfTypeDef
+ *
+ * @return 0 on success, non-zero on failure.
+ */
+static int
+stm32f4_adc_configure_channel(struct adc_dev *dev, uint8_t cnum,
+        void *cfgdata)
+{
+    int rc;
+    ADC_HandleTypeDef *hadc;
+    struct stm32f4_adc_dev_cfg *cfg;
+    struct adc_chan_config *chan_cfg;
+    GPIO_InitTypeDef gpio_td;
+
+    rc = OS_EINVAL;
+
+    if (dev == NULL && !IS_ADC_CHANNEL(cnum)) {
+        goto err;
+    }
+
+    cfg  = (struct stm32f4_adc_dev_cfg *)dev->ad_dev.od_init_arg;
+    hadc = cfg->sac_adc_handle;
+    chan_cfg = &((struct adc_chan_config *)cfg->sac_chans)[cnum];
+
+    cfgdata = (ADC_ChannelConfTypeDef *)cfgdata;
+
+    if ((HAL_ADC_ConfigChannel(hadc, cfgdata)) != HAL_OK) {
+        goto err;
+    }
+
+    dev->ad_chans[cnum].c_res = chan_cfg->c_res;
+    dev->ad_chans[cnum].c_refmv = chan_cfg->c_refmv;
+    dev->ad_chans[cnum].c_configured = 1;
+    dev->ad_chans[cnum].c_cnum = cnum;
+
+    if (stm32f4_resolve_adc_gpio(hadc, cnum, &gpio_td)) {
+        goto err;
+    }
+
+    hal_gpio_init_stm(gpio_td.Pin, &gpio_td);
+
+#if 0
+    if (HAL_ADC_Start_IT(hadc) != HAL_OK) {
+        goto err;
+    }
+#endif
+
+    return (OS_OK);
+err:
+    return (rc);
+}
+
+/**
+ * Set buffer to read data into.  Implementation of setbuffer handler.
+ * Sets both the primary and secondary buffers for DMA.
+ *
+ * For our current implementation we are using DMA in circular mode
+ *
+ */
+static int
+stm32f4_adc_set_buffer(struct adc_dev *dev, void *buf1, void *buf2,
+        int buflen)
+{
+    struct stm32f4_adc_dev_cfg *cfg;
+    int rc;
+
+
+    assert(dev != NULL && buf1 != NULL);
+    rc = OS_OK;
+    buflen /= sizeof(uint32_t);
+
+    cfg  = (struct stm32f4_adc_dev_cfg *)dev->ad_dev.od_init_arg;
+
+    cfg->primarybuf = buf1;
+    cfg->secondarybuf = buf2;
+    cfg->buflen = buflen;
+
+    return rc;
+}
+
+static int
+stm32f4_adc_release_buffer(struct adc_dev *dev, void *buf, int buf_len)
+{
+    ADC_HandleTypeDef *hadc;
+    struct stm32f4_adc_dev_cfg *cfg;
+
+    assert(dev);
+    cfg  = (struct stm32f4_adc_dev_cfg *)dev->ad_dev.od_init_arg;
+    hadc = cfg->sac_adc_handle;
+
+    HAL_ADC_Stop_DMA(hadc);
+
+    return (0);
+}
+
+/**
+ * Trigger an ADC sample.
+ *
+ * @param ADC device structure
+ * @return OS_OK on success, non OS_OK on failure
+ */
+static int
+stm32f4_adc_sample(struct adc_dev *dev)
+{
+    int rc;
+    ADC_HandleTypeDef *hadc;
+    struct stm32f4_adc_dev_cfg *cfg;
+
+    assert(dev);
+    cfg  = (struct stm32f4_adc_dev_cfg *)dev->ad_dev.od_init_arg;
+    hadc = cfg->sac_adc_handle;
+
+    rc = OS_EINVAL;
+
+    if (HAL_ADC_Start_DMA(hadc, cfg->primarybuf, cfg->buflen) != HAL_OK) {
+        ++stm32f4_adc_stats.adc_dma_start_error;
+        goto err;
+    }
+
+    rc = OS_OK;
+
+err:
+    return rc;
+}
+
+/**
+ * Blocking read of an ADC channel, returns result as an integer.
+ *
+ * @param1 ADC device structure
+ * @param2 channel number
+ * @param3 ADC result ptr
+ */
+static int
+stm32f4_adc_read_channel(struct adc_dev *dev, uint8_t cnum, int *result)
+{
+    ADC_HandleTypeDef *hadc;
+    struct stm32f4_adc_dev_cfg *cfg;
+
+    assert(dev != NULL && result != NULL);
+    cfg  = (struct stm32f4_adc_dev_cfg *)dev->ad_dev.od_init_arg;
+    hadc = cfg->sac_adc_handle;
+
+    *result = HAL_ADC_GetValue(hadc);
+
+    return (OS_OK);
+}
+
+static int
+stm32f4_adc_read_buffer(struct adc_dev *dev, void *buf, int buf_len, int off,
+                        int *result)
+{
+
+    assert(off < buf_len);
+
+    /*
+     * If secondary buffer exists the primary buf is going to be cached
+     * in the secondary buffer if the primary buffer is full and we
+     * would be reading that instead since the buffer is specified by
+     * the application
+     */
+    *result = *((uint32_t *)buf + off);
+
+    return (OS_OK);
+}
+
+/**
+ * Callback to return size of buffer
+ *
+ * @param1 ADC device ptr
+ * @param2 Total number of channels
+ * @param3 Total number of samples
+ * @return Length of buffer in bytes
+ */
+static int
+stm32f4_adc_size_buffer(struct adc_dev *dev, int chans, int samples)
+{
+    return (sizeof(uint32_t) * chans * samples);
+}
+
+#if 0
+void ADC_IRQHandler(void)
+{
+    HAL_ADC_IRQHandler(adc_handle);
+}
+#endif
+
+
+/**
+ * Callback to initialize an adc_dev structure from the os device
+ * initialization callback.  This sets up a stm32f4_adc_device(), so
+ * that subsequent lookups to this device allow us to manipulate it.
+ *
+ * @param1 os device ptr
+ * @param2 stm32f4 ADC device cfg ptr
+ * @return OS_OK on success
+ */
+int
+stm32f4_adc_dev_init(struct os_dev *odev, void *arg)
+{
+    struct stm32f4_adc_dev_cfg *sac;
+    struct adc_dev *dev;
+    struct adc_driver_funcs *af;
+
+    sac = (struct stm32f4_adc_dev_cfg *) arg;
+
+    assert(sac != NULL);
+
+    dev = (struct adc_dev *)odev;
+
+    os_mutex_init(&dev->ad_lock);
+
+    dev->ad_chans = (void *) sac->sac_chans;
+    dev->ad_chan_count = sac->sac_chan_count;
+
+    OS_DEV_SETHANDLERS(odev, stm32f4_adc_open, stm32f4_adc_close);
+
+    af = &dev->ad_funcs;
+
+    af->af_configure_channel = stm32f4_adc_configure_channel;
+    af->af_sample = stm32f4_adc_sample;
+    af->af_read_channel = stm32f4_adc_read_channel;
+    af->af_set_buffer = stm32f4_adc_set_buffer;
+    af->af_release_buffer = stm32f4_adc_release_buffer;
+    af->af_read_buffer = stm32f4_adc_read_buffer;
+    af->af_size_buffer = stm32f4_adc_size_buffer;
+
+    return (OS_OK);
+}
+

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/hw/hal/pkg.yml
----------------------------------------------------------------------
diff --git a/hw/hal/pkg.yml b/hw/hal/pkg.yml
index 2049849..e3f5bed 100644
--- a/hw/hal/pkg.yml
+++ b/hw/hal/pkg.yml
@@ -23,4 +23,4 @@ pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
 pkg.homepage: "http://mynewt.apache.org/"
 pkg.keywords:
 
-pkg.deps: libs/os
+pkg.deps: kernel/os

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/hw/mcu/nordic/nrf51xxx/pkg.yml
----------------------------------------------------------------------
diff --git a/hw/mcu/nordic/nrf51xxx/pkg.yml b/hw/mcu/nordic/nrf51xxx/pkg.yml
index 4485725..fad358c 100644
--- a/hw/mcu/nordic/nrf51xxx/pkg.yml
+++ b/hw/mcu/nordic/nrf51xxx/pkg.yml
@@ -26,6 +26,6 @@ pkg.keywords:
 
 pkg.deps: 
     - hw/hal 
-    - libs/cmsis-core 
+    - hw/cmsis-core 
     - hw/mcu/nordic 
     - compiler/arm-none-eabi-m0

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/hw/mcu/nordic/nrf52xxx/pkg.yml
----------------------------------------------------------------------
diff --git a/hw/mcu/nordic/nrf52xxx/pkg.yml b/hw/mcu/nordic/nrf52xxx/pkg.yml
index 27fdb70..ae087c0 100644
--- a/hw/mcu/nordic/nrf52xxx/pkg.yml
+++ b/hw/mcu/nordic/nrf52xxx/pkg.yml
@@ -27,5 +27,5 @@ pkg.keywords:
 pkg.deps: 
     - hw/hal 
     - hw/mcu/nordic
-    - libs/cmsis-core 
+    - hw/cmsis-core 
     - compiler/arm-none-eabi-m4

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/hw/mcu/nordic/pkg.yml
----------------------------------------------------------------------
diff --git a/hw/mcu/nordic/pkg.yml b/hw/mcu/nordic/pkg.yml
index c695143..54e3173 100644
--- a/hw/mcu/nordic/pkg.yml
+++ b/hw/mcu/nordic/pkg.yml
@@ -56,4 +56,4 @@ pkg.cflags: -std=gnu99 -DNRF52_PAN_28
 
 pkg.deps: 
     - hw/hal 
-    - libs/cmsis-core 
+    - hw/cmsis-core 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/hw/mcu/stm/stm32f4xx/pkg.yml
----------------------------------------------------------------------
diff --git a/hw/mcu/stm/stm32f4xx/pkg.yml b/hw/mcu/stm/stm32f4xx/pkg.yml
index 83c0742..d4b8f86 100644
--- a/hw/mcu/stm/stm32f4xx/pkg.yml
+++ b/hw/mcu/stm/stm32f4xx/pkg.yml
@@ -35,5 +35,5 @@ pkg.ign_dirs:
 
 pkg.deps: 
     - hw/hal 
-    - libs/cmsis-core
+    - hw/cmsis-core
     - compiler/arm-none-eabi-m4

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/hw/mcu/stm/stm32f4xx/src/hal_watchdog.c
----------------------------------------------------------------------
diff --git a/hw/mcu/stm/stm32f4xx/src/hal_watchdog.c b/hw/mcu/stm/stm32f4xx/src/hal_watchdog.c
index dfd7304..97bc8e3 100644
--- a/hw/mcu/stm/stm32f4xx/src/hal_watchdog.c
+++ b/hw/mcu/stm/stm32f4xx/src/hal_watchdog.c
@@ -20,7 +20,7 @@
 #include "hal/hal_watchdog.h"
 
 int
-hal_watchdog_init(int expire_msecs)
+hal_watchdog_init(uint32_t expire_msecs)
 {
     return (0);
 }



[20/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/llex.c
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/llex.c b/libs/elua/elua_base/src/llex.c
deleted file mode 100644
index 77a4814..0000000
--- a/libs/elua/elua_base/src/llex.c
+++ /dev/null
@@ -1,458 +0,0 @@
-/*
-** $Id: llex.c,v 2.20.1.2 2009/11/23 14:58:22 roberto Exp $
-** Lexical Analyzer
-** See Copyright Notice in lua.h
-*/
-
-
-#include <ctype.h>
-#include <locale.h>
-#include <string.h>
-
-#define llex_c
-#define LUA_CORE
-
-#include "lua.h"
-
-#include "ldo.h"
-#include "llex.h"
-#include "lobject.h"
-#include "lparser.h"
-#include "lstate.h"
-#include "lstring.h"
-#include "ltable.h"
-#include "lzio.h"
-
-
-
-#define next(ls) (ls->current = zgetc(ls->z))
-
-
-
-
-#define currIsNewline(ls)	(ls->current == '\n' || ls->current == '\r')
-
-
-/* ORDER RESERVED */
-const char *const luaX_tokens [] = {
-    "and", "break", "do", "else", "elseif",
-    "end", "false", "for", "function", "if",
-    "in", "local", "nil", "not", "or", "repeat",
-    "return", "then", "true", "until", "while",
-    "..", "...", "==", ">=", "<=", "~=",
-    "<number>", "<name>", "<string>", "<eof>",
-    NULL
-};
-
-
-#define save_and_next(ls) (save(ls, ls->current), next(ls))
-
-
-static void save (LexState *ls, int c) {
-  Mbuffer *b = ls->buff;
-  if (b->n + 1 > b->buffsize) {
-    size_t newsize;
-    if (b->buffsize >= MAX_SIZET/2)
-      luaX_lexerror(ls, "lexical element too long", 0);
-    newsize = b->buffsize * 2;
-    luaZ_resizebuffer(ls->L, b, newsize);
-  }
-  b->buffer[b->n++] = cast(char, c);
-}
-
-
-void luaX_init (lua_State *L) {
-}
-
-
-#define MAXSRC          80
-
-
-const char *luaX_token2str (LexState *ls, int token) {
-  if (token < FIRST_RESERVED) {
-    lua_assert(token == cast(unsigned char, token));
-    return (iscntrl(token)) ? luaO_pushfstring(ls->L, "char(%d)", token) :
-                              luaO_pushfstring(ls->L, "%c", token);
-  }
-  else
-    return luaX_tokens[token-FIRST_RESERVED];
-}
-
-
-static const char *txtToken (LexState *ls, int token) {
-  switch (token) {
-    case TK_NAME:
-    case TK_STRING:
-    case TK_NUMBER:
-      save(ls, '\0');
-      return luaZ_buffer(ls->buff);
-    default:
-      return luaX_token2str(ls, token);
-  }
-}
-
-
-void luaX_lexerror (LexState *ls, const char *msg, int token) {
-  char buff[MAXSRC];
-  luaO_chunkid(buff, getstr(ls->source), MAXSRC);
-  msg = luaO_pushfstring(ls->L, "%s:%d: %s", buff, ls->linenumber, msg);
-  if (token)
-    luaO_pushfstring(ls->L, "%s near " LUA_QS, msg, txtToken(ls, token));
-  luaD_throw(ls->L, LUA_ERRSYNTAX);
-}
-
-
-void luaX_syntaxerror (LexState *ls, const char *msg) {
-  luaX_lexerror(ls, msg, ls->t.token);
-}
-
-
-TString *luaX_newstring (LexState *ls, const char *str, size_t l) {
-  lua_State *L = ls->L;
-  TString *ts = luaS_newlstr(L, str, l);
-  TValue *o = luaH_setstr(L, ls->fs->h, ts);  /* entry for `str' */
-  if (ttisnil(o)) {
-    setbvalue(o, 1);  /* make sure `str' will not be collected */
-    luaC_checkGC(L);
-  }
-  return ts;
-}
-
-
-static void inclinenumber (LexState *ls) {
-  int old = ls->current;
-  lua_assert(currIsNewline(ls));
-  next(ls);  /* skip `\n' or `\r' */
-  if (currIsNewline(ls) && ls->current != old)
-    next(ls);  /* skip `\n\r' or `\r\n' */
-  if (++ls->linenumber >= MAX_INT)
-    luaX_syntaxerror(ls, "chunk has too many lines");
-}
-
-
-void luaX_setinput (lua_State *L, LexState *ls, ZIO *z, TString *source) {
-  ls->decpoint = '.';
-  ls->L = L;
-  ls->lookahead.token = TK_EOS;  /* no look-ahead token */
-  ls->z = z;
-  ls->fs = NULL;
-  ls->linenumber = 1;
-  ls->lastline = 1;
-  ls->source = source;
-  luaZ_resizebuffer(ls->L, ls->buff, LUA_MINBUFFER);  /* initialize buffer */
-  next(ls);  /* read first char */
-}
-
-
-
-/*
-** =======================================================
-** LEXICAL ANALYZER
-** =======================================================
-*/
-
-
-
-static int check_next (LexState *ls, const char *set) {
-  if (!strchr(set, ls->current))
-    return 0;
-  save_and_next(ls);
-  return 1;
-}
-
-
-static void buffreplace (LexState *ls, char from, char to) {
-  size_t n = luaZ_bufflen(ls->buff);
-  char *p = luaZ_buffer(ls->buff);
-  while (n--)
-    if (p[n] == from) p[n] = to;
-}
-
-
-static void trydecpoint (LexState *ls, SemInfo *seminfo) {
-  /* format error: try to update decimal point separator */
-  struct lconv *cv = localeconv();
-  char old = ls->decpoint;
-  ls->decpoint = (cv ? cv->decimal_point[0] : '.');
-  buffreplace(ls, old, ls->decpoint);  /* try updated decimal separator */
-  if (!luaO_str2d(luaZ_buffer(ls->buff), &seminfo->r)) {
-    /* format error with correct decimal point: no more options */
-    buffreplace(ls, ls->decpoint, '.');  /* undo change (for error message) */
-    luaX_lexerror(ls, "malformed number", TK_NUMBER);
-  }
-}
-
-
-/* LUA_NUMBER */
-static void read_numeral (LexState *ls, SemInfo *seminfo) {
-  lua_assert(isdigit(ls->current));
-  do {
-    save_and_next(ls);
-  } while (isdigit(ls->current) || ls->current == '.');
-  if (check_next(ls, "Ee"))  /* `E'? */
-    check_next(ls, "+-");  /* optional exponent sign */
-  while (isalnum(ls->current) || ls->current == '_')
-    save_and_next(ls);
-  save(ls, '\0');
-  buffreplace(ls, '.', ls->decpoint);  /* follow locale for decimal point */
-  if (!luaO_str2d(luaZ_buffer(ls->buff), &seminfo->r))  /* format error? */
-    trydecpoint(ls, seminfo); /* try to update decimal point separator */
-}
-
-
-static int skip_sep (LexState *ls) {
-  int count = 0;
-  int s = ls->current;
-  lua_assert(s == '[' || s == ']');
-  save_and_next(ls);
-  while (ls->current == '=') {
-    save_and_next(ls);
-    count++;
-  }
-  return (ls->current == s) ? count : (-count) - 1;
-}
-
-
-static void read_long_string (LexState *ls, SemInfo *seminfo, int sep) {
-  int cont = 0;
-  (void)(cont);  /* avoid warnings when `cont' is not used */
-  save_and_next(ls);  /* skip 2nd `[' */
-  if (currIsNewline(ls))  /* string starts with a newline? */
-    inclinenumber(ls);  /* skip it */
-  for (;;) {
-    switch (ls->current) {
-      case EOZ:
-        luaX_lexerror(ls, (seminfo) ? "unfinished long string" :
-                                   "unfinished long comment", TK_EOS);
-        break;  /* to avoid warnings */
-#if defined(LUA_COMPAT_LSTR)
-      case '[': {
-        if (skip_sep(ls) == sep) {
-          save_and_next(ls);  /* skip 2nd `[' */
-          cont++;
-#if LUA_COMPAT_LSTR == 1
-          if (sep == 0)
-            luaX_lexerror(ls, "nesting of [[...]] is deprecated", '[');
-#endif
-        }
-        break;
-      }
-#endif
-      case ']': {
-        if (skip_sep(ls) == sep) {
-          save_and_next(ls);  /* skip 2nd `]' */
-#if defined(LUA_COMPAT_LSTR) && LUA_COMPAT_LSTR == 2
-          cont--;
-          if (sep == 0 && cont >= 0) break;
-#endif
-          goto endloop;
-        }
-        break;
-      }
-      case '\n':
-      case '\r': {
-        save(ls, '\n');
-        inclinenumber(ls);
-        if (!seminfo) luaZ_resetbuffer(ls->buff);  /* avoid wasting space */
-        break;
-      }
-      default: {
-        if (seminfo) save_and_next(ls);
-        else next(ls);
-      }
-    }
-  } endloop:
-  if (seminfo)
-    seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + (2 + sep),
-                                     luaZ_bufflen(ls->buff) - 2*(2 + sep));
-}
-
-
-static void read_string (LexState *ls, int del, SemInfo *seminfo) {
-  save_and_next(ls);
-  while (ls->current != del) {
-    switch (ls->current) {
-      case EOZ:
-        luaX_lexerror(ls, "unfinished string", TK_EOS);
-        continue;  /* to avoid warnings */
-      case '\n':
-      case '\r':
-        luaX_lexerror(ls, "unfinished string", TK_STRING);
-        continue;  /* to avoid warnings */
-      case '\\': {
-        int c;
-        next(ls);  /* do not save the `\' */
-        switch (ls->current) {
-          case 'a': c = '\a'; break;
-          case 'b': c = '\b'; break;
-          case 'f': c = '\f'; break;
-          case 'n': c = '\n'; break;
-          case 'r': c = '\r'; break;
-          case 't': c = '\t'; break;
-          case 'v': c = '\v'; break;
-          case '\n':  /* go through */
-          case '\r': save(ls, '\n'); inclinenumber(ls); continue;
-          case EOZ: continue;  /* will raise an error next loop */
-          default: {
-            if (!isdigit(ls->current))
-              save_and_next(ls);  /* handles \\, \", \', and \? */
-            else {  /* \xxx */
-              int i = 0;
-              c = 0;
-              do {
-                c = 10*c + (ls->current-'0');
-                next(ls);
-              } while (++i<3 && isdigit(ls->current));
-              if (c > UCHAR_MAX)
-                luaX_lexerror(ls, "escape sequence too large", TK_STRING);
-              save(ls, c);
-            }
-            continue;
-          }
-        }
-        save(ls, c);
-        next(ls);
-        continue;
-      }
-      default:
-        save_and_next(ls);
-    }
-  }
-  save_and_next(ls);  /* skip delimiter */
-  seminfo->ts = luaX_newstring(ls, luaZ_buffer(ls->buff) + 1,
-                                   luaZ_bufflen(ls->buff) - 2);
-}
-
-
-static int llex (LexState *ls, SemInfo *seminfo) {
-  luaZ_resetbuffer(ls->buff);
-  for (;;) {
-    switch (ls->current) {
-      case '\n':
-      case '\r': {
-        inclinenumber(ls);
-        continue;
-      }
-      case '-': {
-        next(ls);
-        if (ls->current != '-') return '-';
-        /* else is a comment */
-        next(ls);
-        if (ls->current == '[') {
-          int sep = skip_sep(ls);
-          luaZ_resetbuffer(ls->buff);  /* `skip_sep' may dirty the buffer */
-          if (sep >= 0) {
-            read_long_string(ls, NULL, sep);  /* long comment */
-            luaZ_resetbuffer(ls->buff);
-            continue;
-          }
-        }
-        /* else short comment */
-        while (!currIsNewline(ls) && ls->current != EOZ)
-          next(ls);
-        continue;
-      }
-      case '[': {
-        int sep = skip_sep(ls);
-        if (sep >= 0) {
-          read_long_string(ls, seminfo, sep);
-          return TK_STRING;
-        }
-        else if (sep == -1) return '[';
-        else luaX_lexerror(ls, "invalid long string delimiter", TK_STRING);
-      }
-      case '=': {
-        next(ls);
-        if (ls->current != '=') return '=';
-        else { next(ls); return TK_EQ; }
-      }
-      case '<': {
-        next(ls);
-        if (ls->current != '=') return '<';
-        else { next(ls); return TK_LE; }
-      }
-      case '>': {
-        next(ls);
-        if (ls->current != '=') return '>';
-        else { next(ls); return TK_GE; }
-      }
-      case '~': {
-        next(ls);
-        if (ls->current != '=') return '~';
-        else { next(ls); return TK_NE; }
-      }
-      case '"':
-      case '\'': {
-        read_string(ls, ls->current, seminfo);
-        return TK_STRING;
-      }
-      case '.': {
-        save_and_next(ls);
-        if (check_next(ls, ".")) {
-          if (check_next(ls, "."))
-            return TK_DOTS;   /* ... */
-          else return TK_CONCAT;   /* .. */
-        }
-        else if (!isdigit(ls->current)) return '.';
-        else {
-          read_numeral(ls, seminfo);
-          return TK_NUMBER;
-        }
-      }
-      case EOZ: {
-        return TK_EOS;
-      }
-      default: {
-        if (isspace(ls->current)) {
-          lua_assert(!currIsNewline(ls));
-          next(ls);
-          continue;
-        }
-        else if (isdigit(ls->current)) {
-          read_numeral(ls, seminfo);
-          return TK_NUMBER;
-        }
-        else if (isalpha(ls->current) || ls->current == '_') {
-          /* identifier or reserved word */
-          TString *ts;
-          int i;
-          do {
-            save_and_next(ls);
-          } while (isalnum(ls->current) || ls->current == '_');
-          /* look for reserved word */
-          save(ls, '\0');
-          for (i = 0; i < NUM_RESERVED; i++)
-            if (!strcmp(luaX_tokens[i], luaZ_buffer(ls->buff)))
-              return i + FIRST_RESERVED;
-          ts = luaX_newstring(ls, luaZ_buffer(ls->buff),
-                                  luaZ_bufflen(ls->buff) - 1);
-          seminfo->ts = ts;
-          return TK_NAME;
-        }
-        else {
-          int c = ls->current;
-          next(ls);
-          return c;  /* single-char tokens (+ - / ...) */
-        }
-      }
-    }
-  }
-}
-
-
-void luaX_next (LexState *ls) {
-  ls->lastline = ls->linenumber;
-  if (ls->lookahead.token != TK_EOS) {  /* is there a look-ahead token? */
-    ls->t = ls->lookahead;  /* use this one */
-    ls->lookahead.token = TK_EOS;  /* and discharge it */
-  }
-  else
-    ls->t.token = llex(ls, &ls->t.seminfo);  /* read next token */
-}
-
-
-void luaX_lookahead (LexState *ls) {
-  lua_assert(ls->lookahead.token == TK_EOS);
-  ls->lookahead.token = llex(ls, &ls->lookahead.seminfo);
-}
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/llex.h
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/llex.h b/libs/elua/elua_base/src/llex.h
deleted file mode 100644
index a9201ce..0000000
--- a/libs/elua/elua_base/src/llex.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
-** $Id: llex.h,v 1.58.1.1 2007/12/27 13:02:25 roberto Exp $
-** Lexical Analyzer
-** See Copyright Notice in lua.h
-*/
-
-#ifndef llex_h
-#define llex_h
-
-#include "lobject.h"
-#include "lzio.h"
-
-
-#define FIRST_RESERVED	257
-
-/* maximum length of a reserved word */
-#define TOKEN_LEN	(sizeof("function")/sizeof(char))
-
-
-/*
-* WARNING: if you change the order of this enumeration,
-* grep "ORDER RESERVED"
-*/
-enum RESERVED {
-  /* terminal symbols denoted by reserved words */
-  TK_AND = FIRST_RESERVED, TK_BREAK,
-  TK_DO, TK_ELSE, TK_ELSEIF, TK_END, TK_FALSE, TK_FOR, TK_FUNCTION,
-  TK_IF, TK_IN, TK_LOCAL, TK_NIL, TK_NOT, TK_OR, TK_REPEAT,
-  TK_RETURN, TK_THEN, TK_TRUE, TK_UNTIL, TK_WHILE,
-  /* other terminal symbols */
-  TK_CONCAT, TK_DOTS, TK_EQ, TK_GE, TK_LE, TK_NE, TK_NUMBER,
-  TK_NAME, TK_STRING, TK_EOS
-};
-
-/* number of reserved words */
-#define NUM_RESERVED	(cast(int, TK_WHILE-FIRST_RESERVED+1))
-
-
-/* array with token `names' */
-LUAI_DATA const char *const luaX_tokens [];
-
-
-typedef union {
-  lua_Number r;
-  TString *ts;
-} SemInfo;  /* semantics information */
-
-
-typedef struct Token {
-  int token;
-  SemInfo seminfo;
-} Token;
-
-
-typedef struct LexState {
-  int current;  /* current character (charint) */
-  int linenumber;  /* input line counter */
-  int lastline;  /* line of last token `consumed' */
-  Token t;  /* current token */
-  Token lookahead;  /* look ahead token */
-  struct FuncState *fs;  /* `FuncState' is private to the parser */
-  struct lua_State *L;
-  ZIO *z;  /* input stream */
-  Mbuffer *buff;  /* buffer for tokens */
-  TString *source;  /* current source name */
-  char decpoint;  /* locale decimal point */
-} LexState;
-
-
-LUAI_FUNC void luaX_init (lua_State *L);
-LUAI_FUNC void luaX_setinput (lua_State *L, LexState *ls, ZIO *z,
-                              TString *source);
-LUAI_FUNC TString *luaX_newstring (LexState *ls, const char *str, size_t l);
-LUAI_FUNC void luaX_next (LexState *ls);
-LUAI_FUNC void luaX_lookahead (LexState *ls);
-LUAI_FUNC void luaX_lexerror (LexState *ls, const char *msg, int token);
-LUAI_FUNC void luaX_syntaxerror (LexState *ls, const char *s);
-LUAI_FUNC const char *luaX_token2str (LexState *ls, int token);
-
-
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/llimits.h
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/llimits.h b/libs/elua/elua_base/src/llimits.h
deleted file mode 100644
index ca8dcb7..0000000
--- a/libs/elua/elua_base/src/llimits.h
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
-** $Id: llimits.h,v 1.69.1.1 2007/12/27 13:02:25 roberto Exp $
-** Limits, basic types, and some other `installation-dependent' definitions
-** See Copyright Notice in lua.h
-*/
-
-#ifndef llimits_h
-#define llimits_h
-
-
-#include <limits.h>
-#include <stddef.h>
-
-
-#include "lua.h"
-
-
-typedef LUAI_UINT32 lu_int32;
-
-typedef LUAI_UMEM lu_mem;
-
-typedef LUAI_MEM l_mem;
-
-
-
-/* chars used as small naturals (so that `char' is reserved for characters) */
-typedef unsigned char lu_byte;
-
-
-#define MAX_SIZET	((size_t)(~(size_t)0)-2)
-
-#define MAX_LUMEM	((lu_mem)(~(lu_mem)0)-2)
-
-
-#define MAX_INT (INT_MAX-2)  /* maximum value of an int (-2 for safety) */
-
-/*
-** conversion of pointer to integer
-** this is for hashing only; there is no problem if the integer
-** cannot hold the whole pointer value
-*/
-#define IntPoint(p)  ((unsigned int)(lu_mem)(p))
-
-
-
-/* type to ensure maximum alignment */
-typedef LUAI_USER_ALIGNMENT_T L_Umaxalign;
-
-
-/* result of a `usual argument conversion' over lua_Number */
-typedef LUAI_UACNUMBER l_uacNumber;
-
-
-/* internal assertions for in-house debugging */
-#ifdef lua_assert
-
-#define check_exp(c,e)		(lua_assert(c), (e))
-#define api_check(l,e)		lua_assert(e)
-
-#else
-
-#define lua_assert(c)		((void)0)
-#define check_exp(c,e)		(e)
-#define api_check		luai_apicheck
-
-#endif
-
-
-#ifndef UNUSED
-#define UNUSED(x)	((void)(x))	/* to avoid warnings */
-#endif
-
-
-#ifndef cast
-#define cast(t, exp)	((t)(exp))
-#endif
-
-#define cast_byte(i)	cast(lu_byte, (i))
-#define cast_num(i)	cast(lua_Number, (i))
-#define cast_int(i)	cast(int, (i))
-
-
-
-/*
-** type for virtual-machine instructions
-** must be an unsigned with (at least) 4 bytes (see details in lopcodes.h)
-*/
-typedef lu_int32 Instruction;
-
-
-
-/* maximum stack for a Lua function */
-#define MAXSTACK	250
-
-
-
-/* minimum size for the string table (must be power of 2) */
-#ifndef MINSTRTABSIZE
-#define MINSTRTABSIZE	32
-#endif
-
-
-/* minimum size for string buffer */
-#ifndef LUA_MINBUFFER
-#define LUA_MINBUFFER	32
-#endif
-
-
-#ifndef lua_lock
-#define lua_lock(L)     ((void) 0) 
-#define lua_unlock(L)   ((void) 0)
-#endif
-
-#ifndef luai_threadyield
-#define luai_threadyield(L)     {lua_unlock(L); lua_lock(L);}
-#endif
-
-
-/*
-** macro to control inclusion of some hard tests on stack reallocation
-*/ 
-#ifndef HARDSTACKTESTS
-#define condhardstacktests(x)	((void)0)
-#else
-#define condhardstacktests(x)	x
-#endif
-
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/lmathlib.c
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/lmathlib.c b/libs/elua/elua_base/src/lmathlib.c
deleted file mode 100644
index dff103e..0000000
--- a/libs/elua/elua_base/src/lmathlib.c
+++ /dev/null
@@ -1,395 +0,0 @@
-/*
-** $Id: lmathlib.c,v 1.67.1.1 2007/12/27 13:02:25 roberto Exp $
-** Standard mathematical library
-** See Copyright Notice in lua.h
-*/
-
-
-#include <stdlib.h>
-#include <math.h>
-
-#define lmathlib_c
-#define LUA_LIB
-
-#include "lua.h"
-
-#include "lauxlib.h"
-#include "lualib.h"
-#include "lrotable.h"
-
-#undef PI
-#define PI (3.14159265358979323846)
-#define RADIANS_PER_DEGREE (PI/180.0)
-
-
-
-static int math_abs (lua_State *L) {
-#ifdef LUA_NUMBER_INTEGRAL
-  lua_Number x = luaL_checknumber(L, 1);
-  if (x < 0) x = -x;	//fails for -2^31
-  lua_pushnumber(L, x);
-#else
-  lua_pushnumber(L, fabs(luaL_checknumber(L, 1)));
-#endif
-  return 1;
-}
-
-#ifndef LUA_NUMBER_INTEGRAL
-
-static int math_sin (lua_State *L) {
-  lua_pushnumber(L, sin(luaL_checknumber(L, 1)));
-  return 1;
-}
-
-static int math_sinh (lua_State *L) {
-  lua_pushnumber(L, sinh(luaL_checknumber(L, 1)));
-  return 1;
-}
-
-static int math_cos (lua_State *L) {
-  lua_pushnumber(L, cos(luaL_checknumber(L, 1)));
-  return 1;
-}
-
-static int math_cosh (lua_State *L) {
-  lua_pushnumber(L, cosh(luaL_checknumber(L, 1)));
-  return 1;
-}
-
-static int math_tan (lua_State *L) {
-  lua_pushnumber(L, tan(luaL_checknumber(L, 1)));
-  return 1;
-}
-
-static int math_tanh (lua_State *L) {
-  lua_pushnumber(L, tanh(luaL_checknumber(L, 1)));
-  return 1;
-}
-
-static int math_asin (lua_State *L) {
-  lua_pushnumber(L, asin(luaL_checknumber(L, 1)));
-  return 1;
-}
-
-static int math_acos (lua_State *L) {
-  lua_pushnumber(L, acos(luaL_checknumber(L, 1)));
-  return 1;
-}
-
-static int math_atan (lua_State *L) {
-  lua_pushnumber(L, atan(luaL_checknumber(L, 1)));
-  return 1;
-}
-
-static int math_atan2 (lua_State *L) {
-  lua_pushnumber(L, atan2(luaL_checknumber(L, 1), luaL_checknumber(L, 2)));
-  return 1;
-}
-
-static int math_ceil (lua_State *L) {
-  lua_pushnumber(L, ceil(luaL_checknumber(L, 1)));
-  return 1;
-}
-
-static int math_floor (lua_State *L) {
-  lua_pushnumber(L, floor(luaL_checknumber(L, 1)));
-  return 1;
-}
-
-static int math_fmod (lua_State *L) {
-  lua_pushnumber(L, fmod(luaL_checknumber(L, 1), luaL_checknumber(L, 2)));
-  return 1;
-}
-
-static int math_modf (lua_State *L) {
-  double ip;
-  double fp = modf(luaL_checknumber(L, 1), &ip);
-  lua_pushnumber(L, ip);
-  lua_pushnumber(L, fp);
-  return 2;
-}
-
-#else  // #ifndef LUA_NUMBER_INTEGRAL
-
-// In integer math, floor() and ceil() give the same value;
-// having them in the integer library allows you to write code that
-// works in both integer and floating point versions of Lua.
-// This identity function is used for them.
-
-static int math_identity (lua_State *L) {
-  lua_pushnumber(L, luaL_checknumber(L, 1));
-  return 1;
-}
-
-#endif // #ifndef LUA_NUMBER_INTEGRAL
-
-#ifdef LUA_NUMBER_INTEGRAL
-// Integer square root for integer version
-static lua_Number isqrt(lua_Number x)
-{
-  lua_Number op, res, one;
-
-  op = x; res = 0;
-
-  /* "one" starts at the highest power of four <= than the argument. */
-  one = 1 << 30;  /* second-to-top bit set */
-  while (one > op) one >>= 2;
-
-  while (one != 0) {
-    if (op >= res + one) {
-      op = op - (res + one);
-      res = res +  2 * one;
-    }
-    res >>= 1;
-    one >>= 2;
-  }
-  return(res);
-}
-#endif
-
-static int math_sqrt (lua_State *L) {
-#ifdef LUA_NUMBER_INTEGRAL
-  lua_Number x = luaL_checknumber(L, 1);
-  luaL_argcheck(L, 0<=x, 1, "negative");
-  lua_pushnumber(L, isqrt(x));
-#else
-  lua_pushnumber(L, sqrt(luaL_checknumber(L, 1)));
-#endif
-  return 1;
-}
-
-#ifdef LUA_NUMBER_INTEGRAL
-extern LUA_NUMBER luai_ipow(LUA_NUMBER a, LUA_NUMBER b);
-# define pow(a,b) luai_ipow(a,b)
-#endif
-
-static int math_pow (lua_State *L) {
-  lua_pushnumber(L, pow(luaL_checknumber(L, 1), luaL_checknumber(L, 2)));
-  return 1;
-}
-
-#ifdef LUA_NUMBER_INTEGRAL
-# undef pow
-#endif
-
-
-#ifndef LUA_NUMBER_INTEGRAL
-
-static int math_log (lua_State *L) {
-  lua_pushnumber(L, log(luaL_checknumber(L, 1)));
-  return 1;
-}
-
-static int math_log10 (lua_State *L) {
-  lua_pushnumber(L, log10(luaL_checknumber(L, 1)));
-  return 1;
-}
-
-static int math_exp (lua_State *L) {
-  lua_pushnumber(L, exp(luaL_checknumber(L, 1)));
-  return 1;
-}
-
-static int math_deg (lua_State *L) {
-  lua_pushnumber(L, luaL_checknumber(L, 1)/RADIANS_PER_DEGREE);
-  return 1;
-}
-
-static int math_rad (lua_State *L) {
-  lua_pushnumber(L, luaL_checknumber(L, 1)*RADIANS_PER_DEGREE);
-  return 1;
-}
-
-static int math_frexp (lua_State *L) {
-  int e;
-  lua_pushnumber(L, frexp(luaL_checknumber(L, 1), &e));
-  lua_pushinteger(L, e);
-  return 2;
-}
-
-static int math_ldexp (lua_State *L) {
-  lua_pushnumber(L, ldexp(luaL_checknumber(L, 1), luaL_checkint(L, 2)));
-  return 1;
-}
-
-#endif // #ifdef LUA_NUMBER_INTEGRAL
-
-static int math_min (lua_State *L) {
-  int n = lua_gettop(L);  /* number of arguments */
-  lua_Number dmin = luaL_checknumber(L, 1);
-  int i;
-  for (i=2; i<=n; i++) {
-    lua_Number d = luaL_checknumber(L, i);
-    if (d < dmin)
-      dmin = d;
-  }
-  lua_pushnumber(L, dmin);
-  return 1;
-}
-
-
-static int math_max (lua_State *L) {
-  int n = lua_gettop(L);  /* number of arguments */
-  lua_Number dmax = luaL_checknumber(L, 1);
-  int i;
-  for (i=2; i<=n; i++) {
-    lua_Number d = luaL_checknumber(L, i);
-    if (d > dmax)
-      dmax = d;
-  }
-  lua_pushnumber(L, dmax);
-  return 1;
-}
-
-
-#ifdef LUA_NUMBER_INTEGRAL
-
-static int math_random (lua_State *L) {
-  lua_Number r = (lua_Number)(rand()%RAND_MAX);
-
-  switch (lua_gettop(L)) {  /* check number of arguments */
-    case 0: {  /* no arguments */
-      lua_pushnumber(L, 0);  /* Number between 0 and 1 - always 0 with ints */
-      break;
-    }
-    case 1: {  /* only upper limit */
-      int u = luaL_checkint(L, 1);
-      luaL_argcheck(L, 1<=u, 1, "interval is empty");
-      lua_pushnumber(L, (r % u)+1);  /* int between 1 and `u' */
-      break;
-    }
-    case 2: {  /* lower and upper limits */
-      int l = luaL_checkint(L, 1);
-      int u = luaL_checkint(L, 2);
-      luaL_argcheck(L, l<=u, 2, "interval is empty");
-      lua_pushnumber(L, (r%(u-l+1))+l);  /* int between `l' and `u' */
-      break;
-    }
-    default: return luaL_error(L, "wrong number of arguments");
-  }
-  return 1;
-}
-
-#else
-
-static int math_random (lua_State *L) {
-  /* the `%' avoids the (rare) case of r==1, and is needed also because on
-     some systems (SunOS!) `rand()' may return a value larger than RAND_MAX */
-  lua_Number r = (lua_Number)(rand()%RAND_MAX) / (lua_Number)RAND_MAX;
-  switch (lua_gettop(L)) {  /* check number of arguments */
-    case 0: {  /* no arguments */
-      lua_pushnumber(L, r);  /* Number between 0 and 1 */
-      break;
-    }
-    case 1: {  /* only upper limit */
-      int u = luaL_checkint(L, 1);
-      luaL_argcheck(L, 1<=u, 1, "interval is empty");
-      lua_pushnumber(L, floor(r*u)+1);  /* int between 1 and `u' */
-      break;
-    }
-    case 2: {  /* lower and upper limits */
-      int l = luaL_checkint(L, 1);
-      int u = luaL_checkint(L, 2);
-      luaL_argcheck(L, l<=u, 2, "interval is empty");
-      lua_pushnumber(L, floor(r*(u-l+1))+l);  /* int between `l' and `u' */
-      break;
-    }
-    default: return luaL_error(L, "wrong number of arguments");
-  }
-  return 1;
-}
-
-#endif
-
-
-static int math_randomseed (lua_State *L) {
-  srand(luaL_checkint(L, 1));
-  return 0;
-}
-
-#define MIN_OPT_LEVEL 1
-#include "lrodefs.h"
-const LUA_REG_TYPE math_map[] = {
-#ifdef LUA_NUMBER_INTEGRAL
-  {LSTRKEY("abs"),   LFUNCVAL(math_abs)},
-  {LSTRKEY("ceil"),  LFUNCVAL(math_identity)},
-  {LSTRKEY("floor"), LFUNCVAL(math_identity)},
-  {LSTRKEY("max"),   LFUNCVAL(math_max)},
-  {LSTRKEY("min"),   LFUNCVAL(math_min)},
-  {LSTRKEY("pow"),   LFUNCVAL(math_pow)},
-  {LSTRKEY("random"),     LFUNCVAL(math_random)},
-  {LSTRKEY("randomseed"), LFUNCVAL(math_randomseed)},
-  {LSTRKEY("sqrt"),  LFUNCVAL(math_sqrt)},
-#if LUA_OPTIMIZE_MEMORY > 0
-  {LSTRKEY("huge"),  LNUMVAL(LONG_MAX)},
-#endif
-#else
-  {LSTRKEY("abs"),   LFUNCVAL(math_abs)},
-  {LSTRKEY("acos"),  LFUNCVAL(math_acos)},
-  {LSTRKEY("asin"),  LFUNCVAL(math_asin)},
-  {LSTRKEY("atan2"), LFUNCVAL(math_atan2)},
-  {LSTRKEY("atan"),  LFUNCVAL(math_atan)},
-  {LSTRKEY("ceil"),  LFUNCVAL(math_ceil)},
-  {LSTRKEY("cosh"),  LFUNCVAL(math_cosh)},
-  {LSTRKEY("cos"),   LFUNCVAL(math_cos)},
-  {LSTRKEY("deg"),   LFUNCVAL(math_deg)},
-  {LSTRKEY("exp"),   LFUNCVAL(math_exp)},
-  {LSTRKEY("floor"), LFUNCVAL(math_floor)},
-  {LSTRKEY("fmod"),  LFUNCVAL(math_fmod)},
-#if LUA_OPTIMIZE_MEMORY > 0 && defined(LUA_COMPAT_MOD)
-  {LSTRKEY("mod"),   LFUNCVAL(math_fmod)}, 
-#endif
-  {LSTRKEY("frexp"), LFUNCVAL(math_frexp)},
-  {LSTRKEY("ldexp"), LFUNCVAL(math_ldexp)},
-  {LSTRKEY("log10"), LFUNCVAL(math_log10)},
-  {LSTRKEY("log"),   LFUNCVAL(math_log)},
-  {LSTRKEY("max"),   LFUNCVAL(math_max)},
-  {LSTRKEY("min"),   LFUNCVAL(math_min)},
-  {LSTRKEY("modf"),   LFUNCVAL(math_modf)},
-  {LSTRKEY("pow"),   LFUNCVAL(math_pow)},
-  {LSTRKEY("rad"),   LFUNCVAL(math_rad)},
-  {LSTRKEY("random"),     LFUNCVAL(math_random)},
-  {LSTRKEY("randomseed"), LFUNCVAL(math_randomseed)},
-  {LSTRKEY("sinh"),   LFUNCVAL(math_sinh)},
-  {LSTRKEY("sin"),   LFUNCVAL(math_sin)},
-  {LSTRKEY("sqrt"),  LFUNCVAL(math_sqrt)},
-  {LSTRKEY("tanh"),   LFUNCVAL(math_tanh)},
-  {LSTRKEY("tan"),   LFUNCVAL(math_tan)},
-#if LUA_OPTIMIZE_MEMORY > 0
-  {LSTRKEY("pi"),    LNUMVAL(PI)},
-  {LSTRKEY("huge"),  LNUMVAL(HUGE_VAL)},
-#endif // #if LUA_OPTIMIZE_MEMORY > 0
-#endif // #ifdef LUA_NUMBER_INTEGRAL
-  {LNILKEY, LNILVAL}
-};
-
-
-/*
-** Open math library
-*/
-
-#if defined LUA_NUMBER_INTEGRAL
-# include <limits.h>		/* for LONG_MAX */
-#endif
-
-LUALIB_API int luaopen_math (lua_State *L) {
-#if LUA_OPTIMIZE_MEMORY > 0
-  return 0;
-#else
-  luaL_register(L, LUA_MATHLIBNAME, math_map);
-# if defined LUA_NUMBER_INTEGRAL
-  lua_pushnumber(L, LONG_MAX);
-  lua_setfield(L, -2, "huge");
-# else
-  lua_pushnumber(L, PI);
-  lua_setfield(L, -2, "pi");
-  lua_pushnumber(L, HUGE_VAL);
-  lua_setfield(L, -2, "huge");
-#  if defined(LUA_COMPAT_MOD)
-  lua_getfield(L, -1, "fmod");
-  lua_setfield(L, -2, "mod");
-#  endif
-# endif
-  return 1;
-#endif
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/lmem.c
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/lmem.c b/libs/elua/elua_base/src/lmem.c
deleted file mode 100644
index ae7d8c9..0000000
--- a/libs/elua/elua_base/src/lmem.c
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
-** $Id: lmem.c,v 1.70.1.1 2007/12/27 13:02:25 roberto Exp $
-** Interface to Memory Manager
-** See Copyright Notice in lua.h
-*/
-
-
-#include <stddef.h>
-
-#define lmem_c
-#define LUA_CORE
-
-#include "lua.h"
-
-#include "ldebug.h"
-#include "ldo.h"
-#include "lmem.h"
-#include "lobject.h"
-#include "lstate.h"
-
-
-
-/*
-** About the realloc function:
-** void * frealloc (void *ud, void *ptr, size_t osize, size_t nsize);
-** (`osize' is the old size, `nsize' is the new size)
-**
-** Lua ensures that (ptr == NULL) iff (osize == 0).
-**
-** * frealloc(ud, NULL, 0, x) creates a new block of size `x'
-**
-** * frealloc(ud, p, x, 0) frees the block `p'
-** (in this specific case, frealloc must return NULL).
-** particularly, frealloc(ud, NULL, 0, 0) does nothing
-** (which is equivalent to free(NULL) in ANSI C)
-**
-** frealloc returns NULL if it cannot create or reallocate the area
-** (any reallocation to an equal or smaller size cannot fail!)
-*/
-
-
-
-#define MINSIZEARRAY	4
-
-
-void *luaM_growaux_ (lua_State *L, void *block, int *size, size_t size_elems,
-                     int limit, const char *errormsg) {
-  void *newblock;
-  int newsize;
-  if (*size >= limit/2) {  /* cannot double it? */
-    if (*size >= limit)  /* cannot grow even a little? */
-      luaG_runerror(L, errormsg);
-    newsize = limit;  /* still have at least one free place */
-  }
-  else {
-    newsize = (*size)*2;
-    if (newsize < MINSIZEARRAY)
-      newsize = MINSIZEARRAY;  /* minimum size */
-  }
-  newblock = luaM_reallocv(L, block, *size, newsize, size_elems);
-  *size = newsize;  /* update only when everything else is OK */
-  return newblock;
-}
-
-
-void *luaM_toobig (lua_State *L) {
-  luaG_runerror(L, "memory allocation error: block too big");
-  return NULL;  /* to avoid warnings */
-}
-
-
-
-/*
-** generic allocation routine.
-*/
-void *luaM_realloc_ (lua_State *L, void *block, size_t osize, size_t nsize) {
-  global_State *g = G(L);
-  lua_assert((osize == 0) == (block == NULL));
-  block = (*g->frealloc)(g->ud, block, osize, nsize);
-  if (block == NULL && nsize > 0)
-    luaD_throw(L, LUA_ERRMEM);
-  lua_assert((nsize == 0) == (block == NULL));
-  g->totalbytes = (g->totalbytes - osize) + nsize;
-  return block;
-}
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/lmem.h
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/lmem.h b/libs/elua/elua_base/src/lmem.h
deleted file mode 100644
index 7c2dcb3..0000000
--- a/libs/elua/elua_base/src/lmem.h
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
-** $Id: lmem.h,v 1.31.1.1 2007/12/27 13:02:25 roberto Exp $
-** Interface to Memory Manager
-** See Copyright Notice in lua.h
-*/
-
-#ifndef lmem_h
-#define lmem_h
-
-
-#include <stddef.h>
-
-#include "llimits.h"
-#include "lua.h"
-
-#define MEMERRMSG	"not enough memory"
-
-
-#define luaM_reallocv(L,b,on,n,e) \
-	((cast(size_t, (n)+1) <= MAX_SIZET/(e)) ?  /* +1 to avoid warnings */ \
-		luaM_realloc_(L, (b), (on)*(e), (n)*(e)) : \
-		luaM_toobig(L))
-
-#define luaM_freemem(L, b, s)	luaM_realloc_(L, (b), (s), 0)
-#define luaM_free(L, b)		luaM_realloc_(L, (b), sizeof(*(b)), 0)
-#define luaM_freearray(L, b, n, t)   luaM_reallocv(L, (b), n, 0, sizeof(t))
-
-#define luaM_malloc(L,t)	luaM_realloc_(L, NULL, 0, (t))
-#define luaM_new(L,t)		cast(t *, luaM_malloc(L, sizeof(t)))
-#define luaM_newvector(L,n,t) \
-		cast(t *, luaM_reallocv(L, NULL, 0, n, sizeof(t)))
-
-#define luaM_growvector(L,v,nelems,size,t,limit,e) \
-          if ((nelems)+1 > (size)) \
-            ((v)=cast(t *, luaM_growaux_(L,v,&(size),sizeof(t),limit,e)))
-
-#define luaM_reallocvector(L, v,oldn,n,t) \
-   ((v)=cast(t *, luaM_reallocv(L, v, oldn, n, sizeof(t))))
-
-
-LUAI_FUNC void *luaM_realloc_ (lua_State *L, void *block, size_t oldsize,
-                                                          size_t size);
-LUAI_FUNC void *luaM_toobig (lua_State *L);
-LUAI_FUNC void *luaM_growaux_ (lua_State *L, void *block, int *size,
-                               size_t size_elem, int limit,
-                               const char *errormsg);
-
-#endif
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/lmynewt.c
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/lmynewt.c b/libs/elua/elua_base/src/lmynewt.c
deleted file mode 100644
index bf40a2e..0000000
--- a/libs/elua/elua_base/src/lmynewt.c
+++ /dev/null
@@ -1,56 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include <assert.h>
-#include "sysinit/sysinit.h"
-#include "syscfg/syscfg.h"
-#include "shell/shell.h"
-#include "elua_base/elua.h"
-
-#ifdef MYNEWT
-
-#if MYNEWT_VAL(ELUA_CLI)
-static int lua_cmd(int argc, char **argv);
-
-static struct shell_cmd lua_shell_cmd = {
-    .sc_cmd = "lua",
-    .sc_cmd_func = lua_cmd
-};
-
-static int
-lua_cmd(int argc, char **argv)
-{
-    lua_main(argc, argv);
-    return 0;
-}
-#endif
-
-void
-lua_init(void)
-{
-    int rc;
-
-    (void)rc;
-
-#if MYNEWT_VAL(ELUA_CLI)
-    rc = shell_cmd_register(&lua_shell_cmd);
-    SYSINIT_PANIC_ASSERT(rc == 0);
-#endif
-}
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/loadlib.c.donotcompile
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/loadlib.c.donotcompile b/libs/elua/elua_base/src/loadlib.c.donotcompile
deleted file mode 100644
index 3513245..0000000
--- a/libs/elua/elua_base/src/loadlib.c.donotcompile
+++ /dev/null
@@ -1,684 +0,0 @@
-/*
-** $Id: loadlib.c,v 1.52.1.4 2009/09/09 13:17:16 roberto Exp $
-** Dynamic library loader for Lua
-** See Copyright Notice in lua.h
-**
-** This module contains an implementation of loadlib for Unix systems
-** that have dlfcn, an implementation for Darwin (Mac OS X), an
-** implementation for Windows, and a stub for other systems.
-*/
-
-
-#include <stdlib.h>
-#include <string.h>
-
-
-#define loadlib_c
-#define LUA_LIB
-
-#include "lua.h"
-
-#include "lauxlib.h"
-#include "lualib.h"
-#include "lrotable.h"
-
-/* prefix for open functions in C libraries */
-#define LUA_POF		"luaopen_"
-
-/* separator for open functions in C libraries */
-#define LUA_OFSEP	"_"
-
-
-#define LIBPREFIX	"LOADLIB: "
-
-#define POF		LUA_POF
-#define LIB_FAIL	"open"
-
-
-/* error codes for ll_loadfunc */
-#define ERRLIB		1
-#define ERRFUNC		2
-
-#define setprogdir(L)		((void)0)
-
-
-static void ll_unloadlib (void *lib);
-static void *ll_load (lua_State *L, const char *path);
-static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym);
-
-
-
-#if defined(LUA_DL_DLOPEN)
-/*
-** {========================================================================
-** This is an implementation of loadlib based on the dlfcn interface.
-** The dlfcn interface is available in Linux, SunOS, Solaris, IRIX, FreeBSD,
-** NetBSD, AIX 4.2, HPUX 11, and  probably most other Unix flavors, at least
-** as an emulation layer on top of native functions.
-** =========================================================================
-*/
-
-#include <dlfcn.h>
-
-static void ll_unloadlib (void *lib) {
-  dlclose(lib);
-}
-
-
-static void *ll_load (lua_State *L, const char *path) {
-  void *lib = dlopen(path, RTLD_NOW);
-  if (lib == NULL) lua_pushstring(L, dlerror());
-  return lib;
-}
-
-
-static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) {
-  lua_CFunction f = (lua_CFunction)dlsym(lib, sym);
-  if (f == NULL) lua_pushstring(L, dlerror());
-  return f;
-}
-
-/* }====================================================== */
-
-
-
-#elif defined(LUA_DL_DLL)
-/*
-** {======================================================================
-** This is an implementation of loadlib for Windows using native functions.
-** =======================================================================
-*/
-
-#include <windows.h>
-
-
-#undef setprogdir
-
-static void setprogdir (lua_State *L) {
-  char buff[MAX_PATH + 1];
-  char *lb;
-  DWORD nsize = sizeof(buff)/sizeof(char);
-  DWORD n = GetModuleFileNameA(NULL, buff, nsize);
-  if (n == 0 || n == nsize || (lb = strrchr(buff, '\\')) == NULL)
-    luaL_error(L, "unable to get ModuleFileName");
-  else {
-    *lb = '\0';
-    luaL_gsub(L, lua_tostring(L, -1), LUA_EXECDIR, buff);
-    lua_remove(L, -2);  /* remove original string */
-  }
-}
-
-
-static void pusherror (lua_State *L) {
-  int error = GetLastError();
-  char buffer[128];
-  if (FormatMessageA(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM,
-      NULL, error, 0, buffer, sizeof(buffer), NULL))
-    lua_pushstring(L, buffer);
-  else
-    lua_pushfstring(L, "system error %d\n", error);
-}
-
-static void ll_unloadlib (void *lib) {
-  FreeLibrary((HINSTANCE)lib);
-}
-
-
-static void *ll_load (lua_State *L, const char *path) {
-  HINSTANCE lib = LoadLibraryA(path);
-  if (lib == NULL) pusherror(L);
-  return lib;
-}
-
-
-static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) {
-  lua_CFunction f = (lua_CFunction)GetProcAddress((HINSTANCE)lib, sym);
-  if (f == NULL) pusherror(L);
-  return f;
-}
-
-/* }====================================================== */
-
-
-
-#elif defined(LUA_DL_DYLD)
-/*
-** {======================================================================
-** Native Mac OS X / Darwin Implementation
-** =======================================================================
-*/
-
-#include <mach-o/dyld.h>
-
-
-/* Mac appends a `_' before C function names */
-#undef POF
-#define POF	"_" LUA_POF
-
-
-static void pusherror (lua_State *L) {
-  const char *err_str;
-  const char *err_file;
-  NSLinkEditErrors err;
-  int err_num;
-  NSLinkEditError(&err, &err_num, &err_file, &err_str);
-  lua_pushstring(L, err_str);
-}
-
-
-static const char *errorfromcode (NSObjectFileImageReturnCode ret) {
-  switch (ret) {
-    case NSObjectFileImageInappropriateFile:
-      return "file is not a bundle";
-    case NSObjectFileImageArch:
-      return "library is for wrong CPU type";
-    case NSObjectFileImageFormat:
-      return "bad format";
-    case NSObjectFileImageAccess:
-      return "cannot access file";
-    case NSObjectFileImageFailure:
-    default:
-      return "unable to load library";
-  }
-}
-
-
-static void ll_unloadlib (void *lib) {
-  NSUnLinkModule((NSModule)lib, NSUNLINKMODULE_OPTION_RESET_LAZY_REFERENCES);
-}
-
-
-static void *ll_load (lua_State *L, const char *path) {
-  NSObjectFileImage img;
-  NSObjectFileImageReturnCode ret;
-  /* this would be a rare case, but prevents crashing if it happens */
-  if(!_dyld_present()) {
-    lua_pushliteral(L, "dyld not present");
-    return NULL;
-  }
-  ret = NSCreateObjectFileImageFromFile(path, &img);
-  if (ret == NSObjectFileImageSuccess) {
-    NSModule mod = NSLinkModule(img, path, NSLINKMODULE_OPTION_PRIVATE |
-                       NSLINKMODULE_OPTION_RETURN_ON_ERROR);
-    NSDestroyObjectFileImage(img);
-    if (mod == NULL) pusherror(L);
-    return mod;
-  }
-  lua_pushstring(L, errorfromcode(ret));
-  return NULL;
-}
-
-
-static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) {
-  NSSymbol nss = NSLookupSymbolInModule((NSModule)lib, sym);
-  if (nss == NULL) {
-    lua_pushfstring(L, "symbol " LUA_QS " not found", sym);
-    return NULL;
-  }
-  return (lua_CFunction)NSAddressOfSymbol(nss);
-}
-
-/* }====================================================== */
-
-
-
-#else
-/*
-** {======================================================
-** Fallback for other systems
-** =======================================================
-*/
-
-#undef LIB_FAIL
-#define LIB_FAIL	"absent"
-
-
-#define DLMSG	"dynamic libraries not enabled; check your Lua installation"
-
-
-static void ll_unloadlib (void *lib) {
-  (void)lib;  /* to avoid warnings */
-}
-
-
-static void *ll_load (lua_State *L, const char *path) {
-  (void)path;  /* to avoid warnings */
-  lua_pushliteral(L, DLMSG);
-  return NULL;
-}
-
-
-static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) {
-  (void)lib; (void)sym;  /* to avoid warnings */
-  lua_pushliteral(L, DLMSG);
-  return NULL;
-}
-
-/* }====================================================== */
-#endif
-
-
-
-static void **ll_register (lua_State *L, const char *path) {
-  void **plib;
-  lua_pushfstring(L, "%s%s", LIBPREFIX, path);
-  lua_gettable(L, LUA_REGISTRYINDEX);  /* check library in registry? */
-  if (!lua_isnil(L, -1))  /* is there an entry? */
-    plib = (void **)lua_touserdata(L, -1);
-  else {  /* no entry yet; create one */
-    lua_pop(L, 1);
-    plib = (void **)lua_newuserdata(L, sizeof(const void *));
-    *plib = NULL;
-    luaL_getmetatable(L, "_LOADLIB");
-    lua_setmetatable(L, -2);
-    lua_pushfstring(L, "%s%s", LIBPREFIX, path);
-    lua_pushvalue(L, -2);
-    lua_settable(L, LUA_REGISTRYINDEX);
-  }
-  return plib;
-}
-
-
-/*
-** __gc tag method: calls library's `ll_unloadlib' function with the lib
-** handle
-*/
-static int gctm (lua_State *L) {
-  void **lib = (void **)luaL_checkudata(L, 1, "_LOADLIB");
-  if (*lib) ll_unloadlib(*lib);
-  *lib = NULL;  /* mark library as closed */
-  return 0;
-}
-
-
-static int ll_loadfunc (lua_State *L, const char *path, const char *sym) {
-  void **reg = ll_register(L, path);
-  if (*reg == NULL) *reg = ll_load(L, path);
-  if (*reg == NULL)
-    return ERRLIB;  /* unable to load library */
-  else {
-    lua_CFunction f = ll_sym(L, *reg, sym);
-    if (f == NULL)
-      return ERRFUNC;  /* unable to find function */
-    lua_pushcfunction(L, f);
-    return 0;  /* return function */
-  }
-}
-
-
-static int ll_loadlib (lua_State *L) {
-  const char *path = luaL_checkstring(L, 1);
-  const char *init = luaL_checkstring(L, 2);
-  int stat = ll_loadfunc(L, path, init);
-  if (stat == 0)  /* no errors? */
-    return 1;  /* return the loaded function */
-  else {  /* error; error message is on stack top */
-    lua_pushnil(L);
-    lua_insert(L, -2);
-    lua_pushstring(L, (stat == ERRLIB) ?  LIB_FAIL : "init");
-    return 3;  /* return nil, error message, and where */
-  }
-}
-
-
-
-/*
-** {======================================================
-** 'require' function
-** =======================================================
-*/
-
-
-static int readable (const char *filename) {
-  FILE *f = fopen(filename, "r");  /* try to open file */
-  if (f == NULL) return 0;  /* open failed */
-  fclose(f);
-  return 1;
-}
-
-
-static const char *pushnexttemplate (lua_State *L, const char *path) {
-  const char *l;
-  while (*path == *LUA_PATHSEP) path++;  /* skip separators */
-  if (*path == '\0') return NULL;  /* no more templates */
-  l = strchr(path, *LUA_PATHSEP);  /* find next separator */
-  if (l == NULL) l = path + strlen(path);
-  lua_pushlstring(L, path, l - path);  /* template */
-  return l;
-}
-
-
-static const char *findfile (lua_State *L, const char *name,
-                                           const char *pname) {
-  const char *path;
-  name = luaL_gsub(L, name, ".", LUA_DIRSEP);
-  lua_getfield(L, LUA_ENVIRONINDEX, pname);
-  path = lua_tostring(L, -1);
-  if (path == NULL)
-    luaL_error(L, LUA_QL("package.%s") " must be a string", pname);
-  lua_pushliteral(L, "");  /* error accumulator */
-  while ((path = pushnexttemplate(L, path)) != NULL) {
-    const char *filename;
-    filename = luaL_gsub(L, lua_tostring(L, -1), LUA_PATH_MARK, name);
-    lua_remove(L, -2);  /* remove path template */
-    if (readable(filename))  /* does file exist and is readable? */
-      return filename;  /* return that file name */
-    lua_pushfstring(L, "\n\tno file " LUA_QS, filename);
-    lua_remove(L, -2);  /* remove file name */
-    lua_concat(L, 2);  /* add entry to possible error message */
-  }
-  return NULL;  /* not found */
-}
-
-
-static void loaderror (lua_State *L, const char *filename) {
-  luaL_error(L, "error loading module " LUA_QS " from file " LUA_QS ":\n\t%s",
-                lua_tostring(L, 1), filename, lua_tostring(L, -1));
-}
-
-
-static int loader_Lua (lua_State *L) {
-  const char *filename;
-  const char *name = luaL_checkstring(L, 1);
-  filename = findfile(L, name, "path");
-  if (filename == NULL) return 1;  /* library not found in this path */
-  if (luaL_loadfile(L, filename) != 0)
-    loaderror(L, filename);
-  return 1;  /* library loaded successfully */
-}
-
-
-static const char *mkfuncname (lua_State *L, const char *modname) {
-  const char *funcname;
-  const char *mark = strchr(modname, *LUA_IGMARK);
-  if (mark) modname = mark + 1;
-  funcname = luaL_gsub(L, modname, ".", LUA_OFSEP);
-  funcname = lua_pushfstring(L, POF"%s", funcname);
-  lua_remove(L, -2);  /* remove 'gsub' result */
-  return funcname;
-}
-
-
-static int loader_C (lua_State *L) {
-  const char *funcname;
-  const char *name = luaL_checkstring(L, 1);
-  const char *filename = findfile(L, name, "cpath");
-  if (filename == NULL) return 1;  /* library not found in this path */
-  funcname = mkfuncname(L, name);
-  if (ll_loadfunc(L, filename, funcname) != 0)
-    loaderror(L, filename);
-  return 1;  /* library loaded successfully */
-}
-
-
-static int loader_Croot (lua_State *L) {
-  const char *funcname;
-  const char *filename;
-  const char *name = luaL_checkstring(L, 1);
-  const char *p = strchr(name, '.');
-  int stat;
-  if (p == NULL) return 0;  /* is root */
-  lua_pushlstring(L, name, p - name);
-  filename = findfile(L, lua_tostring(L, -1), "cpath");
-  if (filename == NULL) return 1;  /* root not found */
-  funcname = mkfuncname(L, name);
-  if ((stat = ll_loadfunc(L, filename, funcname)) != 0) {
-    if (stat != ERRFUNC) loaderror(L, filename);  /* real error */
-    lua_pushfstring(L, "\n\tno module " LUA_QS " in file " LUA_QS,
-                       name, filename);
-    return 1;  /* function not found */
-  }
-  return 1;
-}
-
-
-static int loader_preload (lua_State *L) {
-  const char *name = luaL_checkstring(L, 1);
-  lua_getfield(L, LUA_ENVIRONINDEX, "preload");
-  if (!lua_istable(L, -1))
-    luaL_error(L, LUA_QL("package.preload") " must be a table");
-  lua_getfield(L, -1, name);
-  if (lua_isnil(L, -1))  /* not found? */
-    lua_pushfstring(L, "\n\tno field package.preload['%s']", name);
-  return 1;
-}
-
-
-static const int sentinel_ = 0;
-#define sentinel	((void *)&sentinel_)
-
-
-static int ll_require (lua_State *L) {
-  const char *name = luaL_checkstring(L, 1);
-  int i;
-  lua_settop(L, 1);  /* _LOADED table will be at index 2 */
-  lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
-  lua_getfield(L, 2, name);
-  if (lua_toboolean(L, -1)) {  /* is it there? */
-    if (lua_touserdata(L, -1) == sentinel)  /* check loops */
-      luaL_error(L, "loop or previous error loading module " LUA_QS, name);
-    return 1;  /* package is already loaded */
-  }
-  /* Is this a readonly table? */
-  void *res = luaR_findglobal(name, strlen(name));
-  if (res) {
-    lua_pushrotable(L, res);
-    return 1;
-  }
-  /* else must load it; iterate over available loaders */
-  lua_getfield(L, LUA_ENVIRONINDEX, "loaders");
-  if (!lua_istable(L, -1))
-    luaL_error(L, LUA_QL("package.loaders") " must be a table");
-  lua_pushliteral(L, "");  /* error message accumulator */
-  for (i=1; ; i++) {
-    lua_rawgeti(L, -2, i);  /* get a loader */
-    if (lua_isnil(L, -1))
-      luaL_error(L, "module " LUA_QS " not found:%s",
-                    name, lua_tostring(L, -2));
-    lua_pushstring(L, name);
-    lua_call(L, 1, 1);  /* call it */
-    if (lua_isfunction(L, -1))  /* did it find module? */
-      break;  /* module loaded successfully */
-    else if (lua_isstring(L, -1))  /* loader returned error message? */
-      lua_concat(L, 2);  /* accumulate it */
-    else
-      lua_pop(L, 1);
-  }
-  lua_pushlightuserdata(L, sentinel);
-  lua_setfield(L, 2, name);  /* _LOADED[name] = sentinel */
-  lua_pushstring(L, name);  /* pass name as argument to module */
-  lua_call(L, 1, 1);  /* run loaded module */
-  if (!lua_isnil(L, -1))  /* non-nil return? */
-    lua_setfield(L, 2, name);  /* _LOADED[name] = returned value */
-  lua_getfield(L, 2, name);
-  if (lua_touserdata(L, -1) == sentinel) {   /* module did not set a value? */
-    lua_pushboolean(L, 1);  /* use true as result */
-    lua_pushvalue(L, -1);  /* extra copy to be returned */
-    lua_setfield(L, 2, name);  /* _LOADED[name] = true */
-  }
-  return 1;
-}
-
-/* }====================================================== */
-
-
-
-/*
-** {======================================================
-** 'module' function
-** =======================================================
-*/
-  
-
-static void setfenv (lua_State *L) {
-  lua_Debug ar;
-  if (lua_getstack(L, 1, &ar) == 0 ||
-      lua_getinfo(L, "f", &ar) == 0 ||  /* get calling function */
-      lua_iscfunction(L, -1))
-    luaL_error(L, LUA_QL("module") " not called from a Lua function");
-  lua_pushvalue(L, -2);
-  lua_setfenv(L, -2);
-  lua_pop(L, 1);
-}
-
-
-static void dooptions (lua_State *L, int n) {
-  int i;
-  for (i = 2; i <= n; i++) {
-    lua_pushvalue(L, i);  /* get option (a function) */
-    lua_pushvalue(L, -2);  /* module */
-    lua_call(L, 1, 0);
-  }
-}
-
-
-static void modinit (lua_State *L, const char *modname) {
-  const char *dot;
-  lua_pushvalue(L, -1);
-  lua_setfield(L, -2, "_M");  /* module._M = module */
-  lua_pushstring(L, modname);
-  lua_setfield(L, -2, "_NAME");
-  dot = strrchr(modname, '.');  /* look for last dot in module name */
-  if (dot == NULL) dot = modname;
-  else dot++;
-  /* set _PACKAGE as package name (full module name minus last part) */
-  lua_pushlstring(L, modname, dot - modname);
-  lua_setfield(L, -2, "_PACKAGE");
-}
-
-
-static int ll_module (lua_State *L) {
-  const char *modname = luaL_checkstring(L, 1);
-  if (luaR_findglobal(modname, strlen(modname)))
-    return 0;
-  int loaded = lua_gettop(L) + 1;  /* index of _LOADED table */
-  lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
-  lua_getfield(L, loaded, modname);  /* get _LOADED[modname] */
-  if (!lua_istable(L, -1)) {  /* not found? */
-    lua_pop(L, 1);  /* remove previous result */
-    /* try global variable (and create one if it does not exist) */
-    if (luaL_findtable(L, LUA_GLOBALSINDEX, modname, 1) != NULL)
-      return luaL_error(L, "name conflict for module " LUA_QS, modname);
-    lua_pushvalue(L, -1);
-    lua_setfield(L, loaded, modname);  /* _LOADED[modname] = new table */
-  }
-  /* check whether table already has a _NAME field */
-  lua_getfield(L, -1, "_NAME");
-  if (!lua_isnil(L, -1))  /* is table an initialized module? */
-    lua_pop(L, 1);
-  else {  /* no; initialize it */
-    lua_pop(L, 1);
-    modinit(L, modname);
-  }
-  lua_pushvalue(L, -1);
-  setfenv(L);
-  dooptions(L, loaded - 1);
-  return 0;
-}
-
-
-static int ll_seeall (lua_State *L) {
-  luaL_checktype(L, 1, LUA_TTABLE);
-  if (!lua_getmetatable(L, 1)) {
-    lua_createtable(L, 0, 1); /* create new metatable */
-    lua_pushvalue(L, -1);
-    lua_setmetatable(L, 1);
-  }
-  lua_pushvalue(L, LUA_GLOBALSINDEX);
-  lua_setfield(L, -2, "__index");  /* mt.__index = _G */
-  return 0;
-}
-
-
-/* }====================================================== */
-
-
-
-/* auxiliary mark (for internal use) */
-#define AUXMARK		"\1"
-
-static void setpath (lua_State *L, const char *fieldname, const char *envname,
-                                   const char *def) {
-  const char *path = getenv(envname);
-  if (path == NULL)  /* no environment variable? */
-    lua_pushstring(L, def);  /* use default */
-  else {
-    /* replace ";;" by ";AUXMARK;" and then AUXMARK by default path */
-    path = luaL_gsub(L, path, LUA_PATHSEP LUA_PATHSEP,
-                              LUA_PATHSEP AUXMARK LUA_PATHSEP);
-    luaL_gsub(L, path, AUXMARK, def);
-    lua_remove(L, -2);
-  }
-  setprogdir(L);
-  lua_setfield(L, -2, fieldname);
-}
-
-
-static const luaL_Reg pk_funcs[] = {
-  {"loadlib", ll_loadlib},
-  {"seeall", ll_seeall},
-  {NULL, NULL}
-};
-
-
-static const luaL_Reg ll_funcs[] = {
-  {"module", ll_module},
-  {"require", ll_require},
-  {NULL, NULL}
-};
-
-
-static const lua_CFunction loaders[] =
-  {loader_preload, loader_Lua, loader_C, loader_Croot, NULL};
-
-#if LUA_OPTIMIZE_MEMORY > 0
-const luaR_entry lmt[] = {
-  {LRO_STRKEY("__gc"), LRO_FUNCVAL(gctm)},
-  {LRO_NILKEY, LRO_NILVAL}
-};
-#endif
-
-LUALIB_API int luaopen_package (lua_State *L) {
-  int i;
-  /* create new type _LOADLIB */
-#if LUA_OPTIMIZE_MEMORY == 0
-  luaL_newmetatable(L, "_LOADLIB");
-  lua_pushlightfunction(L, gctm);
-  lua_setfield(L, -2, "__gc");
-#else
-  luaL_rometatable(L, "_LOADLIB", (void*)lmt);
-#endif
-  /* create `package' table */
-  luaL_register_light(L, LUA_LOADLIBNAME, pk_funcs);
-#if defined(LUA_COMPAT_LOADLIB) 
-  lua_getfield(L, -1, "loadlib");
-  lua_setfield(L, LUA_GLOBALSINDEX, "loadlib");
-#endif
-  lua_pushvalue(L, -1);
-  lua_replace(L, LUA_ENVIRONINDEX);
-  /* create `loaders' table */
-  lua_createtable(L, sizeof(loaders)/sizeof(loaders[0]) - 1, 0);
-  /* fill it with pre-defined loaders */
-  for (i=0; loaders[i] != NULL; i++) {
-    lua_pushcfunction(L, loaders[i]);
-    lua_rawseti(L, -2, i+1);
-  }
-  lua_setfield(L, -2, "loaders");  /* put it in field `loaders' */
-  setpath(L, "path", LUA_PATH, LUA_PATH_DEFAULT);  /* set field `path' */
-  setpath(L, "cpath", LUA_CPATH, LUA_CPATH_DEFAULT); /* set field `cpath' */
-  /* store config information */
-  lua_pushliteral(L, LUA_DIRSEP "\n" LUA_PATHSEP "\n" LUA_PATH_MARK "\n"
-                     LUA_EXECDIR "\n" LUA_IGMARK);
-  lua_setfield(L, -2, "config");
-  /* set field `loaded' */
-  luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 2);
-  lua_setfield(L, -2, "loaded");
-  /* set field `preload' */
-  lua_newtable(L);
-  lua_setfield(L, -2, "preload");
-  lua_pushvalue(L, LUA_GLOBALSINDEX);
-  luaL_register(L, NULL, ll_funcs);  /* open lib into global table */
-  lua_pop(L, 1);
-  return 1;  /* return 'package' table */
-}
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/lobject.c
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/lobject.c b/libs/elua/elua_base/src/lobject.c
deleted file mode 100644
index 6c987f6..0000000
--- a/libs/elua/elua_base/src/lobject.c
+++ /dev/null
@@ -1,216 +0,0 @@
-/*
-** $Id: lobject.c,v 2.22.1.1 2007/12/27 13:02:25 roberto Exp $
-** Some generic functions over Lua objects
-** See Copyright Notice in lua.h
-*/
-
-#include <ctype.h>
-#include <stdarg.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#define lobject_c
-#define LUA_CORE
-
-#include "lua.h"
-
-#include "ldo.h"
-#include "lmem.h"
-#include "lobject.h"
-#include "lstate.h"
-#include "lstring.h"
-#include "lvm.h"
-
-
-
-const TValue luaO_nilobject_ = {LUA_TVALUE_NIL};
-
-
-/*
-** converts an integer to a "floating point byte", represented as
-** (eeeeexxx), where the real value is (1xxx) * 2^(eeeee - 1) if
-** eeeee != 0 and (xxx) otherwise.
-*/
-int luaO_int2fb (unsigned int x) {
-  int e = 0;  /* expoent */
-  while (x >= 16) {
-    x = (x+1) >> 1;
-    e++;
-  }
-  if (x < 8) return x;
-  else return ((e+1) << 3) | (cast_int(x) - 8);
-}
-
-
-/* converts back */
-int luaO_fb2int (int x) {
-  int e = (x >> 3) & 31;
-  if (e == 0) return x;
-  else return ((x & 7)+8) << (e - 1);
-}
-
-
-int luaO_log2 (unsigned int x) {
-  static const lu_byte log_2[256] = {
-    0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
-    6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
-    7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
-    7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
-    8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
-    8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
-    8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
-    8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8
-  };
-  int l = -1;
-  while (x >= 256) { l += 8; x >>= 8; }
-  return l + log_2[x];
-
-}
-
-
-int luaO_rawequalObj (const TValue *t1, const TValue *t2) {
-  if (ttype(t1) != ttype(t2)) return 0;
-  else switch (ttype(t1)) {
-    case LUA_TNIL:
-      return 1;
-    case LUA_TNUMBER:
-      return luai_numeq(nvalue(t1), nvalue(t2));
-    case LUA_TBOOLEAN:
-      return bvalue(t1) == bvalue(t2);  /* boolean true must be 1 !! */
-    case LUA_TLIGHTUSERDATA:
-    case LUA_TROTABLE:
-    case LUA_TLIGHTFUNCTION:
-      return pvalue(t1) == pvalue(t2);
-    default:
-      lua_assert(iscollectable(t1));
-      return gcvalue(t1) == gcvalue(t2);
-  }
-}
-
-
-int luaO_str2d (const char *s, lua_Number *result) {
-  char *endptr;
-  *result = lua_str2number(s, &endptr);
-  if (endptr == s) return 0;  /* conversion failed */
-  if (*endptr == 'x' || *endptr == 'X')  /* maybe an hexadecimal constant? */
-    *result = cast_num(strtoul(s, &endptr, 16));
-  if (*endptr == '\0') return 1;  /* most common case */
-  while (isspace(cast(unsigned char, *endptr))) endptr++;
-  if (*endptr != '\0') return 0;  /* invalid trailing characters? */
-  return 1;
-}
-
-
-
-static void pushstr (lua_State *L, const char *str) {
-  setsvalue2s(L, L->top, luaS_new(L, str));
-  incr_top(L);
-}
-
-
-/* this function handles only `%d', `%c', %f, %p, and `%s' formats */
-const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) {
-  int n = 1;
-  pushstr(L, "");
-  for (;;) {
-    const char *e = strchr(fmt, '%');
-    if (e == NULL) break;
-    setsvalue2s(L, L->top, luaS_newlstr(L, fmt, e-fmt));
-    incr_top(L);
-    switch (*(e+1)) {
-      case 's': {
-        const char *s = va_arg(argp, char *);
-        if (s == NULL) s = "(null)";
-        pushstr(L, s);
-        break;
-      }
-      case 'c': {
-        char buff[2];
-        buff[0] = cast(char, va_arg(argp, int));
-        buff[1] = '\0';
-        pushstr(L, buff);
-        break;
-      }
-      case 'd': {
-        setnvalue(L->top, cast_num(va_arg(argp, int)));
-        incr_top(L);
-        break;
-      }
-      case 'f': {
-        setnvalue(L->top, cast_num(va_arg(argp, l_uacNumber)));
-        incr_top(L);
-        break;
-      }
-      case 'p': {
-        char buff[4*sizeof(void *) + 8]; /* should be enough space for a `%p' */
-        sprintf(buff, "%p", va_arg(argp, void *));
-        pushstr(L, buff);
-        break;
-      }
-      case '%': {
-        pushstr(L, "%");
-        break;
-      }
-      default: {
-        char buff[3];
-        buff[0] = '%';
-        buff[1] = *(e+1);
-        buff[2] = '\0';
-        pushstr(L, buff);
-        break;
-      }
-    }
-    n += 2;
-    fmt = e+2;
-  }
-  pushstr(L, fmt);
-  luaV_concat(L, n+1, cast_int(L->top - L->base) - 1);
-  L->top -= n;
-  return svalue(L->top - 1);
-}
-
-
-const char *luaO_pushfstring (lua_State *L, const char *fmt, ...) {
-  const char *msg;
-  va_list argp;
-  va_start(argp, fmt);
-  msg = luaO_pushvfstring(L, fmt, argp);
-  va_end(argp);
-  return msg;
-}
-
-
-void luaO_chunkid (char *out, const char *source, size_t bufflen) {
-  if (*source == '=') {
-    strncpy(out, source+1, bufflen);  /* remove first char */
-    out[bufflen-1] = '\0';  /* ensures null termination */
-  }
-  else {  /* out = "source", or "...source" */
-    if (*source == '@') {
-      size_t l;
-      source++;  /* skip the `@' */
-      bufflen -= sizeof(" '...' ");
-      l = strlen(source);
-      strcpy(out, "");
-      if (l > bufflen) {
-        source += (l-bufflen);  /* get last part of file name */
-        strcat(out, "...");
-      }
-      strcat(out, source);
-    }
-    else {  /* out = [string "string"] */
-      size_t len = strcspn(source, "\n\r");  /* stop at first newline */
-      bufflen -= sizeof(" [string \"...\"] ");
-      if (len > bufflen) len = bufflen;
-      strcpy(out, "[string \"");
-      if (source[len] != '\0') {  /* must truncate? */
-        strncat(out, source, len);
-        strcat(out, "...");
-      }
-      else
-        strcat(out, source);
-      strcat(out, "\"]");
-    }
-  }
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/lobject.h
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/lobject.h b/libs/elua/elua_base/src/lobject.h
deleted file mode 100644
index 55532f4..0000000
--- a/libs/elua/elua_base/src/lobject.h
+++ /dev/null
@@ -1,557 +0,0 @@
-/*
-** $Id: lobject.h,v 2.20.1.2 2008/08/06 13:29:48 roberto Exp $
-** Type definitions for Lua objects
-** See Copyright Notice in lua.h
-*/
-
-
-#ifndef lobject_h
-#define lobject_h
-
-
-#include <stdarg.h>
-
-
-#include "llimits.h"
-#include "lua.h"
-
-
-/* tags for values visible from Lua */
-#define LAST_TAG	LUA_TTHREAD
-
-#define NUM_TAGS	(LAST_TAG+1)
-
-/* mask for 'read-only' objects. must match READONLYBIT in lgc.h' */
-#define READONLYMASK  128
-
-
-/*
-** Extra tags for non-values
-*/
-#define LUA_TPROTO	(LAST_TAG+1)
-#define LUA_TUPVAL	(LAST_TAG+2)
-#define LUA_TDEADKEY	(LAST_TAG+3)
-
-
-/*
-** Union of all collectable objects
-*/
-typedef union GCObject GCObject;
-
-
-/*
-** Common Header for all collectable objects (in macro form, to be
-** included in other objects)
-*/
-#define CommonHeader	GCObject *next; lu_byte tt; lu_byte marked
-
-
-/*
-** Common header in struct form
-*/
-typedef struct GCheader {
-  CommonHeader;
-} GCheader;
-
-
-
-
-/*
-** Union of all Lua values
-*/
-#if defined( LUA_PACK_VALUE ) && defined( ELUA_ENDIAN_BIG )
-typedef union {
-  struct {
-    int _pad0;
-    GCObject *gc;
-  };
-  struct {
-    int _pad1;
-    void *p;
-  };
-  lua_Number n;
-  struct {
-    int _pad2;
-    int b;
-  };
-} Value;
-#else // #if defined( LUA_PACK_VALUE ) && defined( ELUA_ENDIAN_BIG )
-typedef union {
-  GCObject *gc;
-  void *p;
-  lua_Number n;
-  int b;
-} Value;
-#endif // #if defined( LUA_PACK_VALUE ) && defined( ELUA_ENDIAN_BIG )
-
-/*
-** Tagged Values
-*/
-
-#ifndef LUA_PACK_VALUE
-#define TValuefields	Value value; int tt
-#define LUA_TVALUE_NIL {NULL}, LUA_TNIL
-
-typedef struct lua_TValue {
-  TValuefields;
-} TValue;
-#else // #ifndef LUA_PACK_VALUE
-#ifdef ELUA_ENDIAN_LITTLE
-#define TValuefields union { \
-  struct { \
-    int _pad0; \
-    int tt_sig; \
-  } _ts; \
-  struct { \
-    int _pad; \
-    short tt; \
-    short sig; \
-  } _t; \
-  Value value; \
-}
-#define LUA_TVALUE_NIL {0, add_sig(LUA_TNIL)}
-#else // #ifdef ELUA_ENDIAN_LITTLE
-#define TValuefields union { \
-  struct { \
-    int tt_sig; \
-    int _pad0; \
-  } _ts; \
-  struct { \
-    short sig; \
-    short tt; \
-    int _pad; \
-  } _t; \
-  Value value; \
-}
-#define LUA_TVALUE_NIL {add_sig(LUA_TNIL), 0}
-#endif // #ifdef ELUA_ENDIAN_LITTLE
-#define LUA_NOTNUMBER_SIG (-1)
-#define add_sig(tt) ( 0xffff0000 | (tt) )
-
-typedef TValuefields TValue;
-#endif // #ifndef LUA_PACK_VALUE
-
-/* Macros to test type */
-#ifndef LUA_PACK_VALUE
-#define ttisnil(o)	(ttype(o) == LUA_TNIL)
-#define ttisnumber(o)	(ttype(o) == LUA_TNUMBER)
-#define ttisstring(o)	(ttype(o) == LUA_TSTRING)
-#define ttistable(o)	(ttype(o) == LUA_TTABLE)
-#define ttisfunction(o)	(ttype(o) == LUA_TFUNCTION)
-#define ttisboolean(o)	(ttype(o) == LUA_TBOOLEAN)
-#define ttisuserdata(o)	(ttype(o) == LUA_TUSERDATA)
-#define ttisthread(o)	(ttype(o) == LUA_TTHREAD)
-#define ttislightuserdata(o)	(ttype(o) == LUA_TLIGHTUSERDATA)
-#define ttisrotable(o) (ttype(o) == LUA_TROTABLE)
-#define ttislightfunction(o)  (ttype(o) == LUA_TLIGHTFUNCTION)
-#else // #ifndef LUA_PACK_VALUE
-#define ttisnil(o) (ttype_sig(o) == add_sig(LUA_TNIL))
-#define ttisnumber(o)  ((o)->_t.sig != LUA_NOTNUMBER_SIG)
-#define ttisstring(o)  (ttype_sig(o) == add_sig(LUA_TSTRING))
-#define ttistable(o) (ttype_sig(o) == add_sig(LUA_TTABLE))
-#define ttisfunction(o)  (ttype_sig(o) == add_sig(LUA_TFUNCTION))
-#define ttisboolean(o) (ttype_sig(o) == add_sig(LUA_TBOOLEAN))
-#define ttisuserdata(o)  (ttype_sig(o) == add_sig(LUA_TUSERDATA))
-#define ttisthread(o)  (ttype_sig(o) == add_sig(LUA_TTHREAD))
-#define ttislightuserdata(o) (ttype_sig(o) == add_sig(LUA_TLIGHTUSERDATA))
-#define ttisrotable(o) (ttype_sig(o) == add_sig(LUA_TROTABLE))
-#define ttislightfunction(o)  (ttype_sig(o) == add_sig(LUA_TLIGHTFUNCTION))
-#endif // #ifndef LUA_PACK_VALUE
-
-/* Macros to access values */
-#ifndef LUA_PACK_VALUE
-#define ttype(o)	((o)->tt)
-#else // #ifndef LUA_PACK_VALUE
-#define ttype(o)	((o)->_t.sig == LUA_NOTNUMBER_SIG ? (o)->_t.tt : LUA_TNUMBER)
-#define ttype_sig(o)	((o)->_ts.tt_sig)
-#endif // #ifndef LUA_PACK_VALUE
-#define gcvalue(o)	check_exp(iscollectable(o), (o)->value.gc)
-#define pvalue(o)	check_exp(ttislightuserdata(o), (o)->value.p)
-#define rvalue(o)	check_exp(ttisrotable(o), (o)->value.p)
-#define fvalue(o) check_exp(ttislightfunction(o), (o)->value.p)
-#define nvalue(o)	check_exp(ttisnumber(o), (o)->value.n)
-#define rawtsvalue(o)	check_exp(ttisstring(o), &(o)->value.gc->ts)
-#define tsvalue(o)	(&rawtsvalue(o)->tsv)
-#define rawuvalue(o)	check_exp(ttisuserdata(o), &(o)->value.gc->u)
-#define uvalue(o)	(&rawuvalue(o)->uv)
-#define clvalue(o)	check_exp(ttisfunction(o), &(o)->value.gc->cl)
-#define hvalue(o)	check_exp(ttistable(o), &(o)->value.gc->h)
-#define bvalue(o)	check_exp(ttisboolean(o), (o)->value.b)
-#define thvalue(o)	check_exp(ttisthread(o), &(o)->value.gc->th)
-
-#define l_isfalse(o)	(ttisnil(o) || (ttisboolean(o) && bvalue(o) == 0))
-
-/*
-** for internal debug only
-*/
-#ifndef LUA_PACK_VALUE
-#define checkconsistency(obj) \
-  lua_assert(!iscollectable(obj) || (ttype(obj) == (obj)->value.gc->gch.tt))
-
-#define checkliveness(g,obj) \
-  lua_assert(!iscollectable(obj) || \
-  ((ttype(obj) == (obj)->value.gc->gch.tt) && !isdead(g, (obj)->value.gc)))
-#else // #ifndef LUA_PACK_VALUE
-#define checkconsistency(obj) \
-  lua_assert(!iscollectable(obj) || (ttype(obj) == (obj)->value.gc->gch._t.tt))
-
-#define checkliveness(g,obj) \
-  lua_assert(!iscollectable(obj) || \
-  ((ttype(obj) == (obj)->value.gc->gch._t.tt) && !isdead(g, (obj)->value.gc)))
-#endif // #ifndef LUA_PACK_VALUE
-
-/* Macros to set values */
-#ifndef LUA_PACK_VALUE
-#define setnilvalue(obj) ((obj)->tt=LUA_TNIL)
-
-#define setnvalue(obj,x) \
-  { lua_Number i_x = (x); TValue *i_o=(obj); i_o->value.n=i_x; i_o->tt=LUA_TNUMBER; }
-
-#define setpvalue(obj,x) \
-  { void *i_x = (x); TValue *i_o=(obj); i_o->value.p=i_x; i_o->tt=LUA_TLIGHTUSERDATA; }
-  
-#define setrvalue(obj,x) \
-  { void *i_x = (x); TValue *i_o=(obj); i_o->value.p=i_x; i_o->tt=LUA_TROTABLE; }
-  
-#define setfvalue(obj,x) \
-  { void *i_x = (x); TValue *i_o=(obj); i_o->value.p=i_x; i_o->tt=LUA_TLIGHTFUNCTION; }
-
-#define setbvalue(obj,x) \
-  { int i_x = (x); TValue *i_o=(obj); i_o->value.b=i_x; i_o->tt=LUA_TBOOLEAN; }
-
-#define setsvalue(L,obj,x) \
-  { GCObject *i_x = cast(GCObject *, (x)); \
-    TValue *i_o=(obj); \
-    i_o->value.gc=i_x; i_o->tt=LUA_TSTRING; \
-    checkliveness(G(L),i_o); }
-
-#define setuvalue(L,obj,x) \
-  { GCObject *i_x = cast(GCObject *, (x)); \
-    TValue *i_o=(obj); \
-    i_o->value.gc=i_x; i_o->tt=LUA_TUSERDATA; \
-    checkliveness(G(L),i_o); }
-
-#define setthvalue(L,obj,x) \
-  { GCObject *i_x = cast(GCObject *, (x)); \
-    TValue *i_o=(obj); \
-    i_o->value.gc=i_x; i_o->tt=LUA_TTHREAD; \
-    checkliveness(G(L),i_o); }
-
-#define setclvalue(L,obj,x) \
-  { GCObject *i_x = cast(GCObject *, (x)); \
-    TValue *i_o=(obj); \
-    i_o->value.gc=i_x; i_o->tt=LUA_TFUNCTION; \
-    checkliveness(G(L),i_o); }
-
-#define sethvalue(L,obj,x) \
-  { GCObject *i_x = cast(GCObject *, (x)); \
-    TValue *i_o=(obj); \
-    i_o->value.gc=i_x; i_o->tt=LUA_TTABLE; \
-    checkliveness(G(L),i_o); }
-
-#define setptvalue(L,obj,x) \
-  { GCObject *i_x = cast(GCObject *, (x)); \
-    TValue *i_o=(obj); \
-    i_o->value.gc=i_x; i_o->tt=LUA_TPROTO; \
-    checkliveness(G(L),i_o); }
-
-
-
-
-#define setobj(L,obj1,obj2) \
-  { const TValue *o2=(obj2); TValue *o1=(obj1); \
-    o1->value = o2->value; o1->tt=o2->tt; \
-    checkliveness(G(L),o1); }
-#else // #ifndef LUA_PACK_VALUE
-#define setnilvalue(obj) ( ttype_sig(obj) = add_sig(LUA_TNIL) )
-
-#define setnvalue(obj,x) \
-  { TValue *i_o=(obj); i_o->value.n=(x); }
-
-#define setpvalue(obj,x) \
-  { TValue *i_o=(obj); i_o->value.p=(x); i_o->_ts.tt_sig=add_sig(LUA_TLIGHTUSERDATA);}
-
-#define setrvalue(obj,x) \
-  { TValue *i_o=(obj); i_o->value.p=(x); i_o->_ts.tt_sig=add_sig(LUA_TROTABLE);}
-
-#define setfvalue(obj,x) \
-  { TValue *i_o=(obj); i_o->value.p=(x); i_o->_ts.tt_sig=add_sig(LUA_TLIGHTFUNCTION);}
-
-#define setbvalue(obj,x) \
-  { TValue *i_o=(obj); i_o->value.b=(x); i_o->_ts.tt_sig=add_sig(LUA_TBOOLEAN);}
-
-#define setsvalue(L,obj,x) \
-  { GCObject *i_x=cast(GCObject *, (x)); \
-    TValue *i_o=(obj); \
-    i_o->value.gc=i_x; i_o->_ts.tt_sig=add_sig(LUA_TSTRING); \
-    checkliveness(G(L),i_o); }
-
-#define setuvalue(L,obj,x) \
-  { GCObject *i_x=cast(GCObject *, (x)); \
-    TValue *i_o=(obj); \
-    i_o->value.gc=i_x; i_o->_ts.tt_sig=add_sig(LUA_TUSERDATA); \
-    checkliveness(G(L),i_o); }
-
-#define setthvalue(L,obj,x) \
-  { GCObject *i_x=cast(GCObject *, (x)); \
-    TValue *i_o=(obj); \
-    i_o->value.gc=i_x; i_o->_ts.tt_sig=add_sig(LUA_TTHREAD); \
-    checkliveness(G(L),i_o); }
-
-#define setclvalue(L,obj,x) \
-  { GCObject *i_x=cast(GCObject *, (x)); \
-    TValue *i_o=(obj); \
-    i_o->value.gc=i_x; i_o->_ts.tt_sig=add_sig(LUA_TFUNCTION); \
-    checkliveness(G(L),i_o); }
-
-#define sethvalue(L,obj,x) \
-  { GCObject *i_x=cast(GCObject *, (x)); \
-    TValue *i_o=(obj); \
-    i_o->value.gc=i_x; i_o->_ts.tt_sig=add_sig(LUA_TTABLE); \
-    checkliveness(G(L),i_o); }
-
-#define setptvalue(L,obj,x) \
-  { GCObject *i_x=cast(GCObject *, (x)); \
-    TValue *i_o=(obj); \
-    i_o->value.gc=i_x; i_o->_ts.tt_sig=add_sig(LUA_TPROTO); \
-    checkliveness(G(L),i_o); }
-
-
-
-
-#define setobj(L,obj1,obj2) \
-  { const TValue *o2=(obj2); TValue *o1=(obj1); \
-    o1->value = o2->value; \
-    checkliveness(G(L),o1); }
-#endif // #ifndef LUA_PACK_VALUE
-
-/*
-** different types of sets, according to destination
-*/
-
-/* from stack to (same) stack */
-#define setobjs2s	setobj
-/* to stack (not from same stack) */
-#define setobj2s	setobj
-#define setsvalue2s	setsvalue
-#define sethvalue2s	sethvalue
-#define setptvalue2s	setptvalue
-/* from table to same table */
-#define setobjt2t	setobj
-/* to table */
-#define setobj2t	setobj
-/* to new object */
-#define setobj2n	setobj
-#define setsvalue2n	setsvalue
-
-#ifndef LUA_PACK_VALUE
-#define setttype(obj, tt) (ttype(obj) = (tt))
-#else // #ifndef LUA_PACK_VALUE
-/* considering it used only in lgc to set LUA_TDEADKEY */
-/* we could define it this way */
-#define setttype(obj, _tt) ( ttype_sig(obj) = add_sig(_tt) )
-#endif // #ifndef LUA_PACK_VALUE
-
-#define iscollectable(o)	(ttype(o) >= LUA_TSTRING)
-
-
-
-typedef TValue *StkId;  /* index to stack elements */
-
-
-/*
-** String headers for string table
-*/
-typedef union TString {
-  L_Umaxalign dummy;  /* ensures maximum alignment for strings */
-  struct {
-    CommonHeader;
-    unsigned int hash;
-    size_t len;
-  } tsv;
-} TString;
-
-
-#define getstr(ts)	(((ts)->tsv.marked & READONLYMASK) ? cast(const char *, *(const char**)((ts) + 1)) : cast(const char *, (ts) + 1))
-#define svalue(o)       getstr(rawtsvalue(o))
-
-
-
-typedef union Udata {
-  L_Umaxalign dummy;  /* ensures maximum alignment for `local' udata */
-  struct {
-    CommonHeader;
-    struct Table *metatable;
-    struct Table *env;
-    size_t len;
-  } uv;
-} Udata;
-
-
-
-
-/*
-** Function Prototypes
-*/
-typedef struct Proto {
-  CommonHeader;
-  TValue *k;  /* constants used by the function */
-  Instruction *code;
-  struct Proto **p;  /* functions defined inside the function */
-  int *lineinfo;  /* map from opcodes to source lines */
-  struct LocVar *locvars;  /* information about local variables */
-  TString **upvalues;  /* upvalue names */
-  TString  *source;
-  int sizeupvalues;
-  int sizek;  /* size of `k' */
-  int sizecode;
-  int sizelineinfo;
-  int sizep;  /* size of `p' */
-  int sizelocvars;
-  int linedefined;
-  int lastlinedefined;
-  GCObject *gclist;
-  lu_byte nups;  /* number of upvalues */
-  lu_byte numparams;
-  lu_byte is_vararg;
-  lu_byte maxstacksize;
-} Proto;
-
-
-/* masks for new-style vararg */
-#define VARARG_HASARG		1
-#define VARARG_ISVARARG		2
-#define VARARG_NEEDSARG		4
-
-
-typedef struct LocVar {
-  TString *varname;
-  int startpc;  /* first point where variable is active */
-  int endpc;    /* first point where variable is dead */
-} LocVar;
-
-
-
-/*
-** Upvalues
-*/
-
-typedef struct UpVal {
-  CommonHeader;
-  TValue *v;  /* points to stack or to its own value */
-  union {
-    TValue value;  /* the value (when closed) */
-    struct {  /* double linked list (when open) */
-      struct UpVal *prev;
-      struct UpVal *next;
-    } l;
-  } u;
-} UpVal;
-
-
-/*
-** Closures
-*/
-
-#define ClosureHeader \
-	CommonHeader; lu_byte isC; lu_byte nupvalues; GCObject *gclist; \
-	struct Table *env
-
-typedef struct CClosure {
-  ClosureHeader;
-  lua_CFunction f;
-  TValue upvalue[1];
-} CClosure;
-
-
-typedef struct LClosure {
-  ClosureHeader;
-  struct Proto *p;
-  UpVal *upvals[1];
-} LClosure;
-
-
-typedef union Closure {
-  CClosure c;
-  LClosure l;
-} Closure;
-
-
-#define iscfunction(o)	((ttype(o) == LUA_TFUNCTION && clvalue(o)->c.isC)||(ttype(o)==LUA_TLIGHTFUNCTION))
-#define isLfunction(o)	(ttype(o) == LUA_TFUNCTION && !clvalue(o)->c.isC)
-
-
-/*
-** Tables
-*/
-
-#ifndef LUA_PACK_VALUE
-typedef union TKey {
-  struct {
-    TValuefields;
-    struct Node *next;  /* for chaining */
-  } nk;
-  TValue tvk;
-} TKey;
-
-#define LUA_TKEY_NIL {LUA_TVALUE_NIL, NULL}
-#else // #ifndef LUA_PACK_VALUE
-typedef struct TKey {
-  TValue tvk;
-  struct {
-     struct Node *next; /* for chaining */
-  } nk;
-} TKey;
-
-#define LUA_TKEY_NIL {LUA_TVALUE_NIL}, {NULL}
-#endif // #ifndef LUA_PACK_VALUE
-
-typedef struct Node {
-  TValue i_val;
-  TKey i_key;
-} Node;
-
-
-typedef struct Table {
-  CommonHeader;
-  lu_byte flags;  /* 1<<p means tagmethod(p) is not present */ 
-  lu_byte lsizenode;  /* log2 of size of `node' array */
-  struct Table *metatable;
-  TValue *array;  /* array part */
-  Node *node;
-  Node *lastfree;  /* any free position is before this position */
-  GCObject *gclist;
-  int sizearray;  /* size of `array' array */
-} Table;
-
-
-/*
-** `module' operation for hashing (size is always a power of 2)
-*/
-#define lmod(s,size) \
-	(check_exp((size&(size-1))==0, (cast(int, (s) & ((size)-1)))))
-
-
-#define twoto(x)	(1<<(x))
-#define sizenode(t)	(twoto((t)->lsizenode))
-
-
-#define luaO_nilobject		(&luaO_nilobject_)
-
-LUAI_DATA const TValue luaO_nilobject_;
-
-#define ceillog2(x)	(luaO_log2((x)-1) + 1)
-
-LUAI_FUNC int luaO_log2 (unsigned int x);
-LUAI_FUNC int luaO_int2fb (unsigned int x);
-LUAI_FUNC int luaO_fb2int (int x);
-LUAI_FUNC int luaO_rawequalObj (const TValue *t1, const TValue *t2);
-LUAI_FUNC int luaO_str2d (const char *s, lua_Number *result);
-LUAI_FUNC const char *luaO_pushvfstring (lua_State *L, const char *fmt,
-                                                       va_list argp);
-LUAI_FUNC const char *luaO_pushfstring (lua_State *L, const char *fmt, ...);
-LUAI_FUNC void luaO_chunkid (char *out, const char *source, size_t len);
-
-
-#endif
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/lopcodes.c
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/lopcodes.c b/libs/elua/elua_base/src/lopcodes.c
deleted file mode 100644
index 4cc7452..0000000
--- a/libs/elua/elua_base/src/lopcodes.c
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
-** $Id: lopcodes.c,v 1.37.1.1 2007/12/27 13:02:25 roberto Exp $
-** See Copyright Notice in lua.h
-*/
-
-
-#define lopcodes_c
-#define LUA_CORE
-
-
-#include "lopcodes.h"
-
-
-/* ORDER OP */
-
-const char *const luaP_opnames[NUM_OPCODES+1] = {
-  "MOVE",
-  "LOADK",
-  "LOADBOOL",
-  "LOADNIL",
-  "GETUPVAL",
-  "GETGLOBAL",
-  "GETTABLE",
-  "SETGLOBAL",
-  "SETUPVAL",
-  "SETTABLE",
-  "NEWTABLE",
-  "SELF",
-  "ADD",
-  "SUB",
-  "MUL",
-  "DIV",
-  "MOD",
-  "POW",
-  "UNM",
-  "NOT",
-  "LEN",
-  "CONCAT",
-  "JMP",
-  "EQ",
-  "LT",
-  "LE",
-  "TEST",
-  "TESTSET",
-  "CALL",
-  "TAILCALL",
-  "RETURN",
-  "FORLOOP",
-  "FORPREP",
-  "TFORLOOP",
-  "SETLIST",
-  "CLOSE",
-  "CLOSURE",
-  "VARARG",
-  NULL
-};
-
-
-#define opmode(t,a,b,c,m) (((t)<<7) | ((a)<<6) | ((b)<<4) | ((c)<<2) | (m))
-
-const lu_byte luaP_opmodes[NUM_OPCODES] = {
-/*       T  A    B       C     mode		   opcode	*/
-  opmode(0, 1, OpArgR, OpArgN, iABC) 		/* OP_MOVE */
- ,opmode(0, 1, OpArgK, OpArgN, iABx)		/* OP_LOADK */
- ,opmode(0, 1, OpArgU, OpArgU, iABC)		/* OP_LOADBOOL */
- ,opmode(0, 1, OpArgR, OpArgN, iABC)		/* OP_LOADNIL */
- ,opmode(0, 1, OpArgU, OpArgN, iABC)		/* OP_GETUPVAL */
- ,opmode(0, 1, OpArgK, OpArgN, iABx)		/* OP_GETGLOBAL */
- ,opmode(0, 1, OpArgR, OpArgK, iABC)		/* OP_GETTABLE */
- ,opmode(0, 0, OpArgK, OpArgN, iABx)		/* OP_SETGLOBAL */
- ,opmode(0, 0, OpArgU, OpArgN, iABC)		/* OP_SETUPVAL */
- ,opmode(0, 0, OpArgK, OpArgK, iABC)		/* OP_SETTABLE */
- ,opmode(0, 1, OpArgU, OpArgU, iABC)		/* OP_NEWTABLE */
- ,opmode(0, 1, OpArgR, OpArgK, iABC)		/* OP_SELF */
- ,opmode(0, 1, OpArgK, OpArgK, iABC)		/* OP_ADD */
- ,opmode(0, 1, OpArgK, OpArgK, iABC)		/* OP_SUB */
- ,opmode(0, 1, OpArgK, OpArgK, iABC)		/* OP_MUL */
- ,opmode(0, 1, OpArgK, OpArgK, iABC)		/* OP_DIV */
- ,opmode(0, 1, OpArgK, OpArgK, iABC)		/* OP_MOD */
- ,opmode(0, 1, OpArgK, OpArgK, iABC)		/* OP_POW */
- ,opmode(0, 1, OpArgR, OpArgN, iABC)		/* OP_UNM */
- ,opmode(0, 1, OpArgR, OpArgN, iABC)		/* OP_NOT */
- ,opmode(0, 1, OpArgR, OpArgN, iABC)		/* OP_LEN */
- ,opmode(0, 1, OpArgR, OpArgR, iABC)		/* OP_CONCAT */
- ,opmode(0, 0, OpArgR, OpArgN, iAsBx)		/* OP_JMP */
- ,opmode(1, 0, OpArgK, OpArgK, iABC)		/* OP_EQ */
- ,opmode(1, 0, OpArgK, OpArgK, iABC)		/* OP_LT */
- ,opmode(1, 0, OpArgK, OpArgK, iABC)		/* OP_LE */
- ,opmode(1, 1, OpArgR, OpArgU, iABC)		/* OP_TEST */
- ,opmode(1, 1, OpArgR, OpArgU, iABC)		/* OP_TESTSET */
- ,opmode(0, 1, OpArgU, OpArgU, iABC)		/* OP_CALL */
- ,opmode(0, 1, OpArgU, OpArgU, iABC)		/* OP_TAILCALL */
- ,opmode(0, 0, OpArgU, OpArgN, iABC)		/* OP_RETURN */
- ,opmode(0, 1, OpArgR, OpArgN, iAsBx)		/* OP_FORLOOP */
- ,opmode(0, 1, OpArgR, OpArgN, iAsBx)		/* OP_FORPREP */
- ,opmode(1, 0, OpArgN, OpArgU, iABC)		/* OP_TFORLOOP */
- ,opmode(0, 0, OpArgU, OpArgU, iABC)		/* OP_SETLIST */
- ,opmode(0, 0, OpArgN, OpArgN, iABC)		/* OP_CLOSE */
- ,opmode(0, 1, OpArgU, OpArgN, iABx)		/* OP_CLOSURE */
- ,opmode(0, 1, OpArgU, OpArgN, iABC)		/* OP_VARARG */
-};
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/lopcodes.h
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/lopcodes.h b/libs/elua/elua_base/src/lopcodes.h
deleted file mode 100644
index 41224d6..0000000
--- a/libs/elua/elua_base/src/lopcodes.h
+++ /dev/null
@@ -1,268 +0,0 @@
-/*
-** $Id: lopcodes.h,v 1.125.1.1 2007/12/27 13:02:25 roberto Exp $
-** Opcodes for Lua virtual machine
-** See Copyright Notice in lua.h
-*/
-
-#ifndef lopcodes_h
-#define lopcodes_h
-
-#include "llimits.h"
-
-
-/*===========================================================================
-  We assume that instructions are unsigned numbers.
-  All instructions have an opcode in the first 6 bits.
-  Instructions can have the following fields:
-	`A' : 8 bits
-	`B' : 9 bits
-	`C' : 9 bits
-	`Bx' : 18 bits (`B' and `C' together)
-	`sBx' : signed Bx
-
-  A signed argument is represented in excess K; that is, the number
-  value is the unsigned value minus K. K is exactly the maximum value
-  for that argument (so that -max is represented by 0, and +max is
-  represented by 2*max), which is half the maximum for the corresponding
-  unsigned argument.
-===========================================================================*/
-
-
-enum OpMode {iABC, iABx, iAsBx};  /* basic instruction format */
-
-
-/*
-** size and position of opcode arguments.
-*/
-#define SIZE_C		9
-#define SIZE_B		9
-#define SIZE_Bx		(SIZE_C + SIZE_B)
-#define SIZE_A		8
-
-#define SIZE_OP		6
-
-#define POS_OP		0
-#define POS_A		(POS_OP + SIZE_OP)
-#define POS_C		(POS_A + SIZE_A)
-#define POS_B		(POS_C + SIZE_C)
-#define POS_Bx		POS_C
-
-
-/*
-** limits for opcode arguments.
-** we use (signed) int to manipulate most arguments,
-** so they must fit in LUAI_BITSINT-1 bits (-1 for sign)
-*/
-#if SIZE_Bx < LUAI_BITSINT-1
-#define MAXARG_Bx        ((1<<SIZE_Bx)-1)
-#define MAXARG_sBx        (MAXARG_Bx>>1)         /* `sBx' is signed */
-#else
-#define MAXARG_Bx        MAX_INT
-#define MAXARG_sBx        MAX_INT
-#endif
-
-
-#define MAXARG_A        ((1<<SIZE_A)-1)
-#define MAXARG_B        ((1<<SIZE_B)-1)
-#define MAXARG_C        ((1<<SIZE_C)-1)
-
-
-/* creates a mask with `n' 1 bits at position `p' */
-#define MASK1(n,p)	((~((~(Instruction)0)<<n))<<p)
-
-/* creates a mask with `n' 0 bits at position `p' */
-#define MASK0(n,p)	(~MASK1(n,p))
-
-/*
-** the following macros help to manipulate instructions
-*/
-
-#define GET_OPCODE(i)	(cast(OpCode, ((i)>>POS_OP) & MASK1(SIZE_OP,0)))
-#define SET_OPCODE(i,o)	((i) = (((i)&MASK0(SIZE_OP,POS_OP)) | \
-		((cast(Instruction, o)<<POS_OP)&MASK1(SIZE_OP,POS_OP))))
-
-#define GETARG_A(i)	(cast(int, ((i)>>POS_A) & MASK1(SIZE_A,0)))
-#define SETARG_A(i,u)	((i) = (((i)&MASK0(SIZE_A,POS_A)) | \
-		((cast(Instruction, u)<<POS_A)&MASK1(SIZE_A,POS_A))))
-
-#define GETARG_B(i)	(cast(int, ((i)>>POS_B) & MASK1(SIZE_B,0)))
-#define SETARG_B(i,b)	((i) = (((i)&MASK0(SIZE_B,POS_B)) | \
-		((cast(Instruction, b)<<POS_B)&MASK1(SIZE_B,POS_B))))
-
-#define GETARG_C(i)	(cast(int, ((i)>>POS_C) & MASK1(SIZE_C,0)))
-#define SETARG_C(i,b)	((i) = (((i)&MASK0(SIZE_C,POS_C)) | \
-		((cast(Instruction, b)<<POS_C)&MASK1(SIZE_C,POS_C))))
-
-#define GETARG_Bx(i)	(cast(int, ((i)>>POS_Bx) & MASK1(SIZE_Bx,0)))
-#define SETARG_Bx(i,b)	((i) = (((i)&MASK0(SIZE_Bx,POS_Bx)) | \
-		((cast(Instruction, b)<<POS_Bx)&MASK1(SIZE_Bx,POS_Bx))))
-
-#define GETARG_sBx(i)	(GETARG_Bx(i)-MAXARG_sBx)
-#define SETARG_sBx(i,b)	SETARG_Bx((i),cast(unsigned int, (b)+MAXARG_sBx))
-
-
-#define CREATE_ABC(o,a,b,c)	((cast(Instruction, o)<<POS_OP) \
-			| (cast(Instruction, a)<<POS_A) \
-			| (cast(Instruction, b)<<POS_B) \
-			| (cast(Instruction, c)<<POS_C))
-
-#define CREATE_ABx(o,a,bc)	((cast(Instruction, o)<<POS_OP) \
-			| (cast(Instruction, a)<<POS_A) \
-			| (cast(Instruction, bc)<<POS_Bx))
-
-
-/*
-** Macros to operate RK indices
-*/
-
-/* this bit 1 means constant (0 means register) */
-#define BITRK		(1 << (SIZE_B - 1))
-
-/* test whether value is a constant */
-#define ISK(x)		((x) & BITRK)
-
-/* gets the index of the constant */
-#define INDEXK(r)	((int)(r) & ~BITRK)
-
-#define MAXINDEXRK	(BITRK - 1)
-
-/* code a constant index as a RK value */
-#define RKASK(x)	((x) | BITRK)
-
-
-/*
-** invalid register that fits in 8 bits
-*/
-#define NO_REG		MAXARG_A
-
-
-/*
-** R(x) - register
-** Kst(x) - constant (in constant table)
-** RK(x) == if ISK(x) then Kst(INDEXK(x)) else R(x)
-*/
-
-
-/*
-** grep "ORDER OP" if you change these enums
-*/
-
-typedef enum {
-/*----------------------------------------------------------------------
-name		args	description
-------------------------------------------------------------------------*/
-OP_MOVE,/*	A B	R(A) := R(B)					*/
-OP_LOADK,/*	A Bx	R(A) := Kst(Bx)					*/
-OP_LOADBOOL,/*	A B C	R(A) := (Bool)B; if (C) pc++			*/
-OP_LOADNIL,/*	A B	R(A) := ... := R(B) := nil			*/
-OP_GETUPVAL,/*	A B	R(A) := UpValue[B]				*/
-
-OP_GETGLOBAL,/*	A Bx	R(A) := Gbl[Kst(Bx)]				*/
-OP_GETTABLE,/*	A B C	R(A) := R(B)[RK(C)]				*/
-
-OP_SETGLOBAL,/*	A Bx	Gbl[Kst(Bx)] := R(A)				*/
-OP_SETUPVAL,/*	A B	UpValue[B] := R(A)				*/
-OP_SETTABLE,/*	A B C	R(A)[RK(B)] := RK(C)				*/
-
-OP_NEWTABLE,/*	A B C	R(A) := {} (size = B,C)				*/
-
-OP_SELF,/*	A B C	R(A+1) := R(B); R(A) := R(B)[RK(C)]		*/
-
-OP_ADD,/*	A B C	R(A) := RK(B) + RK(C)				*/
-OP_SUB,/*	A B C	R(A) := RK(B) - RK(C)				*/
-OP_MUL,/*	A B C	R(A) := RK(B) * RK(C)				*/
-OP_DIV,/*	A B C	R(A) := RK(B) / RK(C)				*/
-OP_MOD,/*	A B C	R(A) := RK(B) % RK(C)				*/
-OP_POW,/*	A B C	R(A) := RK(B) ^ RK(C)				*/
-OP_UNM,/*	A B	R(A) := -R(B)					*/
-OP_NOT,/*	A B	R(A) := not R(B)				*/
-OP_LEN,/*	A B	R(A) := length of R(B)				*/
-
-OP_CONCAT,/*	A B C	R(A) := R(B).. ... ..R(C)			*/
-
-OP_JMP,/*	sBx	pc+=sBx					*/
-
-OP_EQ,/*	A B C	if ((RK(B) == RK(C)) ~= A) then pc++		*/
-OP_LT,/*	A B C	if ((RK(B) <  RK(C)) ~= A) then pc++  		*/
-OP_LE,/*	A B C	if ((RK(B) <= RK(C)) ~= A) then pc++  		*/
-
-OP_TEST,/*	A C	if not (R(A) <=> C) then pc++			*/ 
-OP_TESTSET,/*	A B C	if (R(B) <=> C) then R(A) := R(B) else pc++	*/ 
-
-OP_CALL,/*	A B C	R(A), ... ,R(A+C-2) := R(A)(R(A+1), ... ,R(A+B-1)) */
-OP_TAILCALL,/*	A B C	return R(A)(R(A+1), ... ,R(A+B-1))		*/
-OP_RETURN,/*	A B	return R(A), ... ,R(A+B-2)	(see note)	*/
-
-OP_FORLOOP,/*	A sBx	R(A)+=R(A+2);
-			if R(A) <?= R(A+1) then { pc+=sBx; R(A+3)=R(A) }*/
-OP_FORPREP,/*	A sBx	R(A)-=R(A+2); pc+=sBx				*/
-
-OP_TFORLOOP,/*	A C	R(A+3), ... ,R(A+2+C) := R(A)(R(A+1), R(A+2)); 
-                        if R(A+3) ~= nil then R(A+2)=R(A+3) else pc++	*/ 
-OP_SETLIST,/*	A B C	R(A)[(C-1)*FPF+i] := R(A+i), 1 <= i <= B	*/
-
-OP_CLOSE,/*	A 	close all variables in the stack up to (>=) R(A)*/
-OP_CLOSURE,/*	A Bx	R(A) := closure(KPROTO[Bx], R(A), ... ,R(A+n))	*/
-
-OP_VARARG/*	A B	R(A), R(A+1), ..., R(A+B-1) = vararg		*/
-} OpCode;
-
-
-#define NUM_OPCODES	(cast(int, OP_VARARG) + 1)
-
-
-
-/*===========================================================================
-  Notes:
-  (*) In OP_CALL, if (B == 0) then B = top. C is the number of returns - 1,
-      and can be 0: OP_CALL then sets `top' to last_result+1, so
-      next open instruction (OP_CALL, OP_RETURN, OP_SETLIST) may use `top'.
-
-  (*) In OP_VARARG, if (B == 0) then use actual number of varargs and
-      set top (like in OP_CALL with C == 0).
-
-  (*) In OP_RETURN, if (B == 0) then return up to `top'
-
-  (*) In OP_SETLIST, if (B == 0) then B = `top';
-      if (C == 0) then next `instruction' is real C
-
-  (*) For comparisons, A specifies what condition the test should accept
-      (true or false).
-
-  (*) All `skips' (pc++) assume that next instruction is a jump
-===========================================================================*/
-
-
-/*
-** masks for instruction properties. The format is:
-** bits 0-1: op mode
-** bits 2-3: C arg mode
-** bits 4-5: B arg mode
-** bit 6: instruction set register A
-** bit 7: operator is a test
-*/  
-
-enum OpArgMask {
-  OpArgN,  /* argument is not used */
-  OpArgU,  /* argument is used */
-  OpArgR,  /* argument is a register or a jump offset */
-  OpArgK   /* argument is a constant or register/constant */
-};
-
-LUAI_DATA const lu_byte luaP_opmodes[NUM_OPCODES];
-
-#define getOpMode(m)	(cast(enum OpMode, luaP_opmodes[m] & 3))
-#define getBMode(m)	(cast(enum OpArgMask, (luaP_opmodes[m] >> 4) & 3))
-#define getCMode(m)	(cast(enum OpArgMask, (luaP_opmodes[m] >> 2) & 3))
-#define testAMode(m)	(luaP_opmodes[m] & (1 << 6))
-#define testTMode(m)	(luaP_opmodes[m] & (1 << 7))
-
-
-LUAI_DATA const char *const luaP_opnames[NUM_OPCODES+1];  /* opcode names */
-
-
-/* number of list items to accumulate before a SETLIST instruction */
-#define LFIELDS_PER_FLUSH	50
-
-
-#endif



[31/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/mynewt.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/mynewt.c b/libs/baselibc/src/mynewt.c
deleted file mode 100644
index e35b39e..0000000
--- a/libs/baselibc/src/mynewt.c
+++ /dev/null
@@ -1,47 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include <stdio.h>
-#include <console/console.h>
-
-static size_t
-stdin_read(FILE *fp, char *bp, size_t n)
-{
-    return 0;
-}
-
-static size_t
-stdout_write(FILE *fp, const char *bp, size_t n)
-{
-    console_write(bp, n);
-    return n;
-}
-
-static struct File_methods _stdin_methods = {
-    .write = stdout_write,
-    .read = stdin_read
-};
-
-static struct File _stdin = {
-    .vmt = &_stdin_methods
-};
-
-struct File *const stdin = &_stdin;
-struct File *const stdout = &_stdin;
-struct File *const stderr = &_stdin;

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/nrand48.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/nrand48.c b/libs/baselibc/src/nrand48.c
deleted file mode 100644
index cb3532b..0000000
--- a/libs/baselibc/src/nrand48.c
+++ /dev/null
@@ -1,11 +0,0 @@
-/*
- * nrand48.c
- */
-
-#include <stdlib.h>
-#include <stdint.h>
-
-long nrand48(unsigned short xsubi[3])
-{
-	return (long)((uint32_t) jrand48(xsubi) >> 1);
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/qsort.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/qsort.c b/libs/baselibc/src/qsort.c
deleted file mode 100644
index 4c189fc..0000000
--- a/libs/baselibc/src/qsort.c
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * qsort.c
- *
- * This is actually combsort.  It's an O(n log n) algorithm with
- * simplicity/small code size being its main virtue.
- */
-
-#include <stddef.h>
-#include <stdlib.h>
-#include <string.h>
-
-static inline size_t newgap(size_t gap)
-{
-	gap = (gap * 10) / 13;
-	if (gap == 9 || gap == 10)
-		gap = 11;
-
-	if (gap < 1)
-		gap = 1;
-	return gap;
-}
-
-void qsort(void *base, size_t nmemb, size_t size,
-	   int (*compar) (const void *, const void *))
-{
-	size_t gap = nmemb;
-	size_t i, j;
-	char *p1, *p2;
-	int swapped;
-
-	if (!nmemb)
-		return;
-
-	do {
-		gap = newgap(gap);
-		swapped = 0;
-
-		for (i = 0, p1 = base; i < nmemb - gap; i++, p1 += size) {
-			j = i + gap;
-			if (compar(p1, p2 = (char *)base + j * size) > 0) {
-				memswap(p1, p2, size);
-				swapped = 1;
-			}
-		}
-	} while (gap > 1 || swapped);
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/realloc.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/realloc.c b/libs/baselibc/src/realloc.c
deleted file mode 100644
index 77e8acb..0000000
--- a/libs/baselibc/src/realloc.c
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * realloc.c
- */
-
-#include <stdlib.h>
-#include <string.h>
-
-#include "malloc.h"
-
-/* FIXME: This is cheesy, it should be fixed later */
-
-void *realloc(void *ptr, size_t size)
-{
-	struct free_arena_header *ah;
-	void *newptr;
-	size_t oldsize;
-
-	if (!ptr)
-		return malloc(size);
-
-	if (size == 0) {
-		free(ptr);
-		return NULL;
-	}
-
-	/* Add the obligatory arena header, and round up */
-	size = (size + 2 * sizeof(struct arena_header) - 1) & ARENA_SIZE_MASK;
-
-	ah = (struct free_arena_header *)
-	    ((struct arena_header *)ptr - 1);
-
-	if (ah->a.size >= size && size >= (ah->a.size >> 2)) {
-		/* This field is a good size already. */
-		return ptr;
-	} else {
-		/* Make me a new block.  This is kind of bogus; we should
-		   be checking the following block to see if we can do an
-		   in-place adjustment... fix that later. */
-
-		oldsize = ah->a.size - sizeof(struct arena_header);
-
-		newptr = malloc(size);
-                if(newptr) {
-                    memcpy(newptr, ptr, (size < oldsize) ? size : oldsize);
-                }
-		free(ptr);
-
-		return newptr;
-	}
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/sprintf.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/sprintf.c b/libs/baselibc/src/sprintf.c
deleted file mode 100644
index c6d8758..0000000
--- a/libs/baselibc/src/sprintf.c
+++ /dev/null
@@ -1,18 +0,0 @@
-/*
- * sprintf.c
- */
-
-#include <stdio.h>
-#include <unistd.h>
-
-int sprintf(char *buffer, const char *format, ...)
-{
-	va_list ap;
-	int rv;
-
-	va_start(ap, format);
-	rv = vsnprintf(buffer, ~(size_t) 0, format, ap);
-	va_end(ap);
-
-	return rv;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/srand48.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/srand48.c b/libs/baselibc/src/srand48.c
deleted file mode 100644
index e1c9567..0000000
--- a/libs/baselibc/src/srand48.c
+++ /dev/null
@@ -1,15 +0,0 @@
-/*
- * srand48.c
- */
-
-#include <stdlib.h>
-#include <stdint.h>
-
-unsigned short __rand48_seed[3];	/* Common with mrand48.c, lrand48.c */
-
-void srand48(long seedval)
-{
-	__rand48_seed[0] = 0x330e;
-	__rand48_seed[1] = (unsigned short)seedval;
-	__rand48_seed[2] = (unsigned short)((uint32_t) seedval >> 16);
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/sscanf.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/sscanf.c b/libs/baselibc/src/sscanf.c
deleted file mode 100644
index f53b276..0000000
--- a/libs/baselibc/src/sscanf.c
+++ /dev/null
@@ -1,17 +0,0 @@
-/*
- * sscanf()
- */
-
-#include <stdio.h>
-
-int sscanf(const char *str, const char *format, ...)
-{
-	va_list ap;
-	int rv;
-
-	va_start(ap, format);
-	rv = vsscanf(str, format, ap);
-	va_end(ap);
-
-	return rv;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/strcasecmp.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/strcasecmp.c b/libs/baselibc/src/strcasecmp.c
deleted file mode 100644
index ee1f28b..0000000
--- a/libs/baselibc/src/strcasecmp.c
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * strcasecmp.c
- */
-
-#include <string.h>
-#include <ctype.h>
-
-int strcasecmp(const char *s1, const char *s2)
-{
-	const unsigned char *c1 = (const unsigned char *)s1;
-	const unsigned char *c2 = (const unsigned char *)s2;
-	unsigned char ch;
-	int d = 0;
-
-	while (1) {
-		/* toupper() expects an unsigned char (implicitly cast to int)
-		   as input, and returns an int, which is exactly what we want. */
-		d = toupper(ch = *c1++) - toupper(*c2++);
-		if (d || !ch)
-			break;
-	}
-
-	return d;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/strcat.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/strcat.c b/libs/baselibc/src/strcat.c
deleted file mode 100644
index 6c5b673..0000000
--- a/libs/baselibc/src/strcat.c
+++ /dev/null
@@ -1,11 +0,0 @@
-/*
- * strcat.c
- */
-
-#include <string.h>
-
-char *strcat(char *dst, const char *src)
-{
-	strcpy(strchr(dst, '\0'), src);
-	return dst;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/strchr.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/strchr.c b/libs/baselibc/src/strchr.c
deleted file mode 100644
index 6a57313..0000000
--- a/libs/baselibc/src/strchr.c
+++ /dev/null
@@ -1,17 +0,0 @@
-/*
- * strchr.c
- */
-
-#include <string.h>
-
-char *strchr(const char *s, int c)
-{
-	while (*s != (char)c) {
-		if (!*s)
-			return NULL;
-		s++;
-	}
-
-	return (char *)s;
-}
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/strcmp.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/strcmp.c b/libs/baselibc/src/strcmp.c
deleted file mode 100644
index 3ab9f5a..0000000
--- a/libs/baselibc/src/strcmp.c
+++ /dev/null
@@ -1,21 +0,0 @@
-/*
- * strcmp.c
- */
-
-#include <string.h>
-
-int strcmp(const char *s1, const char *s2)
-{
-	const unsigned char *c1 = (const unsigned char *)s1;
-	const unsigned char *c2 = (const unsigned char *)s2;
-	unsigned char ch;
-	int d = 0;
-
-	while (1) {
-		d = (int)(ch = *c1++) - (int)*c2++;
-		if (d || !ch)
-			break;
-	}
-
-	return d;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/strcpy.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/strcpy.c b/libs/baselibc/src/strcpy.c
deleted file mode 100644
index aa656cf..0000000
--- a/libs/baselibc/src/strcpy.c
+++ /dev/null
@@ -1,20 +0,0 @@
-/*
- * strcpy.c
- *
- * strcpy()
- */
-
-#include <string.h>
-
-char *strcpy(char *dst, const char *src)
-{
-	char *q = dst;
-	const char *p = src;
-	char ch;
-
-	do {
-		*q++ = ch = *p++;
-	} while (ch);
-
-	return dst;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/strcspn.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/strcspn.c b/libs/baselibc/src/strcspn.c
deleted file mode 100644
index ba9e3be..0000000
--- a/libs/baselibc/src/strcspn.c
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
-FUNCTION
-	<<strcspn>>---count characters not in string
-
-INDEX
-	strcspn
-
-ANSI_SYNOPSIS
-	size_t strcspn(const char *<[s1]>, const char *<[s2]>);
-
-TRAD_SYNOPSIS
-	size_t strcspn(<[s1]>, <[s2]>)
-	char *<[s1]>;
-	char *<[s2]>;
-
-DESCRIPTION
-	This function computes the length of the initial part of
-	the string pointed to by <[s1]> which consists entirely of
-	characters <[NOT]> from the string pointed to by <[s2]>
-	(excluding the terminating null character).
-
-RETURNS
-	<<strcspn>> returns the length of the substring found.
-
-PORTABILITY
-<<strcspn>> is ANSI C.
-
-<<strcspn>> requires no supporting OS subroutines.
- */
-
-#include <string.h>
-
-size_t strcspn(const char *s1, const char *s2)
-{
-  const char *s = s1;
-  const char *c;
-
-  while (*s1)
-    {
-      for (c = s2; *c; c++)
-	{
-	  if (*s1 == *c)
-	    break;
-	}
-      if (*c)
-	break;
-      s1++;
-    }
-
-  return s1 - s;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/strdup.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/strdup.c b/libs/baselibc/src/strdup.c
deleted file mode 100644
index 905b51d..0000000
--- a/libs/baselibc/src/strdup.c
+++ /dev/null
@@ -1,17 +0,0 @@
-/*
- * strdup.c
- */
-
-#include <string.h>
-#include <stdlib.h>
-
-char *strdup(const char *s)
-{
-	int l = strlen(s) + 1;
-	char *d = malloc(l);
-
-	if (d)
-		memcpy(d, s, l);
-
-	return d;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/strlcat.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/strlcat.c b/libs/baselibc/src/strlcat.c
deleted file mode 100644
index 6d95087..0000000
--- a/libs/baselibc/src/strlcat.c
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * strlcat.c
- */
-
-#include <string.h>
-
-size_t strlcat(char *dst, const char *src, size_t size)
-{
-	size_t bytes = 0;
-	char *q = dst;
-	const char *p = src;
-	char ch;
-
-	while (bytes < size && *q) {
-		q++;
-		bytes++;
-	}
-	if (bytes == size)
-		return (bytes + strlen(src));
-
-	while ((ch = *p++)) {
-		if (bytes + 1 < size)
-			*q++ = ch;
-
-		bytes++;
-	}
-
-	*q = '\0';
-	return bytes;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/strlcpy.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/strlcpy.c b/libs/baselibc/src/strlcpy.c
deleted file mode 100644
index 3ec8fd2..0000000
--- a/libs/baselibc/src/strlcpy.c
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * strlcpy.c
- */
-
-#include <string.h>
-
-size_t strlcpy(char *dst, const char *src, size_t size)
-{
-	size_t bytes = 0;
-	char *q = dst;
-	const char *p = src;
-	char ch;
-
-	while ((ch = *p++)) {
-		if (bytes + 1 < size)
-			*q++ = ch;
-
-		bytes++;
-	}
-
-	/* If size == 0 there is no space for a final null... */
-	if (size)
-		*q = '\0';
-
-	return bytes;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/strlen.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/strlen.c b/libs/baselibc/src/strlen.c
deleted file mode 100644
index 86526a5..0000000
--- a/libs/baselibc/src/strlen.c
+++ /dev/null
@@ -1,13 +0,0 @@
-/*
- * strlen()
- */
-
-#include <string.h>
-
-size_t strlen(const char *s)
-{
-	const char *ss = s;
-	while (*ss)
-		ss++;
-	return ss - s;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/strncasecmp.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/strncasecmp.c b/libs/baselibc/src/strncasecmp.c
deleted file mode 100644
index 0551935..0000000
--- a/libs/baselibc/src/strncasecmp.c
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * strncasecmp.c
- */
-
-#include <string.h>
-#include <ctype.h>
-
-int strncasecmp(const char *s1, const char *s2, size_t n)
-{
-	const unsigned char *c1 = (const unsigned char *)s1;
-	const unsigned char *c2 = (const unsigned char *)s2;
-	unsigned char ch;
-	int d = 0;
-
-	while (n--) {
-		/* toupper() expects an unsigned char (implicitly cast to int)
-		   as input, and returns an int, which is exactly what we want. */
-		d = toupper(ch = *c1++) - toupper(*c2++);
-		if (d || !ch)
-			break;
-	}
-
-	return d;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/strncat.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/strncat.c b/libs/baselibc/src/strncat.c
deleted file mode 100644
index 5b86216..0000000
--- a/libs/baselibc/src/strncat.c
+++ /dev/null
@@ -1,21 +0,0 @@
-/*
- * strncat.c
- */
-
-#include <string.h>
-
-char *strncat(char *dst, const char *src, size_t n)
-{
-	char *q = strchr(dst, '\0');
-	const char *p = src;
-	char ch;
-
-	while (n--) {
-		*q++ = ch = *p++;
-		if (!ch)
-			return dst;
-	}
-	*q = '\0';
-
-	return dst;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/strncmp.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/strncmp.c b/libs/baselibc/src/strncmp.c
deleted file mode 100644
index 5235545..0000000
--- a/libs/baselibc/src/strncmp.c
+++ /dev/null
@@ -1,21 +0,0 @@
-/*
- * strncmp.c
- */
-
-#include <string.h>
-
-int strncmp(const char *s1, const char *s2, size_t n)
-{
-	const unsigned char *c1 = (const unsigned char *)s1;
-	const unsigned char *c2 = (const unsigned char *)s2;
-	unsigned char ch;
-	int d = 0;
-
-	while (n--) {
-		d = (int)(ch = *c1++) - (int)*c2++;
-		if (d || !ch)
-			break;
-	}
-
-	return d;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/strncpy.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/strncpy.c b/libs/baselibc/src/strncpy.c
deleted file mode 100644
index fffc118..0000000
--- a/libs/baselibc/src/strncpy.c
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * strncpy.c
- */
-
-#include <string.h>
-
-char *strncpy(char *dst, const char *src, size_t n)
-{
-	char *q = dst;
-	const char *p = src;
-	char ch;
-
-	while (n) {
-		n--;
-		*q++ = ch = *p++;
-		if (!ch)
-			break;
-	}
-
-	/* The specs say strncpy() fills the entire buffer with NUL.  Sigh. */
-	memset(q, 0, n);
-
-	return dst;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/strndup.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/strndup.c b/libs/baselibc/src/strndup.c
deleted file mode 100644
index 427162f..0000000
--- a/libs/baselibc/src/strndup.c
+++ /dev/null
@@ -1,19 +0,0 @@
-/*
- * strndup.c
- */
-
-#include <string.h>
-#include <stdlib.h>
-
-char *strndup(const char *s, size_t n)
-{
-	int l = n > strlen(s) ? strlen(s) + 1 : n + 1;
-	char *d = malloc(l);
-
-	if (!d)
-		return NULL;
-	
-	memcpy(d, s, l);
-	d[n] = '\0';
-	return d;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/strnlen.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/strnlen.c b/libs/baselibc/src/strnlen.c
deleted file mode 100644
index 1678f4b..0000000
--- a/libs/baselibc/src/strnlen.c
+++ /dev/null
@@ -1,18 +0,0 @@
-/*
- * strnlen()
- */
-
-#include <string.h>
-
-size_t strnlen(const char *s, size_t maxlen)
-{
-	const char *ss = s;
-
-	/* Important: the maxlen test must precede the reference through ss;
-	   since the byte beyond the maximum may segfault */
-	while ((maxlen > 0) && *ss) {
-		ss++;
-		maxlen--;
-	}
-	return ss - s;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/strntoimax.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/strntoimax.c b/libs/baselibc/src/strntoimax.c
deleted file mode 100644
index 179d9e5..0000000
--- a/libs/baselibc/src/strntoimax.c
+++ /dev/null
@@ -1,13 +0,0 @@
-/*
- * strntoimax.c
- *
- * strntoimax()
- */
-
-#include <stddef.h>
-#include <inttypes.h>
-
-intmax_t strntoimax(const char *nptr, char **endptr, int base, size_t n)
-{
-	return (intmax_t) strntoumax(nptr, endptr, base, n);
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/strntoumax.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/strntoumax.c b/libs/baselibc/src/strntoumax.c
deleted file mode 100644
index 56dddad..0000000
--- a/libs/baselibc/src/strntoumax.c
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * strntoumax.c
- *
- * The strntoumax() function and associated
- */
-
-#include <stddef.h>
-#include <stdint.h>
-#include <ctype.h>
-#include <inttypes.h>
-
-static inline int digitval(int ch)
-{
-	if (ch >= '0' && ch <= '9') {
-		return ch - '0';
-	} else if (ch >= 'A' && ch <= 'Z') {
-		return ch - 'A' + 10;
-	} else if (ch >= 'a' && ch <= 'z') {
-		return ch - 'a' + 10;
-	} else {
-		return -1;
-	}
-}
-
-uintmax_t strntoumax(const char *nptr, char **endptr, int base, size_t n)
-{
-	int minus = 0;
-	uintmax_t v = 0;
-	int d;
-
-	while (n && isspace((unsigned char)*nptr)) {
-		nptr++;
-		n--;
-	}
-
-	/* Single optional + or - */
-	if (n) {
-		char c = *nptr;
-		if (c == '-' || c == '+') {
-			minus = (c == '-');
-			nptr++;
-			n--;
-		}
-	}
-
-	if (base == 0) {
-		if (n >= 2 && nptr[0] == '0' &&
-		    (nptr[1] == 'x' || nptr[1] == 'X')) {
-			n -= 2;
-			nptr += 2;
-			base = 16;
-		} else if (n >= 1 && nptr[0] == '0') {
-			n--;
-			nptr++;
-			base = 8;
-		} else {
-			base = 10;
-		}
-	} else if (base == 16) {
-		if (n >= 2 && nptr[0] == '0' &&
-		    (nptr[1] == 'x' || nptr[1] == 'X')) {
-			n -= 2;
-			nptr += 2;
-		}
-	}
-
-	while (n && (d = digitval(*nptr)) >= 0 && d < base) {
-		v = v * base + d;
-		n--;
-		nptr++;
-	}
-
-	if (endptr)
-		*endptr = (char *)nptr;
-
-	return minus ? -v : v;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/strpbrk.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/strpbrk.c b/libs/baselibc/src/strpbrk.c
deleted file mode 100644
index 1873971..0000000
--- a/libs/baselibc/src/strpbrk.c
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
-FUNCTION
-	<<strpbrk>>---find characters in string
-
-INDEX
-	strpbrk
-
-ANSI_SYNOPSIS
-	#include <string.h>
-	char *strpbrk(const char *<[s1]>, const char *<[s2]>);
-
-TRAD_SYNOPSIS
-	#include <string.h>
-	char *strpbrk(<[s1]>, <[s2]>)
-	char *<[s1]>;
-	char *<[s2]>;
-
-DESCRIPTION
-	This function locates the first occurence in the string
-	pointed to by <[s1]> of any character in string pointed to by
-	<[s2]> (excluding the terminating null character).
-
-RETURNS
-	<<strpbrk>> returns a pointer to the character found in <[s1]>, or a
-	null pointer if no character from <[s2]> occurs in <[s1]>.
-
-PORTABILITY
-<<strpbrk>> requires no supporting OS subroutines.
-*/
-
-#include <string.h>
-
-char *strpbrk(const char *s1, const char *s2)
-{
-  const char *c = s2;
-  if (!*s1)
-    return (char *) NULL;
-
-  while (*s1)
-    {
-      for (c = s2; *c; c++)
-	{
-	  if (*s1 == *c)
-	    break;
-	}
-      if (*c)
-	break;
-      s1++;
-    }
-
-  if (*c == '\0')
-    s1 = NULL;
-
-  return (char *) s1;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/strrchr.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/strrchr.c b/libs/baselibc/src/strrchr.c
deleted file mode 100644
index 69b238f..0000000
--- a/libs/baselibc/src/strrchr.c
+++ /dev/null
@@ -1,19 +0,0 @@
-/*
- * strrchr.c
- */
-
-#include <string.h>
-
-char *strrchr(const char *s, int c)
-{
-	const char *found = NULL;
-
-	while (*s) {
-		if (*s == (char)c)
-			found = s;
-		s++;
-	}
-
-	return (char *)found;
-}
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/strsep.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/strsep.c b/libs/baselibc/src/strsep.c
deleted file mode 100644
index 44e76bd..0000000
--- a/libs/baselibc/src/strsep.c
+++ /dev/null
@@ -1,21 +0,0 @@
-/*
- * strsep.c
- */
-
-#include <string.h>
-
-char *strsep(char **stringp, const char *delim)
-{
-	char *s = *stringp;
-	char *e;
-
-	if (!s)
-		return NULL;
-
-	e = strpbrk(s, delim);
-	if (e)
-		*e++ = '\0';
-
-	*stringp = e;
-	return s;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/strspn.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/strspn.c b/libs/baselibc/src/strspn.c
deleted file mode 100644
index e8b213c..0000000
--- a/libs/baselibc/src/strspn.c
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
-FUNCTION
-	<<strspn>>---find initial match
-
-INDEX
-	strspn
-
-ANSI_SYNOPSIS
-	#include <string.h>
-	size_t strspn(const char *<[s1]>, const char *<[s2]>);
-
-TRAD_SYNOPSIS
-	#include <string.h>
-	size_t strspn(<[s1]>, <[s2]>)
-	char *<[s1]>;
-	char *<[s2]>;
-
-DESCRIPTION
-	This function computes the length of the initial segment of
-	the string pointed to by <[s1]> which consists entirely of
-	characters from the string pointed to by <[s2]> (excluding the
-	terminating null character).
-
-RETURNS
-	<<strspn>> returns the length of the segment found.
-
-PORTABILITY
-<<strspn>> is ANSI C.
-
-<<strspn>> requires no supporting OS subroutines.
-
-QUICKREF
-	strspn ansi pure
-*/
-
-#include <string.h>
-
-size_t strspn(const char *s1, const char *s2)
-{
-  const char *s = s1;
-  const char *c;
-
-  while (*s1)
-    {
-      for (c = s2; *c; c++)
-	{
-	  if (*s1 == *c)
-	    break;
-	}
-      if (*c == '\0')
-	break;
-      s1++;
-    }
-
-  return s1 - s;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/strstr.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/strstr.c b/libs/baselibc/src/strstr.c
deleted file mode 100644
index 8850858..0000000
--- a/libs/baselibc/src/strstr.c
+++ /dev/null
@@ -1,11 +0,0 @@
-/*
- * strstr.c
- */
-
-#include <string.h>
-
-char *strstr(const char *haystack, const char *needle)
-{
-	return (char *)memmem(haystack, strlen(haystack), needle,
-			      strlen(needle));
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/strtoimax.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/strtoimax.c b/libs/baselibc/src/strtoimax.c
deleted file mode 100644
index cd4fdca..0000000
--- a/libs/baselibc/src/strtoimax.c
+++ /dev/null
@@ -1,3 +0,0 @@
-#define TYPE intmax_t
-#define NAME strtoimax
-#include "templates/strtox.c.template"

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/strtok.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/strtok.c b/libs/baselibc/src/strtok.c
deleted file mode 100644
index 6b169a1..0000000
--- a/libs/baselibc/src/strtok.c
+++ /dev/null
@@ -1,12 +0,0 @@
-/*
- * strtok.c
- */
-
-#include <string.h>
-
-char *strtok(char *s, const char *delim)
-{
-	static char *holder;
-
-	return strtok_r(s, delim, &holder);
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/strtok_r.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/strtok_r.c b/libs/baselibc/src/strtok_r.c
deleted file mode 100644
index 695d516..0000000
--- a/libs/baselibc/src/strtok_r.c
+++ /dev/null
@@ -1,13 +0,0 @@
-#include <string.h>
-
-char *strtok_r(char *s, const char *delim, char **holder)
-{
-	if (s)
-		*holder = s;
-
-	do {
-		s = strsep(holder, delim);
-	} while (s && !*s);
-
-	return s;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/strtol.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/strtol.c b/libs/baselibc/src/strtol.c
deleted file mode 100644
index ab318cd..0000000
--- a/libs/baselibc/src/strtol.c
+++ /dev/null
@@ -1,3 +0,0 @@
-#define TYPE signed long
-#define NAME strtol
-#include "templates/strtox.c.template"

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/strtoll.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/strtoll.c b/libs/baselibc/src/strtoll.c
deleted file mode 100644
index ceb924d..0000000
--- a/libs/baselibc/src/strtoll.c
+++ /dev/null
@@ -1,3 +0,0 @@
-#define TYPE signed long long
-#define NAME strtoll
-#include "templates/strtox.c.template"

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/strtoul.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/strtoul.c b/libs/baselibc/src/strtoul.c
deleted file mode 100644
index d0201e1..0000000
--- a/libs/baselibc/src/strtoul.c
+++ /dev/null
@@ -1,3 +0,0 @@
-#define TYPE unsigned long
-#define NAME strtoul
-#include "templates/strtox.c.template"

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/strtoull.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/strtoull.c b/libs/baselibc/src/strtoull.c
deleted file mode 100644
index 2da622a..0000000
--- a/libs/baselibc/src/strtoull.c
+++ /dev/null
@@ -1,3 +0,0 @@
-#define TYPE unsigned long long
-#define NAME strtoull
-#include "templates/strtox.c.template"

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/strtoumax.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/strtoumax.c b/libs/baselibc/src/strtoumax.c
deleted file mode 100644
index c49d125..0000000
--- a/libs/baselibc/src/strtoumax.c
+++ /dev/null
@@ -1,3 +0,0 @@
-#define TYPE uintmax_t
-#define NAME strtoumax
-#include "templates/strtox.c.template"

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/templates/atox.c.template
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/templates/atox.c.template b/libs/baselibc/src/templates/atox.c.template
deleted file mode 100644
index c013bb4..0000000
--- a/libs/baselibc/src/templates/atox.c.template
+++ /dev/null
@@ -1,14 +0,0 @@
-/*
- * atox.c
- *
- * atoi(), atol(), atoll()
- */
-
-#include <inttypes.h>
-#include <stdlib.h>
-#include <stdio.h>
-
-TYPE NAME(const char *nptr)
-{
-	return (TYPE) strntoumax(nptr, (char **)NULL, 10, ~(size_t) 0);
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/templates/strtox.c.template
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/templates/strtox.c.template b/libs/baselibc/src/templates/strtox.c.template
deleted file mode 100644
index c22e7c7..0000000
--- a/libs/baselibc/src/templates/strtox.c.template
+++ /dev/null
@@ -1,14 +0,0 @@
-/*
- * strtox.c
- *
- * strto...() functions, by macro definition
- */
-
-#include <stddef.h>
-#include <stdlib.h>
-#include <inttypes.h>
-
-TYPE NAME(const char *nptr, char **endptr, int base)
-{
-	return (TYPE) strntoumax(nptr, endptr, base, ~(size_t) 0);
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/tinyprintf.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/tinyprintf.c b/libs/baselibc/src/tinyprintf.c
deleted file mode 100644
index e48be4a..0000000
--- a/libs/baselibc/src/tinyprintf.c
+++ /dev/null
@@ -1,362 +0,0 @@
-/*
-File: tinyprintf.c
-
-Copyright (C) 2004  Kustaa Nyholm
-Copyright (C) 2010  CJlano
-Copyright (C) 2011  Petteri Aimonen
-
-This file is dual-licensed. You can use either of these licenses:
-
-1) GNU LGPL
-This library is free software; you can redistribute it and/or
-modify it under the terms of the GNU Lesser General Public
-License as published by the Free Software Foundation; either
-version 2.1 of the License, or (at your option) any later version.
-
-This library is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-Lesser General Public License for more details.
-
-You should have received a copy of the GNU Lesser General Public
-License along with this library; if not, write to the Free Software
-Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
-
-2) BSD
-Copyright (c) 2004,2012 Kustaa Nyholm / SpareTimeLabs
-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 Kustaa Nyholm or SpareTimeLabs 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 COPYRIGHT HOLDER 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.
-
-*/
-
-/* This is a smaller implementation of printf-family of functions,
- * based on tinyprintf code by Kustaa Nyholm.
- * The formats supported by this implementation are: 'd' 'u' 'c' 's' 'x' 'X'.
- * Zero padding and field width are also supported.
- * If the library is compiled with 'PRINTF_SUPPORT_LONG' defined then the
- * long specifier is also supported.
- * Otherwise it is ignored, so on 32 bit platforms there is no point to use
- * PRINTF_SUPPORT_LONG because int == long.
- */
-
-#include <stdio.h>
-
-struct param {
-    unsigned char width; /**< field width */
-    char lz;            /**< Leading zeros */
-    char sign:1;        /**<  The sign to display (if any) */
-    char alt:1;         /**< alternate form */
-    char uc:1;          /**<  Upper case (for base16 only) */
-    char base;  /**<  number base (e.g.: 8, 10, 16) */
-    char *bf;           /**<  Buffer to output */
-};
-
-static void ui2a(unsigned long long int num, struct param *p)
-{
-    int n = 0;
-    unsigned long long int d = 1;
-    char *bf = p->bf;
-    while (num / d >= p->base)
-        d *= p->base;
-    while (d != 0) {
-        unsigned long long  dgt = num / d;
-        num %= d;
-        d /= p->base;
-        if (n || dgt > 0 || d == 0) {
-            *bf++ = dgt + (dgt < 10 ? '0' : (p->uc ? 'A' : 'a') - 10);
-            ++n;
-        }
-    }
-    *bf = 0;
-}
-
-static void i2a(long long int num, struct param *p)
-{
-    if (num < 0) {
-        num = -num;
-        p->sign = 1;
-    }
-    ui2a(num, p);
-}
-
-static int a2d(char ch)
-{
-    if (ch >= '0' && ch <= '9')
-        return ch - '0';
-    else if (ch >= 'a' && ch <= 'f')
-        return ch - 'a' + 10;
-    else if (ch >= 'A' && ch <= 'F')
-        return ch - 'A' + 10;
-    else
-        return -1;
-}
-
-static char a2i(char ch, const char **src, int base, unsigned char *nump)
-{
-    const char *p = *src;
-    int num = 0;
-    int digit;
-    while ((digit = a2d(ch)) >= 0) {
-        if (digit > base)
-            break;
-        num = num * base + digit;
-        ch = *p++;
-    }
-    *src = p;
-    *nump = num;
-    return ch;
-}
-
-static int putf(FILE *putp, char c)
-{
-    if (fputc(c, putp) == EOF)
-        return 0;
-    else
-        return 1;
-}
-
-static unsigned putchw(FILE *putp, struct param *p)
-{
-    unsigned written = 0;
-    char ch;
-    int n = p->width;
-    char *bf = p->bf;
-
-    /* Number of filling characters */
-    while (*bf++ && n > 0)
-        n--;
-    if (p->sign)
-        n--;
-    if (p->alt && p->base == 16)
-        n -= 2;
-    else if (p->alt && p->base == 8)
-        n--;
-
-    /* Fill with space, before alternate or sign */
-    if (!p->lz) {
-        while (n-- > 0)
-            written += putf(putp, ' ');
-    }
-
-    /* print sign */
-    if (p->sign)
-        written += putf(putp, '-');
-
-    /* Alternate */
-    if (p->alt && p->base == 16) {
-        written += putf(putp, '0');
-        written += putf(putp, (p->uc ? 'X' : 'x'));
-    } else if (p->alt && p->base == 8) {
-        written += putf(putp, '0');
-    }
-
-    /* Fill with zeros, after alternate or sign */
-    if (p->lz) {
-        while (n-- > 0)
-            written += putf(putp, '0');
-    }
-
-    /* Put actual buffer */
-    bf = p->bf;
-    while ((ch = *bf++))
-        written += putf(putp, ch);
-    
-    return written;
-}
-
-static unsigned long long
-intarg(int lng, int sign, va_list *va)
-{
-    unsigned long long val;
-
-    switch (lng) {
-    case 0:
-        if (sign) {
-            val = va_arg(*va, int);
-        } else {
-            val = va_arg(*va, unsigned int);
-        }
-        break;
-
-    case 1:
-        if (sign) {
-            val = va_arg(*va, long);
-        } else {
-            val = va_arg(*va, unsigned long);
-        }
-        break;
-
-    case 2:
-    default:
-        /* Pull the 64-bit number off the stack as a pair of 32-bit integers.
-         * The va_arg macro was reading from the wrong location when a 64-bit
-         * type was specified.
-         */
-        /* XXX: Look into this; may just be an incorrect setting when the
-         * compiler / newlib was built.
-         */
-        val = va_arg(*va, unsigned long);
-        val |= (unsigned long long)(va_arg(*va, unsigned long)) << 32;
-        break;
-    }
-
-    return val;
-}
-
-size_t tfp_format(FILE *putp, const char *fmt, va_list va)
-{
-    size_t written = 0;
-    struct param p;
-    char bf[23];
-    char ch;
-    char lng;
-
-    p.bf = bf;
-
-    while ((ch = *(fmt++))) {
-        if (ch != '%') {
-            written += putf(putp, ch);
-        } else {
-            /* Init parameter struct */
-            p.lz = 0;
-            p.alt = 0;
-            p.width = 0;
-            p.sign = 0;
-            lng = 0;
-
-            /* Flags */
-            while ((ch = *(fmt++))) {
-                switch (ch) {
-                case '0':
-                    p.lz = 1;
-                    continue;
-                case '#':
-                    p.alt = 1;
-                    continue;
-                default:
-                    break;
-                }
-                break;
-            }
-
-            /* Width */
-            if (ch >= '0' && ch <= '9') {
-                ch = a2i(ch, &fmt, 10, &(p.width));
-            }
-            if (ch == 'l') {
-                ch = *(fmt++);
-                lng = 1;
-
-                if (ch == 'l') {
-                    ch = *(fmt++);
-                    lng = 2;
-                }
-            }
-
-            switch (ch) {
-            case 0:
-                goto abort;
-            case 'u':
-                p.base = 10;
-                ui2a(intarg(lng, 0, &va), &p);
-                written += putchw(putp, &p);
-                break;
-            case 'd':
-            case 'i':
-                p.base = 10;
-                i2a(intarg(lng, 1, &va), &p);
-                written += putchw(putp, &p);
-                break;
-            case 'x':
-            case 'X':
-                p.base = 16;
-                p.uc = (ch == 'X');
-                ui2a(intarg(lng, 0, &va), &p);
-                written += putchw(putp, &p);
-                break;
-            case 'o':
-                p.base = 8;
-                ui2a(intarg(lng, 0, &va), &p);
-                written += putchw(putp, &p);
-                break;
-            case 'c':
-                written += putf(putp, (char)(va_arg(va, int)));
-                break;
-            case 's':
-                p.bf = va_arg(va, char *);
-                written += putchw(putp, &p);
-                p.bf = bf;
-                break;
-            case '%':
-                written += putf(putp, ch);
-            default:
-                break;
-            }
-        }
-    }
- abort:;
- 
- return written;
-}
-
-int vfprintf(FILE *f, const char *fmt, va_list va)
-{
-    return tfp_format(f, fmt, va);
-}
-
-int fprintf(FILE *f, const char *fmt, ...)
-{
-    va_list va;
-    va_start(va, fmt);
-    int rv = vfprintf(f, fmt, va);
-    va_end(va);
-    return rv;
-}
-
-int printf(const char *fmt, ...)
-{
-    va_list va;
-    va_start(va, fmt);
-    int rv = vfprintf(stdout, fmt, va);
-    va_end(va);
-    return rv;
-}
-
-int vsnprintf(char *str, size_t size, const char *fmt, va_list va)
-{
-    struct MemFile state;
-    FILE *f = fmemopen_w(&state, str, size - 1);
-    tfp_format(f, fmt, va);
-    *(state.buffer) = '\0';
-    return state.bytes_written;
-}
-
-int snprintf(char *str, size_t size, const char *fmt, ...)
-{
-    va_list va;
-    va_start(va, fmt);
-    int rv = vsnprintf(str, size, fmt, va);
-    va_end(va);
-    return rv;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/vasprintf.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/vasprintf.c b/libs/baselibc/src/vasprintf.c
deleted file mode 100644
index cdc302f..0000000
--- a/libs/baselibc/src/vasprintf.c
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * vasprintf.c
- */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <stdarg.h>
-
-int vasprintf(char **bufp, const char *format, va_list ap)
-{
-	va_list ap1;
-	int bytes;
-	char *p;
-
-	va_copy(ap1, ap);
-
-	bytes = vsnprintf(NULL, 0, format, ap1) + 1;
-	va_end(ap1);
-
-	*bufp = p = malloc(bytes);
-	if (!p)
-		return -1;
-
-	return vsnprintf(p, bytes, format, ap);
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/vprintf.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/vprintf.c b/libs/baselibc/src/vprintf.c
deleted file mode 100644
index d6bfeaf..0000000
--- a/libs/baselibc/src/vprintf.c
+++ /dev/null
@@ -1,11 +0,0 @@
-/*
- * vprintf.c
- */
-
-#include <stdio.h>
-#include <stdarg.h>
-
-int vprintf(const char *format, va_list ap)
-{
-	return vfprintf(stdout, format, ap);
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/vsprintf.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/vsprintf.c b/libs/baselibc/src/vsprintf.c
deleted file mode 100644
index 51f5d87..0000000
--- a/libs/baselibc/src/vsprintf.c
+++ /dev/null
@@ -1,11 +0,0 @@
-/*
- * vsprintf.c
- */
-
-#include <stdio.h>
-#include <unistd.h>
-
-int vsprintf(char *buffer, const char *format, va_list ap)
-{
-	return vsnprintf(buffer, ~(size_t) 0, format, ap);
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/baselibc/src/vsscanf.c
----------------------------------------------------------------------
diff --git a/libs/baselibc/src/vsscanf.c b/libs/baselibc/src/vsscanf.c
deleted file mode 100644
index 60eaca6..0000000
--- a/libs/baselibc/src/vsscanf.c
+++ /dev/null
@@ -1,400 +0,0 @@
-/*
- * vsscanf.c
- *
- * vsscanf(), from which the rest of the scanf()
- * family is built
- */
-
-#include <ctype.h>
-#include <stdarg.h>
-#include <stddef.h>
-#include <inttypes.h>
-#include <string.h>
-#include <limits.h>
-#include <stdio.h>
-
-#ifndef LONG_BIT
-#define LONG_BIT (CHAR_BIT*sizeof(long))
-#endif
-
-enum flags {
-	FL_SPLAT = 0x01,	/* Drop the value, do not assign */
-	FL_INV   = 0x02,	/* Character-set with inverse */
-	FL_WIDTH = 0x04,	/* Field width specified */
-	FL_MINUS = 0x08,	/* Negative number */
-};
-
-enum ranks {
-	rank_char     = -2,
-	rank_short    = -1,
-	rank_int      = 0,
-	rank_long     = 1,
-	rank_longlong = 2,
-	rank_ptr      = INT_MAX	/* Special value used for pointers */
-};
-
-#define MIN_RANK	rank_char
-#define MAX_RANK	rank_longlong
-
-#define INTMAX_RANK	rank_longlong
-#define SIZE_T_RANK	rank_long
-#define PTRDIFF_T_RANK	rank_long
-
-enum bail {
-	bail_none = 0,		/* No error condition */
-	bail_eof,		/* Hit EOF */
-	bail_err		/* Conversion mismatch */
-};
-
-static inline const char *skipspace(const char *p)
-{
-	while (isspace((unsigned char)*p))
-		p++;
-	return p;
-}
-
-#undef set_bit
-static inline void set_bit(unsigned long *bitmap, unsigned int bit)
-{
-	bitmap[bit / LONG_BIT] |= 1UL << (bit % LONG_BIT);
-}
-
-#undef test_bit
-static inline int test_bit(unsigned long *bitmap, unsigned int bit)
-{
-	return (int)(bitmap[bit / LONG_BIT] >> (bit % LONG_BIT)) & 1;
-}
-
-int vsscanf(const char *buffer, const char *format, va_list ap)
-{
-	const char *p = format;
-	char ch;
-	unsigned char uc;
-	const char *q = buffer;
-	const char *qq;
-	uintmax_t val = 0;
-	int rank = rank_int;	/* Default rank */
-	unsigned int width = UINT_MAX;
-	int base;
-	enum flags flags = 0;
-	enum {
-		st_normal,	/* Ground state */
-		st_flags,	/* Special flags */
-		st_width,	/* Field width */
-		st_modifiers,	/* Length or conversion modifiers */
-		st_match_init,	/* Initial state of %[ sequence */
-		st_match,	/* Main state of %[ sequence */
-		st_match_range,	/* After - in a %[ sequence */
-	} state = st_normal;
-	char *sarg = NULL;	/* %s %c or %[ string argument */
-	enum bail bail = bail_none;
-	int sign;
-	int converted = 0;	/* Successful conversions */
-	unsigned long matchmap[((1 << CHAR_BIT) + (LONG_BIT - 1)) / LONG_BIT];
-	int matchinv = 0;	/* Is match map inverted? */
-	unsigned char range_start = 0;
-	(void)sign;
-
-	while ((ch = *p++) && !bail) {
-		switch (state) {
-		case st_normal:
-			if (ch == '%') {
-				state = st_flags;
-				flags = 0;
-				rank = rank_int;
-				width = UINT_MAX;
-			} else if (isspace((unsigned char)ch)) {
-				q = skipspace(q);
-			} else {
-				if (*q == ch)
-					q++;
-				else
-					bail = bail_err; /* Match failure */
-			}
-			break;
-
-		case st_flags:
-			switch (ch) {
-			case '*':
-				flags |= FL_SPLAT;
-				break;
-			case '0'...'9':
-				width = (ch - '0');
-				state = st_width;
-				flags |= FL_WIDTH;
-				break;
-			default:
-				state = st_modifiers;
-				p--;	/* Process this character again */
-				break;
-			}
-			break;
-
-		case st_width:
-			if (ch >= '0' && ch <= '9') {
-				width = width * 10 + (ch - '0');
-			} else {
-				state = st_modifiers;
-				p--;	/* Process this character again */
-			}
-			break;
-
-		case st_modifiers:
-			switch (ch) {
-				/* Length modifiers - nonterminal sequences */
-			case 'h':
-				rank--;	/* Shorter rank */
-				break;
-			case 'l':
-				rank++;	/* Longer rank */
-				break;
-			case 'j':
-				rank = INTMAX_RANK;
-				break;
-			case 'z':
-				rank = SIZE_T_RANK;
-				break;
-			case 't':
-				rank = PTRDIFF_T_RANK;
-				break;
-			case 'L':
-			case 'q':
-				rank = rank_longlong;	/* long double/long long */
-				break;
-
-			default:
-				/* Output modifiers - terminal sequences */
-				/* Next state will be normal */
-				state = st_normal;
-
-				/* Canonicalize rank */
-				if (rank < MIN_RANK)
-					rank = MIN_RANK;
-				else if (rank > MAX_RANK)
-					rank = MAX_RANK;
-
-				switch (ch) {
-				case 'P':	/* Upper case pointer */
-				case 'p':	/* Pointer */
-					rank = rank_ptr;
-					base = 0;
-					sign = 0;
-					goto scan_int;
-
-				case 'i':	/* Base-independent integer */
-					base = 0;
-					sign = 1;
-					goto scan_int;
-
-				case 'd':	/* Decimal integer */
-					base = 10;
-					sign = 1;
-					goto scan_int;
-
-				case 'o':	/* Octal integer */
-					base = 8;
-					sign = 0;
-					goto scan_int;
-
-				case 'u':	/* Unsigned decimal integer */
-					base = 10;
-					sign = 0;
-					goto scan_int;
-
-				case 'x':	/* Hexadecimal integer */
-				case 'X':
-					base = 16;
-					sign = 0;
-					goto scan_int;
-
-				case 'n':	/* # of characters consumed */
-					val = (q - buffer);
-					goto set_integer;
-
-				      scan_int:
-					q = skipspace(q);
-					if (!*q) {
-						bail = bail_eof;
-						break;
-					}
-					val =
-					    strntoumax(q, (char **)&qq, base,
-						       width);
-					if (qq == q) {
-						bail = bail_err;
-						break;
-					}
-					q = qq;
-					if (!(flags & FL_SPLAT))
-						converted++;
-					/* fall through */
-
-				      set_integer:
-					if (!(flags & FL_SPLAT)) {
-						switch (rank) {
-						case rank_char:
-							*va_arg(ap,
-								unsigned char *)
-								= val;
-							break;
-						case rank_short:
-							*va_arg(ap,
-								unsigned short
-								*) = val;
-							break;
-						case rank_int:
-							*va_arg(ap,
-								unsigned int *)
-							    = val;
-							break;
-						case rank_long:
-							*va_arg(ap,
-								unsigned long *)
-								= val;
-							break;
-						case rank_longlong:
-							*va_arg(ap,
-								unsigned long
-								long *) = val;
-							break;
-						case rank_ptr:
-							*va_arg(ap, void **) =
-								(void *)
-								(uintptr_t)val;
-							break;
-						}
-					}
-					break;
-
-				case 'c':	/* Character */
-					/* Default width == 1 */
-					width = (flags & FL_WIDTH) ? width : 1;
-					if (flags & FL_SPLAT) {
-						while (width--) {
-							if (!*q) {
-								bail = bail_eof;
-								break;
-							}
-						}
-					} else {
-						sarg = va_arg(ap, char *);
-						while (width--) {
-							if (!*q) {
-								bail = bail_eof;
-								break;
-							}
-							*sarg++ = *q++;
-						}
-						if (!bail)
-							converted++;
-					}
-					break;
-
-				case 's':	/* String */
-					uc = 1;	/* Anything nonzero */
-					if (flags & FL_SPLAT) {
-						while (width-- && (uc = *q) &&
-						       !isspace(uc)) {
-							q++;
-						}
-					} else {
-						char *sp;
-						sp = sarg = va_arg(ap, char *);
-						while (width-- && (uc = *q) &&
-						       !isspace(uc)) {
-							*sp++ = uc;
-							q++;
-						}
-						if (sarg != sp) {
-							/* Terminate output */
-							*sp = '\0';
-							converted++;
-						}
-					}
-					if (!uc)
-						bail = bail_eof;
-					break;
-
-				case '[':	/* Character range */
-					sarg = (flags & FL_SPLAT) ? NULL
-						: va_arg(ap, char *);
-					state = st_match_init;
-					matchinv = 0;
-					memset(matchmap, 0, sizeof matchmap);
-					break;
-
-				case '%':	/* %% sequence */
-					if (*q == '%')
-						q++;
-					else
-						bail = bail_err;
-					break;
-
-				default:	/* Anything else */
-					/* Unknown sequence */
-					bail = bail_err;
-					break;
-				}
-			}
-			break;
-
-		case st_match_init:	/* Initial state for %[ match */
-			if (ch == '^' && !(flags & FL_INV)) {
-				matchinv = 1;
-			} else {
-				set_bit(matchmap, (unsigned char)ch);
-				state = st_match;
-			}
-			break;
-
-		case st_match:	/* Main state for %[ match */
-			if (ch == ']') {
-				goto match_run;
-			} else if (ch == '-') {
-				range_start = (unsigned char)ch;
-				state = st_match_range;
-			} else {
-				set_bit(matchmap, (unsigned char)ch);
-			}
-			break;
-
-		case st_match_range:	/* %[ match after - */
-			if (ch == ']') {
-				/* - was last character */
-				set_bit(matchmap, (unsigned char)'-');
-				goto match_run;
-			} else {
-				int i;
-				for (i = range_start; i < (unsigned char)ch;
-				     i++)
-					set_bit(matchmap, i);
-				state = st_match;
-			}
-			break;
-
-		      match_run:	/* Match expression finished */
-			qq = q;
-			uc = 1;	/* Anything nonzero */
-			while (width && (uc = *q)
-			       && test_bit(matchmap, uc)^matchinv) {
-				if (sarg)
-					*sarg++ = uc;
-				q++;
-			}
-			if (q != qq && sarg) {
-				*sarg = '\0';
-				converted++;
-			} else {
-				bail = bail_err;
-			}
-			if (!uc)
-				bail = bail_eof;
-			break;
-		}
-	}
-
-	if (bail == bail_eof && !converted)
-		converted = -1;	/* Return EOF (-1) */
-
-	return converted;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/bleuart/include/bleuart/bleuart.h
----------------------------------------------------------------------
diff --git a/libs/bleuart/include/bleuart/bleuart.h b/libs/bleuart/include/bleuart/bleuart.h
deleted file mode 100644
index 6639747..0000000
--- a/libs/bleuart/include/bleuart/bleuart.h
+++ /dev/null
@@ -1,34 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 _BLEUART_H_
-#define _BLEUART_H_
-
-void
-bleuart_init(void);
-int
-bleuart_svc_register(void);
-int
-bleuart_gatt_svr_init(void);
-void
-bleuart_set_conn_handle(uint16_t conn_handle);
-
-extern const uint8_t gatt_svr_svc_uart[16];
-
-#endif /* _BLEUART_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/bleuart/pkg.yml
----------------------------------------------------------------------
diff --git a/libs/bleuart/pkg.yml b/libs/bleuart/pkg.yml
deleted file mode 100644
index 272f53d..0000000
--- a/libs/bleuart/pkg.yml
+++ /dev/null
@@ -1,42 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you 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.
-#
-
-pkg.name: libs/bleuart
-pkg.description: BLE uart service.
-pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
-pkg.homepage: "http://mynewt.apache.org/"
-pkg.keywords:
-    - ble
-    - bluetooth
-    - uart
-
-pkg.deps:
-    - libs/os
-    - net/nimble/host
-
-pkg.req_apis:
-    - console
-
-pkg.init_function: bleuart_init
-pkg.init_stage: 5
-
-pkg.syscfg_defs:
-    BLEUART_MAX_INPUT:
-        description: 'TBD'
-        value: 120

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/bleuart/src/bleuart.c
----------------------------------------------------------------------
diff --git a/libs/bleuart/src/bleuart.c b/libs/bleuart/src/bleuart.c
deleted file mode 100644
index b7b2591..0000000
--- a/libs/bleuart/src/bleuart.c
+++ /dev/null
@@ -1,201 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include <assert.h>
-#include <stdio.h>
-#include <string.h>
-
-#include "sysinit/sysinit.h"
-#include "host/ble_hs.h"
-#include "bleuart/bleuart.h"
-#include "os/endian.h"
-#include "console/console.h"
-
-/* ble uart attr read handle */
-uint16_t g_bleuart_attr_read_handle;
-
-/* ble uart attr write handle */
-uint16_t g_bleuart_attr_write_handle;
-
-/* Pointer to a console buffer */
-char *console_buf;
-
-uint16_t g_console_conn_handle;
-/**
- * The vendor specific "bleuart" service consists of one write no-rsp characteristic
- * and one notification only read charateristic
- *     o "write no-rsp": a single-byte characteristic that can be written only
- *       over a non-encrypted connection
- *     o "read": a single-byte characteristic that can always be read only via
- *       notifications
- */
-
-/* {6E400001-B5A3-F393-E0A9-E50E24DCCA9E} */
-const uint8_t gatt_svr_svc_uart[16] = {
-    0x9e, 0xca, 0xdc, 0x24, 0x0e, 0xe5, 0xa9, 0xe0,
-    0x93, 0xf3, 0xa3, 0xb5, 0x01, 0x00, 0x40, 0x6e
-};
-
-/* {6E400002-B5A3-F393-E0A9-E50E24DCCA9E} */
-const uint8_t gatt_svr_chr_uart_write[16] = {
-    0x9e, 0xca, 0xdc, 0x24, 0x0e, 0xe5, 0xa9, 0xe0,
-    0x93, 0xf3, 0xa3, 0xb5, 0x02, 0x00, 0x40, 0x6e
-};
-
-
-/* {6E400003-B5A3-F393-E0A9-E50E24DCCA9E} */
-const uint8_t gatt_svr_chr_uart_read[16] = {
-    0x9e, 0xca, 0xdc, 0x24, 0x0e, 0xe5, 0xa9, 0xe0,
-    0x93, 0xf3, 0xa3, 0xb5, 0x03, 0x00, 0x40, 0x6e
-};
-
-static int
-gatt_svr_chr_access_uart_write(uint16_t conn_handle, uint16_t attr_handle,
-                              struct ble_gatt_access_ctxt *ctxt, void *arg);
-
-static const struct ble_gatt_svc_def gatt_svr_svcs[] = {
-    {
-        /* Service: uart */
-        .type = BLE_GATT_SVC_TYPE_PRIMARY,
-        .uuid128 = (void *)gatt_svr_svc_uart,
-        .characteristics = (struct ble_gatt_chr_def[]) { {
-            .uuid128 = gatt_svr_chr_uart_read,
-            .val_handle = &g_bleuart_attr_read_handle,
-            .access_cb = gatt_svr_chr_access_uart_write,
-            .flags = BLE_GATT_CHR_F_NOTIFY,
-        }, {
-            /* Characteristic: Write */
-            .uuid128 = (void *)gatt_svr_chr_uart_write,
-            .access_cb = gatt_svr_chr_access_uart_write,
-            .flags = BLE_GATT_CHR_F_WRITE | BLE_GATT_CHR_F_WRITE_NO_RSP,
-            .val_handle = &g_bleuart_attr_write_handle,
-        }, {
-            0, /* No more characteristics in this service */
-        } },
-    },
-
-    {
-        0, /* No more services */
-    },
-};
-
-static int
-gatt_svr_chr_access_uart_write(uint16_t conn_handle, uint16_t attr_handle,
-                               struct ble_gatt_access_ctxt *ctxt, void *arg)
-{
-    struct os_mbuf *om = ctxt->om;
-    switch (ctxt->op) {
-        case BLE_GATT_ACCESS_OP_WRITE_CHR:
-              while(om) {
-                  console_write((char *)om->om_data, om->om_len);
-                  om = SLIST_NEXT(om, om_next);
-              }
-              console_write("\n", 1);
-              return 0;
-        default:
-            assert(0);
-            return BLE_ATT_ERR_UNLIKELY;
-    }
-}
-
-/**
- * bleuart GATT server initialization
- *
- * @param eventq
- * @return 0 on success; non-zero on failure
- */
-int
-bleuart_gatt_svr_init(void)
-{
-    int rc;
-
-    rc = ble_gatts_count_cfg(gatt_svr_svcs);
-    if (rc != 0) {
-        goto err;
-    }
-
-    rc = ble_gatts_add_svcs(gatt_svr_svcs);
-    if (rc != 0) {
-        return rc;
-    }
-
-err:
-    return rc;
-}
-
-/**
- * Reads console and sends data over BLE
- */
-static void
-bleuart_uart_read(void)
-{
-    int rc;
-    int off;
-    int full_line;
-    struct os_mbuf *om;
-
-    off = 0;
-    while (1) {
-        rc = console_read(console_buf + off,
-                          MYNEWT_VAL(BLEUART_MAX_INPUT) - off, &full_line);
-        if (rc <= 0 && !full_line) {
-            continue;
-        }
-        off += rc;
-        if (!full_line) {
-            continue;
-        }
-
-        om = ble_hs_mbuf_from_flat(console_buf, off);
-        if (!om) {
-            return;
-        }
-        ble_gattc_notify_custom(g_console_conn_handle,
-                                g_bleuart_attr_read_handle, om);
-        off = 0;
-        break;
-    }
-}
-
-/**
- * Sets the global connection handle
- *
- * @param connection handle
- */
-void
-bleuart_set_conn_handle(uint16_t conn_handle) {
-    g_console_conn_handle = conn_handle;
-}
-
-/**
- * BLEuart console initialization
- *
- * @param Maximum input
- */
-void
-bleuart_init(void)
-{
-    int rc;
-
-    rc = console_init(bleuart_uart_read);
-    SYSINIT_PANIC_ASSERT(rc == 0);
-
-    console_buf = malloc(MYNEWT_VAL(BLEUART_MAX_INPUT));
-    SYSINIT_PANIC_ASSERT(console_buf != NULL);
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/boot_serial/include/boot_serial/boot_serial.h
----------------------------------------------------------------------
diff --git a/libs/boot_serial/include/boot_serial/boot_serial.h b/libs/boot_serial/include/boot_serial/boot_serial.h
deleted file mode 100644
index 67fa415..0000000
--- a/libs/boot_serial/include/boot_serial/boot_serial.h
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 __BOOT_SERIAL_H__
-#define __BOOT_SERIAL_H__
-
-/*
- * Create a task for uploading image0 over serial.
- *
- * Task opens console serial port and waits for download command.
- * Return code 0 means new image was uploaded, non-zero means that
- * there was an error.
- */
-int boot_serial_task_init(struct os_task *task, uint8_t prio,
-  os_stack_t *stack, uint16_t stack_size, int max_input);
-
-#endif /*  __BOOT_SERIAL_H__ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/boot_serial/pkg.yml
----------------------------------------------------------------------
diff --git a/libs/boot_serial/pkg.yml b/libs/boot_serial/pkg.yml
deleted file mode 100644
index b556e13..0000000
--- a/libs/boot_serial/pkg.yml
+++ /dev/null
@@ -1,35 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you 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.
-#
-
-pkg.name: libs/boot_serial
-pkg.description: The boot_serial library is used when downloading image over serial port.
-pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
-pkg.homepage: "http://mynewt.apache.org/"
-pkg.keywords:
-    - boot
-    - bootloader
-
-pkg.deps:
-    - hw/hal
-    - libs/os
-    - libs/bootutil
-    - libs/util
-
-pkg.req_apis:
-    - console

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/boot_serial/src/boot_serial.c
----------------------------------------------------------------------
diff --git a/libs/boot_serial/src/boot_serial.c b/libs/boot_serial/src/boot_serial.c
deleted file mode 100644
index c8dfaf4..0000000
--- a/libs/boot_serial/src/boot_serial.c
+++ /dev/null
@@ -1,403 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-#include <assert.h>
-#include <stddef.h>
-#include <inttypes.h>
-#include <ctype.h>
-#include <stdio.h>
-
-#include <bsp/bsp.h>
-
-#include <hal/flash_map.h>
-#include <hal/hal_flash.h>
-#include <hal/hal_system.h>
-
-#include <os/endian.h>
-#include <os/os.h>
-#include <os/os_malloc.h>
-
-#include <console/console.h>
-
-#include <util/base64.h>
-#include <util/crc16.h>
-
-#include <bootutil/image.h>
-
-#include "boot_serial/boot_serial.h"
-#include "boot_serial_priv.h"
-
-#define BOOT_SERIAL_OUT_MAX	48
-
-static uint32_t curr_off;
-static uint32_t img_size;
-static struct nmgr_hdr *bs_hdr;
-
-static void boot_serial_output(char *data, int len);
-
-/*
- * Looks for 'name' from NULL-terminated json data in buf.
- * Returns pointer to first character of value for that name.
- * Returns NULL if 'name' is not found.
- */
-char *
-bs_find_val(char *buf, char *name)
-{
-    char *ptr;
-
-    ptr = strstr(buf, name);
-    if (!ptr) {
-        return NULL;
-    }
-    ptr += strlen(name);
-
-    while (*ptr != '\0') {
-        if (*ptr != ':' && !isspace(*ptr)) {
-            break;
-        }
-        ++ptr;
-    }
-    if (*ptr == '\0') {
-        ptr = NULL;
-    }
-    return ptr;
-}
-
-/*
- * List images.
- */
-static void
-bs_list(char *buf, int len)
-{
-    char *ptr;
-    struct image_header hdr;
-    uint8_t tmpbuf[64];
-    const struct flash_area *fap = NULL;
-    int good_img, need_comma = 0;
-    int rc;
-    int i;
-
-    ptr = os_malloc(BOOT_SERIAL_OUT_MAX);
-    if (!ptr) {
-        return;
-    }
-    len = snprintf(ptr, BOOT_SERIAL_OUT_MAX, "{\"images\":[");
-    for (i = FLASH_AREA_IMAGE_0; i <= FLASH_AREA_IMAGE_1; i++) {
-        rc = flash_area_open(i, &fap);
-        if (rc) {
-            continue;
-        }
-
-        flash_area_read(fap, 0, &hdr, sizeof(hdr));
-
-        if (hdr.ih_magic == IMAGE_MAGIC &&
-          bootutil_img_validate(&hdr, fap->fa_flash_id, fap->fa_off,
-            tmpbuf, sizeof(tmpbuf), NULL, 0, NULL) == 0) {
-            good_img = 1;
-        } else {
-            good_img = 0;
-        }
-        if (good_img) {
-            len += snprintf(ptr + len, BOOT_SERIAL_OUT_MAX - len,
-              "%c\"%u.%u.%u.%u\"", need_comma ? ',' : ' ',
-              hdr.ih_ver.iv_major, hdr.ih_ver.iv_minor, hdr.ih_ver.iv_revision,
-              (unsigned int)hdr.ih_ver.iv_build_num);
-        }
-        flash_area_close(fap);
-    }
-    len += snprintf(ptr + len, BOOT_SERIAL_OUT_MAX - len, "]}");
-    boot_serial_output(ptr, len);
-    os_free(ptr);
-}
-
-/*
- * Image upload request.
- */
-static void
-bs_upload(char *buf, int len)
-{
-    char *ptr;
-    char *data_ptr;
-    uint32_t off, data_len = 0;
-    const struct flash_area *fap = NULL;
-    int rc;
-
-    /*
-     * should be json inside
-     */
-    ptr = bs_find_val(buf, "\"off\"");
-    if (!ptr) {
-        rc = NMGR_ERR_EINVAL;
-        goto out;
-    }
-    off = strtoul(ptr, NULL, 10);
-
-    if (off == 0) {
-        ptr = bs_find_val(buf, "\"len\"");
-        if (!ptr) {
-            rc = NMGR_ERR_EINVAL;
-            goto out;
-        }
-        data_len = strtoul(ptr, NULL, 10);
-
-    }
-    data_ptr = bs_find_val(buf, "\"data\"");
-    if (!data_ptr) {
-        rc = NMGR_ERR_EINVAL;
-        goto out;
-    }
-    if (*data_ptr != '"') {
-        rc = NMGR_ERR_EINVAL;
-        goto out;
-    }
-    ++data_ptr;
-    data_ptr = strsep(&data_ptr, "\"");
-    if (!data_ptr) {
-        rc = NMGR_ERR_EINVAL;
-        goto out;
-    }
-
-    len = base64_decode(data_ptr, data_ptr);
-    if (len <= 0) {
-        rc = NMGR_ERR_EINVAL;
-        goto out;
-    }
-
-    rc = flash_area_open(FLASH_AREA_IMAGE_0, &fap);
-    if (rc) {
-        rc = NMGR_ERR_EINVAL;
-        goto out;
-    }
-
-    if (off == 0) {
-        curr_off = 0;
-        if (data_len > fap->fa_size) {
-            rc = NMGR_ERR_EINVAL;
-            goto out;
-        }
-        rc = flash_area_erase(fap, 0, fap->fa_size);
-        if (rc) {
-            rc = NMGR_ERR_EINVAL;
-            goto out;
-        }
-        img_size = data_len;
-    }
-    if (off != curr_off) {
-        rc = 0;
-        goto out;
-    }
-    rc = flash_area_write(fap, curr_off, data_ptr, len);
-    if (rc) {
-        rc = NMGR_ERR_EINVAL;
-        goto out;
-    }
-    curr_off += len;
-
-out:
-    ptr = os_malloc(BOOT_SERIAL_OUT_MAX);
-    if (!ptr) {
-        return;
-    }
-    if (rc == 0) {
-        len = snprintf(ptr, BOOT_SERIAL_OUT_MAX, "{\"rc\":%d,\"off\":%u}",
-          rc, (int)curr_off);
-    } else {
-        len = snprintf(ptr, BOOT_SERIAL_OUT_MAX, "{\"rc\":%d}", rc);
-    }
-    boot_serial_output(ptr, len);
-    os_free(ptr);
-    flash_area_close(fap);
-}
-
-/*
- * Console echo control. Send empty response, don't do anything.
- */
-static void
-bs_echo_ctl(char *buf, int len)
-{
-    boot_serial_output(NULL, 0);
-}
-
-/*
- * Reset, and (presumably) boot to newly uploaded image. Flush console
- * before restarting.
- */
-static void
-bs_reset(char *buf, int len)
-{
-    char msg[] = "{\"rc\":0}";
-
-    boot_serial_output(msg, strlen(msg));
-    os_time_delay(250);
-    system_reset();
-}
-
-/*
- * Parse incoming line of input from console.
- * Expect newtmgr protocol with serial transport.
- */
-void
-boot_serial_input(char *buf, int len)
-{
-    int rc;
-    uint16_t crc;
-    uint16_t expected_len;
-    struct nmgr_hdr *hdr;
-
-    if (len < BASE64_ENCODE_SIZE(sizeof(uint16_t) * 2)) {
-        return;
-    }
-    rc = base64_decode(buf, buf);
-    if (rc < 0) {
-        return;
-    }
-    len = rc;
-
-    expected_len = ntohs(*(uint16_t *)buf);
-    buf += sizeof(uint16_t);
-    len -= sizeof(uint16_t);
-
-    len = min(len, expected_len);
-
-    crc = crc16_ccitt(CRC16_INITIAL_CRC, buf, len);
-    if (crc || len <= sizeof(crc)) {
-        return;
-    }
-    len -= sizeof(crc);
-    buf[len] = '\0';
-
-    hdr = (struct nmgr_hdr *)buf;
-    if (len < sizeof(*hdr) ||
-      (hdr->nh_op != NMGR_OP_READ && hdr->nh_op != NMGR_OP_WRITE) ||
-      (ntohs(hdr->nh_len) < len - sizeof(*hdr))) {
-        return;
-    }
-    bs_hdr = hdr;
-    hdr->nh_group = ntohs(hdr->nh_group);
-
-    buf += sizeof(*hdr);
-    len -= sizeof(*hdr);
-
-    /*
-     * Limited support for commands.
-     */
-    if (hdr->nh_group == NMGR_GROUP_ID_IMAGE) {
-        switch (hdr->nh_id) {
-        case IMGMGR_NMGR_OP_LIST:
-            bs_list(buf, len);
-            break;
-        case IMGMGR_NMGR_OP_UPLOAD:
-            bs_upload(buf, len);
-            break;
-        default:
-            break;
-        }
-    } else if (hdr->nh_group == NMGR_GROUP_ID_DEFAULT) {
-        switch (hdr->nh_id) {
-        case NMGR_ID_CONS_ECHO_CTRL:
-            bs_echo_ctl(buf, len);
-            break;
-        case NMGR_ID_RESET:
-            bs_reset(buf, len);
-            break;
-        default:
-            break;
-        }
-    }
-}
-
-static void
-boot_serial_output(char *data, int len)
-{
-    uint16_t crc;
-    uint16_t totlen;
-    char pkt_start[2] = { SHELL_NLIP_PKT_START1, SHELL_NLIP_PKT_START2 };
-    char buf[BOOT_SERIAL_OUT_MAX];
-    char encoded_buf[BASE64_ENCODE_SIZE(BOOT_SERIAL_OUT_MAX)];
-
-    bs_hdr->nh_op++;
-    bs_hdr->nh_len = htons(len);
-    bs_hdr->nh_group = htons(bs_hdr->nh_group);
-
-    crc = crc16_ccitt(CRC16_INITIAL_CRC, bs_hdr, sizeof(*bs_hdr));
-    crc = crc16_ccitt(crc, data, len);
-    crc = htons(crc);
-
-    console_write(pkt_start, sizeof(pkt_start));
-
-    totlen = len + sizeof(*bs_hdr) + sizeof(crc);
-    totlen = htons(totlen);
-
-    memcpy(buf, &totlen, sizeof(totlen));
-    totlen = sizeof(totlen);
-    memcpy(&buf[totlen], bs_hdr, sizeof(*bs_hdr));
-    totlen += sizeof(*bs_hdr);
-    memcpy(&buf[totlen], data, len);
-    totlen += len;
-    memcpy(&buf[totlen], &crc, sizeof(crc));
-    totlen += sizeof(crc);
-    totlen = base64_encode(buf, totlen, encoded_buf, 1);
-    console_write(encoded_buf, totlen);
-    console_write("\n", 1);
-}
-
-/*
- * Task which waits reading console, expecting to get image over
- * serial port.
- */
-static void
-boot_serial(void *arg)
-{
-    int rc;
-    int off;
-    char *buf;
-    int full_line;
-    int max_input = (int)arg;
-
-    rc = console_init(NULL);
-    assert(rc == 0);
-    console_echo(0);
-
-    buf = os_malloc(max_input);
-    assert(buf);
-
-    off = 0;
-    while (1) {
-        rc = console_read(buf + off, max_input - off, &full_line);
-        if (rc <= 0 && !full_line) {
-            continue;
-        }
-        off += rc;
-        if (!full_line) {
-            continue;
-        }
-        if (buf[0] == SHELL_NLIP_PKT_START1 &&
-          buf[1] == SHELL_NLIP_PKT_START2) {
-            boot_serial_input(&buf[2], off - 2);
-        }
-        off = 0;
-    }
-}
-
-int
-boot_serial_task_init(struct os_task *task, uint8_t prio, os_stack_t *stack,
-  uint16_t stack_size, int max_input)
-{
-    return os_task_init(task, "boot", boot_serial, (void *)max_input,
-      prio, OS_WAIT_FOREVER, stack, stack_size);
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/boot_serial/src/boot_serial_priv.h
----------------------------------------------------------------------
diff --git a/libs/boot_serial/src/boot_serial_priv.h b/libs/boot_serial/src/boot_serial_priv.h
deleted file mode 100644
index 86ba6c6..0000000
--- a/libs/boot_serial/src/boot_serial_priv.h
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 __BOOTUTIL_SERIAL_PRIV_H__
-#define __BOOTUTIL_SERIAL_PRIV_H__
-
-/*
- * From shell.h
- */
-#define SHELL_NLIP_PKT_START1   6
-#define SHELL_NLIP_PKT_START2   9
-
-/*
- * From newtmgr.h
- */
-#define NMGR_ERR_EINVAL         3
-
-#define NMGR_OP_READ            0
-#define NMGR_OP_WRITE           2
-
-#define NMGR_GROUP_ID_DEFAULT   0
-#define NMGR_GROUP_ID_IMAGE     1
-
-#define NMGR_ID_CONS_ECHO_CTRL  1
-#define NMGR_ID_RESET           5
-
-struct nmgr_hdr {
-    uint8_t  nh_op;             /* NMGR_OP_XXX */
-    uint8_t  nh_flags;
-    uint16_t nh_len;            /* length of the payload */
-    uint16_t nh_group;          /* NMGR_GROUP_XXX */
-    uint8_t  nh_seq;            /* sequence number */
-    uint8_t  nh_id;             /* message ID within group */
-};
-
-/*
- * From imgmgr.h
- */
-#define IMGMGR_NMGR_OP_LIST             0
-#define IMGMGR_NMGR_OP_UPLOAD           1
-
-
-void boot_serial_input(char *buf, int len);
-
-#endif /*  __BOOTUTIL_SERIAL_PRIV_H__ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/boot_serial/test/pkg.yml
----------------------------------------------------------------------
diff --git a/libs/boot_serial/test/pkg.yml b/libs/boot_serial/test/pkg.yml
deleted file mode 100644
index 561c94b..0000000
--- a/libs/boot_serial/test/pkg.yml
+++ /dev/null
@@ -1,33 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you 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.
-#
-pkg.name: libs/boot_serial/test
-pkg.type: unittest
-pkg.description: "Boot serial unit tests."
-pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
-pkg.homepage: "http://mynewt.apache.org/"
-pkg.keywords:
-
-pkg.deps:
-    - libs/boot_serial
-    - libs/testutil
-
-pkg.deps.SELFTEST:
-    - libs/console/stub
-
-pkg.syscfg_vals.SELFTEST:
-    CONFIG_FCB: 1

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/boot_serial/test/src/boot_test.c
----------------------------------------------------------------------
diff --git a/libs/boot_serial/test/src/boot_test.c b/libs/boot_serial/test/src/boot_test.c
deleted file mode 100644
index 853a391..0000000
--- a/libs/boot_serial/test/src/boot_test.c
+++ /dev/null
@@ -1,231 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include <assert.h>
-#include <stddef.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <inttypes.h>
-#include "syscfg/syscfg.h"
-#include "util/base64.h"
-#include "util/crc16.h"
-#include "testutil/testutil.h"
-#include "hal/hal_flash.h"
-#include "hal/flash_map.h"
-
-#include "boot_serial_priv.h"
-
-void
-tx_msg(void *src, int len)
-{
-    char *msg;
-    char *enc;
-    int off;
-    uint16_t crc;
-
-    crc = htons(crc16_ccitt(CRC16_INITIAL_CRC, src, len));
-
-    /*
-     * Lazy, malloc a buffer, fill it and send it.
-     */
-    msg = malloc(len + 2 * sizeof(uint16_t));
-    assert(msg);
-
-    *(uint16_t *)msg = ntohs(len + sizeof(uint16_t));
-    off = sizeof(uint16_t);
-    memcpy(&msg[off], src, len);
-    off += len;
-    memcpy(&msg[off], &crc, sizeof(crc));
-    off += sizeof(uint16_t);
-
-    enc = malloc(BASE64_ENCODE_SIZE(off) + 1);
-    assert(enc);
-
-    off = base64_encode(msg, off, enc, 1);
-    assert(off > 0);
-
-    boot_serial_input(enc, off + 1);
-
-    free(enc);
-    free(msg);
-}
-
-TEST_CASE(boot_serial_setup)
-{
-
-}
-
-TEST_CASE(boot_serial_empty_msg)
-{
-    char buf[4];
-    struct nmgr_hdr hdr;
-
-    boot_serial_input(buf, 0);
-
-    tx_msg(buf, 0);
-
-    strcpy(buf, "--");
-    tx_msg(buf, 2);
-
-    memset(&hdr, 0, sizeof(hdr));
-    tx_msg(&hdr, sizeof(hdr));
-
-    hdr.nh_op = NMGR_OP_WRITE;
-
-    tx_msg(&hdr, sizeof(hdr));
-}
-
-TEST_CASE(boot_serial_empty_img_msg)
-{
-    char buf[sizeof(struct nmgr_hdr) + 32];
-    struct nmgr_hdr *hdr;
-
-    hdr = (struct nmgr_hdr *)buf;
-    memset(hdr, 0, sizeof(*hdr));
-    hdr->nh_op = NMGR_OP_WRITE;
-    hdr->nh_group = htons(NMGR_GROUP_ID_IMAGE);
-    hdr->nh_id = IMGMGR_NMGR_OP_UPLOAD;
-    hdr->nh_len = htons(2);
-    strcpy((char *)(hdr + 1), "{}");
-
-    tx_msg(buf, sizeof(*hdr) + 2);
-}
-
-TEST_CASE(boot_serial_img_msg)
-{
-    char img[16];
-    char enc_img[BASE64_ENCODE_SIZE(sizeof(img))];
-    char buf[sizeof(struct nmgr_hdr) + sizeof(enc_img) + 32];
-    int len;
-    int rc;
-    struct nmgr_hdr *hdr;
-    const struct flash_area *fap;
-
-    memset(img, 0xa5, sizeof(img));
-    len = base64_encode(img, sizeof(img), enc_img, 1);
-    assert(len > 0);
-
-    hdr = (struct nmgr_hdr *)buf;
-    memset(hdr, 0, sizeof(*hdr));
-    hdr->nh_op = NMGR_OP_WRITE;
-    hdr->nh_group = htons(NMGR_GROUP_ID_IMAGE);
-    hdr->nh_id = IMGMGR_NMGR_OP_UPLOAD;
-
-    len = sprintf((char *)(hdr + 1), "{\"off\":0,\"len\":16,\"data\":\"%s\"}",
-      enc_img);
-    hdr->nh_len = htons(len);
-
-    len = sizeof(*hdr) + len;
-
-    tx_msg(buf, len);
-
-    /*
-     * Validate contents inside image 0 slot
-     */
-    rc = flash_area_open(FLASH_AREA_IMAGE_0, &fap);
-    assert(rc == 0);
-
-    rc = flash_area_read(fap, 0, enc_img, sizeof(img));
-    assert(rc == 0);
-    assert(!memcmp(enc_img, img, sizeof(img)));
-}
-
-TEST_CASE(boot_serial_upload_bigger_image)
-{
-    char img[256];
-    char enc_img[64];
-    char buf[sizeof(struct nmgr_hdr) + 128];
-    int len;
-    int off;
-    int rc;
-    struct nmgr_hdr *hdr;
-    const struct flash_area *fap;
-    int i;
-
-    for (i = 0; i < sizeof(img); i++) {
-        img[i] = i;
-    }
-
-    for (off = 0; off < sizeof(img); off += 32) {
-        len = base64_encode(&img[off], 32, enc_img, 1);
-        assert(len > 0);
-
-        hdr = (struct nmgr_hdr *)buf;
-        memset(hdr, 0, sizeof(*hdr));
-        hdr->nh_op = NMGR_OP_WRITE;
-        hdr->nh_group = htons(NMGR_GROUP_ID_IMAGE);
-        hdr->nh_id = IMGMGR_NMGR_OP_UPLOAD;
-
-        if (off) {
-            len = sprintf((char *)(hdr + 1), "{\"off\":%d,\"data\":\"%s\"}",
-              off, enc_img);
-        } else {
-            len = sprintf((char *)(hdr + 1), "{\"off\": 0 ,\"len\":%ld, "
-              "\"data\":\"%s\"}", (long)sizeof(img), enc_img);
-        }
-        hdr->nh_len = htons(len);
-
-        len = sizeof(*hdr) + len;
-
-        tx_msg(buf, len);
-    }
-
-    /*
-     * Validate contents inside image 0 slot
-     */
-    rc = flash_area_open(FLASH_AREA_IMAGE_0, &fap);
-    assert(rc == 0);
-
-    for (off = 0; off < sizeof(img); off += sizeof(enc_img)) {
-        rc = flash_area_read(fap, off, enc_img, sizeof(enc_img));
-        assert(rc == 0);
-        assert(!memcmp(enc_img, &img[off], sizeof(enc_img)));
-    }
-}
-
-TEST_SUITE(boot_serial_suite)
-{
-    boot_serial_setup();
-    boot_serial_empty_msg();
-    boot_serial_empty_img_msg();
-    boot_serial_img_msg();
-    boot_serial_upload_bigger_image();
-}
-
-int
-boot_serial_test(void)
-{
-    boot_serial_suite();
-    return tu_any_failed;
-}
-
-#if MYNEWT_VAL(SELFTEST)
-int
-main(void)
-{
-    tu_config.tc_print_results = 1;
-    tu_init();
-
-    boot_serial_test();
-
-    return tu_any_failed;
-}
-
-#endif


[13/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/src/os_mbuf.c
----------------------------------------------------------------------
diff --git a/libs/os/src/os_mbuf.c b/libs/os/src/os_mbuf.c
deleted file mode 100644
index c7183f9..0000000
--- a/libs/os/src/os_mbuf.c
+++ /dev/null
@@ -1,1270 +0,0 @@
-/*
- * Software in this file is based heavily on code written in the FreeBSD source
- * code repostiory.  While the code is written from scratch, it contains
- * many of the ideas and logic flow in the original source, this is a
- * derivative work, and the following license applies as well:
- *
- * Copyright (c) 1982, 1986, 1988, 1991, 1993
- *  The Regents of the University of California.  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.
- * 4. Neither the name of the University 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 REGENTS 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 REGENTS 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 "os/os.h"
-
-#include <assert.h>
-#include <string.h>
-#include <limits.h>
-
-STAILQ_HEAD(, os_mbuf_pool) g_msys_pool_list =
-    STAILQ_HEAD_INITIALIZER(g_msys_pool_list);
-
-/**
- * Initialize a mbuf queue.  An mbuf queue is a queue of mbufs that tie
- * to a specific task's event queue.  Mbuf queues are a helper API around
- * a common paradigm, which is to wait on an event queue, until at least
- * 1 packet is available, and then process a queue of packets.
- *
- * When mbufs are available on the queue, an event OS_EVENT_T_MQUEUE_DATA
- * will be posted to the task's mbuf queue.
- *
- * @param mq The mbuf queue to initialize
- * @param arg The argument to provide to the event posted on this mbuf queue
- *
- * @return 0 on success, non-zero on failure.
- *
- */
-int
-os_mqueue_init(struct os_mqueue *mq, void *arg)
-{
-    struct os_event *ev;
-
-    STAILQ_INIT(&mq->mq_head);
-
-    ev = &mq->mq_ev;
-    memset(ev, 0, sizeof(*ev));
-    ev->ev_arg = arg;
-    ev->ev_type = OS_EVENT_T_MQUEUE_DATA;
-
-    return (0);
-}
-
-/**
- * Remove and return a single mbuf from the mbuf queue.  Does not block.
- *
- * @param mq The mbuf queue to pull an element off of.
- *
- * @return The next mbuf in the queue, or NULL if queue has no mbufs.
- */
-struct os_mbuf *
-os_mqueue_get(struct os_mqueue *mq)
-{
-    struct os_mbuf_pkthdr *mp;
-    struct os_mbuf *m;
-    os_sr_t sr;
-
-    OS_ENTER_CRITICAL(sr);
-    mp = STAILQ_FIRST(&mq->mq_head);
-    if (mp) {
-        STAILQ_REMOVE_HEAD(&mq->mq_head, omp_next);
-    }
-    OS_EXIT_CRITICAL(sr);
-
-    if (mp) {
-        m = OS_MBUF_PKTHDR_TO_MBUF(mp);
-    } else {
-        m = NULL;
-    }
-
-    return (m);
-}
-
-/**
- * Put a new mbuf in the mbuf queue.  Appends an mbuf to the end of the
- * mbuf queue, and posts an event to the event queue passed in.
- *
- * @param mq The mbuf queue to append the mbuf to
- * @param evq The event queue to post an OS_EVENT_T_MQUEUE_DATA event to
- * @param m The mbuf to append to the mbuf queue
- *
- * @return 0 on success, non-zero on failure.
- */
-int
-os_mqueue_put(struct os_mqueue *mq, struct os_eventq *evq, struct os_mbuf *m)
-{
-    struct os_mbuf_pkthdr *mp;
-    os_sr_t sr;
-    int rc;
-
-    /* Can only place the head of a chained mbuf on the queue. */
-    if (!OS_MBUF_IS_PKTHDR(m)) {
-        rc = OS_EINVAL;
-        goto err;
-    }
-
-    mp = OS_MBUF_PKTHDR(m);
-
-    OS_ENTER_CRITICAL(sr);
-    STAILQ_INSERT_TAIL(&mq->mq_head, mp, omp_next);
-    OS_EXIT_CRITICAL(sr);
-
-    /* Only post an event to the queue if its specified */
-    if (evq) {
-        os_eventq_put(evq, &mq->mq_ev);
-    }
-
-    return (0);
-err:
-    return (rc);
-}
-
-/**
- * MSYS is a system level mbuf registry.  Allows the system to share
- * packet buffers amongst the various networking stacks that can be running
- * simultaeneously.
- *
- * Mbuf pools are created in the system initialization code, and then when
- * a mbuf is allocated out of msys, it will try and find the best fit based
- * upon estimated mbuf size.
- *
- * os_msys_register() registers a mbuf pool with MSYS, and allows MSYS to
- * allocate mbufs out of it.
- *
- * @param new_pool The pool to register with MSYS
- *
- * @return 0 on success, non-zero on failure
- */
-int
-os_msys_register(struct os_mbuf_pool *new_pool)
-{
-    struct os_mbuf_pool *pool;
-
-    pool = NULL;
-    STAILQ_FOREACH(pool, &g_msys_pool_list, omp_next) {
-        if (new_pool->omp_databuf_len > pool->omp_databuf_len) {
-            break;
-        }
-    }
-
-    if (pool) {
-        STAILQ_INSERT_AFTER(&g_msys_pool_list, pool, new_pool, omp_next);
-    } else {
-        STAILQ_INSERT_TAIL(&g_msys_pool_list, new_pool, omp_next);
-    }
-
-    return (0);
-}
-
-/**
- * De-registers all mbuf pools from msys.
- */
-void
-os_msys_reset(void)
-{
-    STAILQ_INIT(&g_msys_pool_list);
-}
-
-static struct os_mbuf_pool *
-_os_msys_find_pool(uint16_t dsize)
-{
-    struct os_mbuf_pool *pool;
-
-    pool = NULL;
-    STAILQ_FOREACH(pool, &g_msys_pool_list, omp_next) {
-        if (dsize <= pool->omp_databuf_len) {
-            break;
-        }
-    }
-
-    if (!pool) {
-        pool = STAILQ_LAST(&g_msys_pool_list, os_mbuf_pool, omp_next);
-    }
-
-    return (pool);
-}
-
-/**
- * Allocate a mbuf from msys.  Based upon the data size requested,
- * os_msys_get() will choose the mbuf pool that has the best fit.
- *
- * @param dsize The estimated size of the data being stored in the mbuf
- * @param leadingspace The amount of leadingspace to allocate in the mbuf
- *
- * @return A freshly allocated mbuf on success, NULL on failure.
- *
- */
-struct os_mbuf *
-os_msys_get(uint16_t dsize, uint16_t leadingspace)
-{
-    struct os_mbuf *m;
-    struct os_mbuf_pool *pool;
-
-    pool = _os_msys_find_pool(dsize);
-    if (!pool) {
-        goto err;
-    }
-
-    m = os_mbuf_get(pool, leadingspace);
-    return (m);
-err:
-    return (NULL);
-}
-
-/**
- * Allocate a packet header structure from the MSYS pool.  See
- * os_msys_register() for a description of MSYS.
- *
- * @param dsize The estimated size of the data being stored in the mbuf
- * @param user_hdr_len The length to allocate for the packet header structure
- *
- * @return A freshly allocated mbuf on success, NULL on failure.
- */
-struct os_mbuf *
-os_msys_get_pkthdr(uint16_t dsize, uint16_t user_hdr_len)
-{
-    uint16_t total_pkthdr_len;
-    struct os_mbuf *m;
-    struct os_mbuf_pool *pool;
-
-    total_pkthdr_len =  user_hdr_len + sizeof(struct os_mbuf_pkthdr);
-    pool = _os_msys_find_pool(dsize + total_pkthdr_len);
-    if (!pool) {
-        goto err;
-    }
-
-    m = os_mbuf_get_pkthdr(pool, user_hdr_len);
-    return (m);
-err:
-    return (NULL);
-}
-
-int
-os_msys_count(void)
-{
-    struct os_mbuf_pool *omp;
-    int total;
-
-    total = 0;
-    STAILQ_FOREACH(omp, &g_msys_pool_list, omp_next) {
-        total += omp->omp_pool->mp_num_blocks;
-    }
-
-    return total;
-}
-
-int
-os_msys_num_free(void)
-{
-    struct os_mbuf_pool *omp;
-    int total;
-
-    total = 0;
-    STAILQ_FOREACH(omp, &g_msys_pool_list, omp_next) {
-        total += omp->omp_pool->mp_num_free;
-    }
-
-    return total;
-}
-
-/**
- * Initialize a pool of mbufs.
- *
- * @param omp     The mbuf pool to initialize
- * @param mp      The memory pool that will hold this mbuf pool
- * @param buf_len The length of the buffer itself.
- * @param nbufs   The number of buffers in the pool
- *
- * @return 0 on success, error code on failure.
- */
-int
-os_mbuf_pool_init(struct os_mbuf_pool *omp, struct os_mempool *mp,
-                  uint16_t buf_len, uint16_t nbufs)
-{
-    omp->omp_databuf_len = buf_len - sizeof(struct os_mbuf);
-    omp->omp_mbuf_count = nbufs;
-    omp->omp_pool = mp;
-
-    return (0);
-}
-
-/**
- * Get an mbuf from the mbuf pool.  The mbuf is allocated, and initialized
- * prior to being returned.
- *
- * @param omp The mbuf pool to return the packet from
- * @param leadingspace The amount of leadingspace to put before the data
- *     section by default.
- *
- * @return An initialized mbuf on success, and NULL on failure.
- */
-struct os_mbuf *
-os_mbuf_get(struct os_mbuf_pool *omp, uint16_t leadingspace)
-{
-    struct os_mbuf *om;
-
-    if (leadingspace > omp->omp_databuf_len) {
-        goto err;
-    }
-
-    om = os_memblock_get(omp->omp_pool);
-    if (!om) {
-        goto err;
-    }
-
-    SLIST_NEXT(om, om_next) = NULL;
-    om->om_flags = 0;
-    om->om_pkthdr_len = 0;
-    om->om_len = 0;
-    om->om_data = (&om->om_databuf[0] + leadingspace);
-    om->om_omp = omp;
-
-    return (om);
-err:
-    return (NULL);
-}
-
-/**
- * Allocate a new packet header mbuf out of the os_mbuf_pool.
- *
- * @param omp The mbuf pool to allocate out of
- * @param user_pkthdr_len The packet header length to reserve for the caller.
- *
- * @return A freshly allocated mbuf on success, NULL on failure.
- */
-struct os_mbuf *
-os_mbuf_get_pkthdr(struct os_mbuf_pool *omp, uint8_t user_pkthdr_len)
-{
-    uint16_t pkthdr_len;
-    struct os_mbuf_pkthdr *pkthdr;
-    struct os_mbuf *om;
-
-    /* User packet header must fit inside mbuf */
-    pkthdr_len = user_pkthdr_len + sizeof(struct os_mbuf_pkthdr);
-    if ((pkthdr_len > omp->omp_databuf_len) || (pkthdr_len > 255)) {
-        return NULL;
-    }
-
-    om = os_mbuf_get(omp, 0);
-    if (om) {
-        om->om_pkthdr_len = pkthdr_len;
-        om->om_data += pkthdr_len;
-
-        pkthdr = OS_MBUF_PKTHDR(om);
-        pkthdr->omp_len = 0;
-        pkthdr->omp_flags = 0;
-        STAILQ_NEXT(pkthdr, omp_next) = NULL;
-    }
-
-    return om;
-}
-
-/**
- * Release a mbuf back to the pool
- *
- * @param omp The Mbuf pool to release back to
- * @param om  The Mbuf to release back to the pool
- *
- * @return 0 on success, -1 on failure
- */
-int
-os_mbuf_free(struct os_mbuf *om)
-{
-    int rc;
-
-    if (om->om_omp != NULL) {
-        rc = os_memblock_put(om->om_omp->omp_pool, om);
-        if (rc != 0) {
-            goto err;
-        }
-    }
-
-    return (0);
-err:
-    return (rc);
-}
-
-/**
- * Free a chain of mbufs
- *
- * @param omp The mbuf pool to free the chain of mbufs into
- * @param om  The starting mbuf of the chain to free back into the pool
- *
- * @return 0 on success, -1 on failure
- */
-int
-os_mbuf_free_chain(struct os_mbuf *om)
-{
-    struct os_mbuf *next;
-    int rc;
-
-    while (om != NULL) {
-        next = SLIST_NEXT(om, om_next);
-
-        rc = os_mbuf_free(om);
-        if (rc != 0) {
-            goto err;
-        }
-
-        om = next;
-    }
-
-    return (0);
-err:
-    return (rc);
-}
-
-/**
- * Copy a packet header from one mbuf to another.
- *
- * @param omp The mbuf pool associated with these buffers
- * @param new_buf The new buffer to copy the packet header into
- * @param old_buf The old buffer to copy the packet header from
- */
-static inline void
-_os_mbuf_copypkthdr(struct os_mbuf *new_buf, struct os_mbuf *old_buf)
-{
-    assert(new_buf->om_len == 0);
-
-    memcpy(&new_buf->om_databuf[0], &old_buf->om_databuf[0],
-           old_buf->om_pkthdr_len);
-    new_buf->om_pkthdr_len = old_buf->om_pkthdr_len;
-    new_buf->om_data = new_buf->om_databuf + old_buf->om_pkthdr_len;
-}
-
-/**
- * Append data onto a mbuf
- *
- * @param om   The mbuf to append the data onto
- * @param data The data to append onto the mbuf
- * @param len  The length of the data to append
- *
- * @return 0 on success, and an error code on failure
- */
-int
-os_mbuf_append(struct os_mbuf *om, const void *data,  uint16_t len)
-{
-    struct os_mbuf_pool *omp;
-    struct os_mbuf *last;
-    struct os_mbuf *new;
-    int remainder;
-    int space;
-    int rc;
-
-    if (om == NULL) {
-        rc = OS_EINVAL;
-        goto err;
-    }
-
-    omp = om->om_omp;
-
-    /* Scroll to last mbuf in the chain */
-    last = om;
-    while (SLIST_NEXT(last, om_next) != NULL) {
-        last = SLIST_NEXT(last, om_next);
-    }
-
-    remainder = len;
-    space = OS_MBUF_TRAILINGSPACE(last);
-
-    /* If room in current mbuf, copy the first part of the data into the
-     * remaining space in that mbuf.
-     */
-    if (space > 0) {
-        if (space > remainder) {
-            space = remainder;
-        }
-
-        memcpy(OS_MBUF_DATA(last, uint8_t *) + last->om_len , data, space);
-
-        last->om_len += space;
-        data += space;
-        remainder -= space;
-    }
-
-    /* Take the remaining data, and keep allocating new mbufs and copying
-     * data into it, until data is exhausted.
-     */
-    while (remainder > 0) {
-        new = os_mbuf_get(omp, 0);
-        if (!new) {
-            break;
-        }
-
-        new->om_len = min(omp->omp_databuf_len, remainder);
-        memcpy(OS_MBUF_DATA(new, void *), data, new->om_len);
-        data += new->om_len;
-        remainder -= new->om_len;
-        SLIST_NEXT(last, om_next) = new;
-        last = new;
-    }
-
-    /* Adjust the packet header length in the buffer */
-    if (OS_MBUF_IS_PKTHDR(om)) {
-        OS_MBUF_PKTHDR(om)->omp_len += len - remainder;
-    }
-
-    if (remainder != 0) {
-        rc = OS_ENOMEM;
-        goto err;
-    }
-
-
-    return (0);
-err:
-    return (rc);
-}
-
-/**
- * Reads data from one mbuf and appends it to another.  On error, the specified
- * data range may be partially appended.  Neither mbuf is required to contain
- * an mbuf packet header.
- *
- * @param dst                   The mbuf to append to.
- * @param src                   The mbuf to copy data from.
- * @param src_off               The absolute offset within the source mbuf
- *                                  chain to read from.
- * @param len                   The number of bytes to append.
- *
- * @return                      0 on success;
- *                              OS_EINVAL if the specified range extends beyond
- *                                  the end of the source mbuf chain.
- */
-int
-os_mbuf_appendfrom(struct os_mbuf *dst, const struct os_mbuf *src,
-                   uint16_t src_off, uint16_t len)
-{
-    const struct os_mbuf *src_cur_om;
-    uint16_t src_cur_off;
-    uint16_t chunk_sz;
-    int rc;
-
-    src_cur_om = os_mbuf_off(src, src_off, &src_cur_off);
-    while (len > 0) {
-        if (src_cur_om == NULL) {
-            return OS_EINVAL;
-        }
-
-        chunk_sz = min(len, src_cur_om->om_len - src_cur_off);
-        rc = os_mbuf_append(dst, src_cur_om->om_data + src_cur_off, chunk_sz);
-        if (rc != 0) {
-            return rc;
-        }
-
-        len -= chunk_sz;
-        src_cur_om = SLIST_NEXT(src_cur_om, om_next);
-        src_cur_off = 0;
-    }
-
-    return 0;
-}
-
-/**
- * Duplicate a chain of mbufs.  Return the start of the duplicated chain.
- *
- * @param omp The mbuf pool to duplicate out of
- * @param om  The mbuf chain to duplicate
- *
- * @return A pointer to the new chain of mbufs
- */
-struct os_mbuf *
-os_mbuf_dup(struct os_mbuf *om)
-{
-    struct os_mbuf_pool *omp;
-    struct os_mbuf *head;
-    struct os_mbuf *copy;
-
-    omp = om->om_omp;
-
-    head = NULL;
-    copy = NULL;
-
-    for (; om != NULL; om = SLIST_NEXT(om, om_next)) {
-        if (head) {
-            SLIST_NEXT(copy, om_next) = os_mbuf_get(omp,
-                    OS_MBUF_LEADINGSPACE(om));
-            if (!SLIST_NEXT(copy, om_next)) {
-                os_mbuf_free_chain(head);
-                goto err;
-            }
-
-            copy = SLIST_NEXT(copy, om_next);
-        } else {
-            head = os_mbuf_get(omp, OS_MBUF_LEADINGSPACE(om));
-            if (!head) {
-                goto err;
-            }
-
-            if (OS_MBUF_IS_PKTHDR(om)) {
-                _os_mbuf_copypkthdr(head, om);
-            }
-            copy = head;
-        }
-        copy->om_flags = om->om_flags;
-        copy->om_len = om->om_len;
-        memcpy(OS_MBUF_DATA(copy, uint8_t *), OS_MBUF_DATA(om, uint8_t *),
-                om->om_len);
-    }
-
-    return (head);
-err:
-    return (NULL);
-}
-
-/**
- * Locates the specified absolute offset within an mbuf chain.  The offset
- * can be one past than the total length of the chain, but no greater.
- *
- * @param om                    The start of the mbuf chain to seek within.
- * @param off                   The absolute address to find.
- * @param out_off               On success, this points to the relative offset
- *                                  within the returned mbuf.
- *
- * @return                      The mbuf containing the specified offset on
- *                                  success.
- *                              NULL if the specified offset is out of bounds.
- */
-struct os_mbuf *
-os_mbuf_off(const struct os_mbuf *om, int off, uint16_t *out_off)
-{
-    struct os_mbuf *next;
-    struct os_mbuf *cur;
-
-    /* Cast away const. */
-    cur = (struct os_mbuf *)om;
-
-    while (1) {
-        if (cur == NULL) {
-            return NULL;
-        }
-
-        next = SLIST_NEXT(cur, om_next);
-
-        if (cur->om_len > off ||
-            (cur->om_len == off && next == NULL)) {
-
-            *out_off = off;
-            return cur;
-        }
-
-        off -= cur->om_len;
-        cur = next;
-    }
-}
-
-/*
- * Copy data from an mbuf chain starting "off" bytes from the beginning,
- * continuing for "len" bytes, into the indicated buffer.
- *
- * @param m The mbuf chain to copy from
- * @param off The offset into the mbuf chain to begin copying from
- * @param len The length of the data to copy
- * @param dst The destination buffer to copy into
- *
- * @return                      0 on success;
- *                              -1 if the mbuf does not contain enough data.
- */
-int
-os_mbuf_copydata(const struct os_mbuf *m, int off, int len, void *dst)
-{
-    unsigned int count;
-    uint8_t *udst;
-
-    if (!len) {
-        return 0;
-    }
-
-    udst = dst;
-
-    while (off > 0) {
-        if (!m) {
-            return (-1);
-        }
-
-        if (off < m->om_len)
-            break;
-        off -= m->om_len;
-        m = SLIST_NEXT(m, om_next);
-    }
-    while (len > 0 && m != NULL) {
-        count = min(m->om_len - off, len);
-        memcpy(udst, m->om_data + off, count);
-        len -= count;
-        udst += count;
-        off = 0;
-        m = SLIST_NEXT(m, om_next);
-    }
-
-    return (len > 0 ? -1 : 0);
-}
-
-/**
- * Adjust the length of a mbuf, trimming either from the head or the tail
- * of the mbuf.
- *
- * @param mp The mbuf chain to adjust
- * @param req_len The length to trim from the mbuf.  If positive, trims
- *                from the head of the mbuf, if negative, trims from the
- *                tail of the mbuf.
- */
-void
-os_mbuf_adj(struct os_mbuf *mp, int req_len)
-{
-    int len = req_len;
-    struct os_mbuf *m;
-    int count;
-
-    if ((m = mp) == NULL)
-        return;
-    if (len >= 0) {
-        /*
-         * Trim from head.
-         */
-        while (m != NULL && len > 0) {
-            if (m->om_len <= len) {
-                len -= m->om_len;
-                m->om_len = 0;
-                m = SLIST_NEXT(m, om_next);
-            } else {
-                m->om_len -= len;
-                m->om_data += len;
-                len = 0;
-            }
-        }
-        if (OS_MBUF_IS_PKTHDR(mp))
-            OS_MBUF_PKTHDR(mp)->omp_len -= (req_len - len);
-    } else {
-        /*
-         * Trim from tail.  Scan the mbuf chain,
-         * calculating its length and finding the last mbuf.
-         * If the adjustment only affects this mbuf, then just
-         * adjust and return.  Otherwise, rescan and truncate
-         * after the remaining size.
-         */
-        len = -len;
-        count = 0;
-        for (;;) {
-            count += m->om_len;
-            if (SLIST_NEXT(m, om_next) == (struct os_mbuf *)0)
-                break;
-            m = SLIST_NEXT(m, om_next);
-        }
-        if (m->om_len >= len) {
-            m->om_len -= len;
-            if (OS_MBUF_IS_PKTHDR(mp))
-                OS_MBUF_PKTHDR(mp)->omp_len -= len;
-            return;
-        }
-        count -= len;
-        if (count < 0)
-            count = 0;
-        /*
-         * Correct length for chain is "count".
-         * Find the mbuf with last data, adjust its length,
-         * and toss data from remaining mbufs on chain.
-         */
-        m = mp;
-        if (OS_MBUF_IS_PKTHDR(m))
-            OS_MBUF_PKTHDR(m)->omp_len = count;
-        for (; m; m = SLIST_NEXT(m, om_next)) {
-            if (m->om_len >= count) {
-                m->om_len = count;
-                if (SLIST_NEXT(m, om_next) != NULL) {
-                    os_mbuf_free_chain(SLIST_NEXT(m, om_next));
-                    SLIST_NEXT(m, om_next) = NULL;
-                }
-                break;
-            }
-            count -= m->om_len;
-        }
-    }
-}
-
-/**
- * Performs a memory compare of the specified region of an mbuf chain against a
- * flat buffer.
- *
- * @param om                    The start of the mbuf chain to compare.
- * @param off                   The offset within the mbuf chain to start the
- *                                  comparison.
- * @param data                  The flat buffer to compare.
- * @param len                   The length of the flat buffer.
- *
- * @return                      0 if both memory regions are identical;
- *                              A memcmp return code if there is a mismatch;
- *                              INT_MAX if the mbuf is too short.
- */
-int
-os_mbuf_cmpf(const struct os_mbuf *om, int off, const void *data, int len)
-{
-    uint16_t chunk_sz;
-    uint16_t data_off;
-    uint16_t om_off;
-    int rc;
-
-    if (len <= 0) {
-        return 0;
-    }
-
-    data_off = 0;
-    om = os_mbuf_off(om, off, &om_off);
-    while (1) {
-        if (om == NULL) {
-            return INT_MAX;
-        }
-
-        chunk_sz = min(om->om_len - om_off, len - data_off);
-        if (chunk_sz > 0) {
-            rc = memcmp(om->om_data + om_off, data + data_off, chunk_sz);
-            if (rc != 0) {
-                return rc;
-            }
-        }
-
-        data_off += chunk_sz;
-        if (data_off == len) {
-            return 0;
-        }
-
-        om = SLIST_NEXT(om, om_next);
-        om_off = 0;
-
-        if (om == NULL) {
-            return INT_MAX;
-        }
-    }
-}
-
-/**
- * Compares the contents of two mbuf chains.  The ranges of the two chains to
- * be compared are specified via the two offset parameters and the len
- * parameter.  Neither mbuf chain is required to contain a packet header.
- *
- * @param om1                   The first mbuf chain to compare.
- * @param offset1               The absolute offset within om1 at which to
- *                                  start the comparison.
- * @param om2                   The second mbuf chain to compare.
- * @param offset2               The absolute offset within om2 at which to
- *                                  start the comparison.
- * @param len                   The number of bytes to compare.
- *
- * @return                      0 if both mbuf segments are identical;
- *                              A memcmp() return code if the segment contents
- *                                  differ;
- *                              INT_MAX if a specified range extends beyond the
- *                                  end of its corresponding mbuf chain.
- */
-int
-os_mbuf_cmpm(const struct os_mbuf *om1, uint16_t offset1,
-             const struct os_mbuf *om2, uint16_t offset2,
-             uint16_t len)
-{
-    const struct os_mbuf *cur1;
-    const struct os_mbuf *cur2;
-    uint16_t bytes_remaining;
-    uint16_t chunk_sz;
-    uint16_t om1_left;
-    uint16_t om2_left;
-    uint16_t om1_off;
-    uint16_t om2_off;
-    int rc;
-
-    cur1 = os_mbuf_off(om1, offset1, &om1_off);
-    cur2 = os_mbuf_off(om2, offset2, &om2_off);
-
-    bytes_remaining = len;
-    while (1) {
-        if (bytes_remaining == 0) {
-            return 0;
-        }
-
-        while (cur1 != NULL && om1_off >= cur1->om_len) {
-            cur1 = SLIST_NEXT(cur1, om_next);
-            om1_off = 0;
-        }
-        while (cur2 != NULL && om2_off >= cur2->om_len) {
-            cur2 = SLIST_NEXT(cur2, om_next);
-            om2_off = 0;
-        }
-
-        if (cur1 == NULL || cur2 == NULL) {
-            return INT_MAX;
-        }
-
-        om1_left = cur1->om_len - om1_off;
-        om2_left = cur2->om_len - om2_off;
-        chunk_sz = min(min(om1_left, om2_left), bytes_remaining);
-
-        rc = memcmp(cur1->om_data + om1_off, cur2->om_data + om2_off,
-                    chunk_sz);
-        if (rc != 0) {
-            return rc;
-        }
-
-        om1_off += chunk_sz;
-        om2_off += chunk_sz;
-        bytes_remaining -= chunk_sz;
-    }
-}
-
-/**
- * Increases the length of an mbuf chain by adding data to the front.  If there
- * is insufficient room in the leading mbuf, additional mbufs are allocated and
- * prepended as necessary.  If this function fails to allocate an mbuf, the
- * entire chain is freed.
- *
- * The specified mbuf chain does not need to contain a packet header.
- *
- * @param omp                   The mbuf pool to allocate from.
- * @param om                    The head of the mbuf chain.
- * @param len                   The number of bytes to prepend.
- *
- * @return                      The new head of the chain on success;
- *                              NULL on failure.
- */
-struct os_mbuf *
-os_mbuf_prepend(struct os_mbuf *om, int len)
-{
-    struct os_mbuf *p;
-    int leading;
-
-    while (1) {
-        /* Fill the available space at the front of the head of the chain, as
-         * needed.
-         */
-        leading = min(len, OS_MBUF_LEADINGSPACE(om));
-
-        om->om_data -= leading;
-        om->om_len += leading;
-        if (OS_MBUF_IS_PKTHDR(om)) {
-            OS_MBUF_PKTHDR(om)->omp_len += leading;
-        }
-
-        len -= leading;
-        if (len == 0) {
-            break;
-        }
-
-        /* The current head didn't have enough space; allocate a new head. */
-        if (OS_MBUF_IS_PKTHDR(om)) {
-            p = os_mbuf_get_pkthdr(om->om_omp,
-                om->om_pkthdr_len - sizeof (struct os_mbuf_pkthdr));
-        } else {
-            p = os_mbuf_get(om->om_omp, 0);
-        }
-        if (p == NULL) {
-            os_mbuf_free_chain(om);
-            om = NULL;
-            break;
-        }
-
-        if (OS_MBUF_IS_PKTHDR(om)) {
-            _os_mbuf_copypkthdr(p, om);
-            om->om_pkthdr_len = 0;
-        }
-
-        /* Move the new head's data pointer to the end so that data can be
-         * prepended.
-         */
-        p->om_data += OS_MBUF_TRAILINGSPACE(p);
-
-        SLIST_NEXT(p, om_next) = om;
-        om = p;
-    }
-
-    return om;
-}
-
-/**
- * Prepends a chunk of empty data to the specified mbuf chain and ensures the
- * chunk is contiguous.  If either operation fails, the specified mbuf chain is
- * freed and NULL is returned.
- *
- * @param om                    The mbuf chain to prepend to.
- * @param len                   The number of bytes to prepend and pullup.
- *
- * @return                      The modified mbuf on success;
- *                              NULL on failure (and the mbuf chain is freed).
- */
-struct os_mbuf *
-os_mbuf_prepend_pullup(struct os_mbuf *om, uint16_t len)
-{
-    om = os_mbuf_prepend(om, len);
-    if (om == NULL) {
-        return NULL;
-    }
-
-    om = os_mbuf_pullup(om, len);
-    if (om == NULL) {
-        return NULL;
-    }
-
-    return om;
-}
-
-/**
- * Copies the contents of a flat buffer into an mbuf chain, starting at the
- * specified destination offset.  If the mbuf is too small for the source data,
- * it is extended as necessary.  If the destination mbuf contains a packet
- * header, the header length is updated.
- *
- * @param omp                   The mbuf pool to allocate from.
- * @param om                    The mbuf chain to copy into.
- * @param off                   The offset within the chain to copy to.
- * @param src                   The source buffer to copy from.
- * @param len                   The number of bytes to copy.
- *
- * @return                      0 on success; nonzero on failure.
- */
-int
-os_mbuf_copyinto(struct os_mbuf *om, int off, const void *src, int len)
-{
-    struct os_mbuf *next;
-    struct os_mbuf *cur;
-    const uint8_t *sptr;
-    uint16_t cur_off;
-    int copylen;
-    int rc;
-
-    /* Find the mbuf,offset pair for the start of the destination. */
-    cur = os_mbuf_off(om, off, &cur_off);
-    if (cur == NULL) {
-        return -1;
-    }
-
-    /* Overwrite existing data until we reach the end of the chain. */
-    sptr = src;
-    while (1) {
-        copylen = min(cur->om_len - cur_off, len);
-        if (copylen > 0) {
-            memcpy(cur->om_data + cur_off, sptr, copylen);
-            sptr += copylen;
-            len -= copylen;
-
-            copylen = 0;
-        }
-
-        if (len == 0) {
-            /* All the source data fit in the existing mbuf chain. */
-            return 0;
-        }
-
-        next = SLIST_NEXT(cur, om_next);
-        if (next == NULL) {
-            break;
-        }
-
-        cur = next;
-    }
-
-    /* Append the remaining data to the end of the chain. */
-    rc = os_mbuf_append(cur, sptr, len);
-    if (rc != 0) {
-        return rc;
-    }
-
-    /* Fix up the packet header, if one is present. */
-    if (OS_MBUF_IS_PKTHDR(om)) {
-        OS_MBUF_PKTHDR(om)->omp_len =
-            max(OS_MBUF_PKTHDR(om)->omp_len, off + len);
-    }
-
-    return 0;
-}
-
-/**
- * Attaches a second mbuf chain onto the end of the first.  If the first chain
- * contains a packet header, the header's length is updated.  If the second
- * chain has a packet header, its header is cleared.
- *
- * @param first                 The mbuf chain being attached to.
- * @param second                The mbuf chain that gets attached.
- */
-void
-os_mbuf_concat(struct os_mbuf *first, struct os_mbuf *second)
-{
-    struct os_mbuf *next;
-    struct os_mbuf *cur;
-
-    /* Point 'cur' to the last buffer in the first chain. */
-    cur = first;
-    while (1) {
-        next = SLIST_NEXT(cur, om_next);
-        if (next == NULL) {
-            break;
-        }
-
-        cur = next;
-    }
-
-    /* Attach the second chain to the end of the first. */
-    SLIST_NEXT(cur, om_next) = second;
-
-    /* If the first chain has a packet header, calculate the length of the
-     * second chain and add it to the header length.
-     */
-    if (OS_MBUF_IS_PKTHDR(first)) {
-        if (OS_MBUF_IS_PKTHDR(second)) {
-            OS_MBUF_PKTHDR(first)->omp_len += OS_MBUF_PKTHDR(second)->omp_len;
-        } else {
-            for (cur = second; cur != NULL; cur = SLIST_NEXT(cur, om_next)) {
-                OS_MBUF_PKTHDR(first)->omp_len += cur->om_len;
-            }
-        }
-    }
-
-    second->om_pkthdr_len = 0;
-}
-
-/**
- * Increases the length of an mbuf chain by the specified amount.  If there is
- * not sufficient room in the last buffer, a new buffer is allocated and
- * appended to the chain.  It is an error to request more data than can fit in
- * a single buffer.
- *
- * @param omp
- * @param om                    The head of the chain to extend.
- * @param len                   The number of bytes to extend by.
- *
- * @return                      A pointer to the new data on success;
- *                              NULL on failure.
- */
-void *
-os_mbuf_extend(struct os_mbuf *om, uint16_t len)
-{
-    struct os_mbuf *newm;
-    struct os_mbuf *last;
-    void *data;
-
-    if (len > om->om_omp->omp_databuf_len) {
-        return NULL;
-    }
-
-    /* Scroll to last mbuf in the chain */
-    last = om;
-    while (SLIST_NEXT(last, om_next) != NULL) {
-        last = SLIST_NEXT(last, om_next);
-    }
-
-    if (OS_MBUF_TRAILINGSPACE(last) < len) {
-        newm = os_mbuf_get(om->om_omp, 0);
-        if (newm == NULL) {
-            return NULL;
-        }
-
-        SLIST_NEXT(last, om_next) = newm;
-        last = newm;
-    }
-
-    data = last->om_data + last->om_len;
-    last->om_len += len;
-
-    if (OS_MBUF_IS_PKTHDR(om)) {
-        OS_MBUF_PKTHDR(om)->omp_len += len;
-    }
-
-    return data;
-}
-
-/**
- * Rearrange a mbuf chain so that len bytes are contiguous,
- * and in the data area of an mbuf (so that OS_MBUF_DATA() will
- * work on a structure of size len.)  Returns the resulting
- * mbuf chain on success, free's it and returns NULL on failure.
- *
- * If there is room, it will add up to "max_protohdr - len"
- * extra bytes to the contiguous region, in an attempt to avoid being
- * called next time.
- *
- * @param omp The mbuf pool to take the mbufs out of
- * @param om The mbuf chain to make contiguous
- * @param len The number of bytes in the chain to make contiguous
- *
- * @return The contiguous mbuf chain on success, NULL on failure.
- */
-struct os_mbuf *
-os_mbuf_pullup(struct os_mbuf *om, uint16_t len)
-{
-    struct os_mbuf_pool *omp;
-    struct os_mbuf *next;
-    struct os_mbuf *om2;
-    int count;
-    int space;
-
-    omp = om->om_omp;
-
-    /*
-     * If first mbuf has no cluster, and has room for len bytes
-     * without shifting current data, pullup into it,
-     * otherwise allocate a new mbuf to prepend to the chain.
-     */
-    if (om->om_len >= len) {
-        return (om);
-    }
-    if (om->om_len + OS_MBUF_TRAILINGSPACE(om) >= len &&
-        SLIST_NEXT(om, om_next)) {
-        om2 = om;
-        om = SLIST_NEXT(om, om_next);
-        len -= om2->om_len;
-    } else {
-        if (len > omp->omp_databuf_len - om->om_pkthdr_len) {
-            goto bad;
-        }
-
-        om2 = os_mbuf_get(omp, 0);
-        if (om2 == NULL) {
-            goto bad;
-        }
-
-        if (OS_MBUF_IS_PKTHDR(om)) {
-            _os_mbuf_copypkthdr(om2, om);
-        }
-    }
-    space = OS_MBUF_TRAILINGSPACE(om2);
-    do {
-        count = min(min(len, space), om->om_len);
-        memcpy(om2->om_data + om2->om_len, om->om_data, count);
-        len -= count;
-        om2->om_len += count;
-        om->om_len -= count;
-        space -= count;
-        if (om->om_len) {
-            om->om_data += count;
-        } else {
-            next = SLIST_NEXT(om, om_next);
-            os_mbuf_free(om);
-            om = next;
-        }
-    } while (len > 0 && om);
-    if (len > 0) {
-        os_mbuf_free(om2);
-        goto bad;
-    }
-    SLIST_NEXT(om2, om_next) = om;
-    return (om2);
-bad:
-    os_mbuf_free_chain(om);
-    return (NULL);
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/src/os_mempool.c
----------------------------------------------------------------------
diff --git a/libs/os/src/os_mempool.c b/libs/os/src/os_mempool.c
deleted file mode 100644
index e940ba4..0000000
--- a/libs/os/src/os_mempool.c
+++ /dev/null
@@ -1,233 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include "os/os.h"
-
-#include <string.h>
-#include <assert.h>
-
-#define OS_MEMPOOL_TRUE_BLOCK_SIZE(bsize)   OS_ALIGN(bsize, OS_ALIGNMENT)
-
-STAILQ_HEAD(, os_mempool) g_os_mempool_list = 
-    STAILQ_HEAD_INITIALIZER(g_os_mempool_list);
-
-/**
- * os mempool init
- *  
- * Initialize a memory pool. 
- * 
- * @param mp            Pointer to a pointer to a mempool
- * @param blocks        The number of blocks in the pool
- * @param blocks_size   The size of the block, in bytes. 
- * @param membuf        Pointer to memory to contain blocks. 
- * @param name          Name of the pool.
- * 
- * @return os_error_t 
- */
-os_error_t
-os_mempool_init(struct os_mempool *mp, int blocks, int block_size,
-                void *membuf, char *name)
-{
-    int true_block_size;
-    uint8_t *block_addr;
-    struct os_memblock *block_ptr;
-
-    /* Check for valid parameters */
-    if ((!mp) || (blocks < 0) || (block_size <= 0)) {
-        return OS_INVALID_PARM;
-    }
-
-    if ((!membuf) && (blocks != 0)) {
-        return OS_INVALID_PARM;
-    }
-
-    if (membuf != NULL) {
-        /* Blocks need to be sized properly and memory buffer should be
-         * aligned
-         */
-        if (((uint32_t)membuf & (OS_ALIGNMENT - 1)) != 0) {
-            return OS_MEM_NOT_ALIGNED;
-        }
-    }
-    true_block_size = OS_MEMPOOL_TRUE_BLOCK_SIZE(block_size);
-
-    /* Initialize the memory pool structure */
-    mp->mp_block_size = block_size;
-    mp->mp_num_free = blocks;
-    mp->mp_num_blocks = blocks;
-    mp->mp_membuf_addr = (uint32_t)membuf;
-    mp->name = name;
-    SLIST_FIRST(mp) = membuf;
-
-    /* Chain the memory blocks to the free list */
-    block_addr = (uint8_t *)membuf;
-    block_ptr = (struct os_memblock *)block_addr;
-    while (blocks > 1) {
-        block_addr += true_block_size;
-        SLIST_NEXT(block_ptr, mb_next) = (struct os_memblock *)block_addr;
-        block_ptr = (struct os_memblock *)block_addr;
-        --blocks;
-    }
-
-    /* Last one in the list should be NULL */
-    SLIST_NEXT(block_ptr, mb_next) = NULL;
-
-    STAILQ_INSERT_TAIL(&g_os_mempool_list, mp, mp_list);
-
-    return OS_OK;
-}
-
-/**
- * Checks if a memory block was allocated from the specified mempool.
- *
- * @param mp                    The mempool to check as parent.
- * @param block_addr            The memory block to check as child.
- *
- * @return                      0 if the block does not belong to the mempool;
- *                              1 if the block does belong to the mempool.
- */
-int
-os_memblock_from(struct os_mempool *mp, void *block_addr)
-{
-    uint32_t true_block_size;
-    uint32_t baddr32;
-    uint32_t end;
-
-    _Static_assert(sizeof block_addr == sizeof baddr32,
-                   "Pointer to void must be 32-bits.");
-
-    baddr32 = (uint32_t)block_addr;
-    true_block_size = OS_MEMPOOL_TRUE_BLOCK_SIZE(mp->mp_block_size);
-    end = mp->mp_membuf_addr + (mp->mp_num_blocks * true_block_size);
-
-    /* Check that the block is in the memory buffer range. */
-    if ((baddr32 < mp->mp_membuf_addr) || (baddr32 >= end)) {
-        return 0;
-    }
-
-    /* All freed blocks should be on true block size boundaries! */
-    if (((baddr32 - mp->mp_membuf_addr) % true_block_size) != 0) {
-        return 0;
-    }
-
-    return 1;
-}
-
-/**
- * os memblock get 
- *  
- * Get a memory block from a memory pool 
- * 
- * @param mp Pointer to the memory pool
- * 
- * @return void* Pointer to block if available; NULL otherwise
- */
-void *
-os_memblock_get(struct os_mempool *mp)
-{
-    os_sr_t sr;
-    struct os_memblock *block;
-
-    /* Check to make sure they passed in a memory pool (or something) */
-    block = NULL;
-    if (mp) {
-        OS_ENTER_CRITICAL(sr);
-        /* Check for any free */
-        if (mp->mp_num_free) {
-            /* Get a free block */
-            block = SLIST_FIRST(mp);
-
-            /* Set new free list head */
-            SLIST_FIRST(mp) = SLIST_NEXT(block, mb_next);
-
-            /* Decrement number free by 1 */
-            mp->mp_num_free--;
-        }
-        OS_EXIT_CRITICAL(sr);
-    }
-
-    return (void *)block;
-}
-
-/**
- * os memblock put 
- *  
- * Puts the memory block back into the pool 
- * 
- * @param mp Pointer to memory pool
- * @param block_addr Pointer to memory block
- * 
- * @return os_error_t 
- */
-os_error_t
-os_memblock_put(struct os_mempool *mp, void *block_addr)
-{
-    os_sr_t sr;
-    struct os_memblock *block;
-
-    /* Make sure parameters are valid */
-    if ((mp == NULL) || (block_addr == NULL)) {
-        return OS_INVALID_PARM;
-    }
-
-    /* Check that the block we are freeing is a valid block! */
-    if (!os_memblock_from(mp, block_addr)) {
-        return OS_INVALID_PARM;
-    }
-
-    block = (struct os_memblock *)block_addr;
-    OS_ENTER_CRITICAL(sr);
-    
-    /* Chain current free list pointer to this block; make this block head */
-    SLIST_NEXT(block, mb_next) = SLIST_FIRST(mp);
-    SLIST_FIRST(mp) = block;
-
-    /* XXX: Should we check that the number free <= number blocks? */
-    /* Increment number free */
-    mp->mp_num_free++;
-
-    OS_EXIT_CRITICAL(sr);
-
-    return OS_OK;
-}
-
-
-struct os_mempool *
-os_mempool_info_get_next(struct os_mempool *mp, struct os_mempool_info *omi)
-{
-    struct os_mempool *cur;
-
-    if (mp == NULL) {
-        cur = STAILQ_FIRST(&g_os_mempool_list);
-    } else {
-        cur = STAILQ_NEXT(mp, mp_list);
-    }
-
-    if (cur == NULL) {
-        return (NULL);
-    }
-
-    omi->omi_block_size = cur->mp_block_size;
-    omi->omi_num_blocks = cur->mp_num_blocks;
-    omi->omi_num_free = cur->mp_num_free;
-    strncpy(omi->omi_name, cur->name, sizeof(omi->omi_name));
-
-    return (cur);
-}
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/src/os_msys_init.c
----------------------------------------------------------------------
diff --git a/libs/os/src/os_msys_init.c b/libs/os/src/os_msys_init.c
deleted file mode 100644
index fe0d569..0000000
--- a/libs/os/src/os_msys_init.c
+++ /dev/null
@@ -1,147 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include <assert.h>
-#include "sysinit/sysinit.h"
-#include "syscfg/syscfg.h"
-#include "os/os_mempool.h"
-#include "util/mem.h"
-#include "os_priv.h"
-
-#if MYNEWT_VAL(MSYS_1_BLOCK_COUNT) > 0
-#define SYSINIT_MSYS_1_MEMBLOCK_SIZE                \
-    OS_ALIGN(MYNEWT_VAL(MSYS_1_BLOCK_SIZE), 4)
-#define SYSINIT_MSYS_1_MEMPOOL_SIZE                 \
-    OS_MEMPOOL_SIZE(MYNEWT_VAL(MSYS_1_BLOCK_COUNT),  \
-                    SYSINIT_MSYS_1_MEMBLOCK_SIZE)
-static os_membuf_t os_msys_init_1_data[SYSINIT_MSYS_1_MEMPOOL_SIZE];
-static struct os_mbuf_pool os_msys_init_1_mbuf_pool;
-static struct os_mempool os_msys_init_1_mempool;
-#endif
-
-#if MYNEWT_VAL(MSYS_2_BLOCK_COUNT) > 0
-#define SYSINIT_MSYS_2_MEMBLOCK_SIZE                \
-    OS_ALIGN(MYNEWT_VAL(MSYS_2_BLOCK_SIZE), 4)
-#define SYSINIT_MSYS_2_MEMPOOL_SIZE                 \
-    OS_MEMPOOL_SIZE(MYNEWT_VAL(MSYS_2_BLOCK_COUNT),  \
-                    SYSINIT_MSYS_2_MEMBLOCK_SIZE)
-static os_membuf_t os_msys_init_2_data[SYSINIT_MSYS_2_MEMPOOL_SIZE];
-static struct os_mbuf_pool os_msys_init_2_mbuf_pool;
-static struct os_mempool os_msys_init_2_mempool;
-#endif
-
-#if MYNEWT_VAL(MSYS_3_BLOCK_COUNT) > 0
-#define SYSINIT_MSYS_3_MEMBLOCK_SIZE                \
-    OS_ALIGN(MYNEWT_VAL(MSYS_3_BLOCK_SIZE), 4)
-#define SYSINIT_MSYS_3_MEMPOOL_SIZE                 \
-    OS_MEMPOOL_SIZE(MYNEWT_VAL(MSYS_3_BLOCK_COUNT),  \
-                    SYSINIT_MSYS_3_MEMBLOCK_SIZE)
-static os_membuf_t os_msys_init_3_data[SYSINIT_MSYS_3_MEMPOOL_SIZE];
-static struct os_mbuf_pool os_msys_init_3_mbuf_pool;
-static struct os_mempool os_msys_init_3_mempool;
-#endif
-
-#if MYNEWT_VAL(MSYS_4_BLOCK_COUNT) > 0
-#define SYSINIT_MSYS_4_MEMBLOCK_SIZE                \
-    OS_ALIGN(MYNEWT_VAL(MSYS_4_BLOCK_SIZE), 4)
-#define SYSINIT_MSYS_4_MEMPOOL_SIZE                 \
-    OS_MEMPOOL_SIZE(MYNEWT_VAL(MSYS_4_BLOCK_COUNT),  \
-                    SYSINIT_MSYS_4_MEMBLOCK_SIZE)
-static os_membuf_t os_msys_init_4_data[SYSINIT_MSYS_4_MEMPOOL_SIZE];
-static struct os_mbuf_pool os_msys_init_4_mbuf_pool;
-static struct os_mempool os_msys_init_4_mempool;
-#endif
-
-#if MYNEWT_VAL(MSYS_5_BLOCK_COUNT) > 0
-#define SYSINIT_MSYS_5_MEMBLOCK_SIZE                \
-    OS_ALIGN(MYNEWT_VAL(MSYS_5_BLOCK_SIZE), 4)
-#define SYSINIT_MSYS_5_MEMPOOL_SIZE                 \
-    OS_MEMPOOL_SIZE(MYNEWT_VAL(MSYS_5_BLOCK_COUNT),  \
-                    SYSINIT_MSYS_5_MEMBLOCK_SIZE)
-
-static os_membuf_t os_msys_init_5_data[SYSINIT_MSYS_5_MEMPOOL_SIZE];
-static struct os_mbuf_pool os_msys_init_5_mbuf_pool;
-static struct os_mempool os_msys_init_5_mempool;
-#endif
-
-static void
-os_msys_init_once(void *data, struct os_mempool *mempool,
-                  struct os_mbuf_pool *mbuf_pool,
-                  int block_count, int block_size, char *name)
-{
-    int rc;
-
-    rc = mem_init_mbuf_pool(data, mempool, mbuf_pool, block_count, block_size,
-                            name);
-    SYSINIT_PANIC_ASSERT(rc == 0);
-
-    rc = os_msys_register(mbuf_pool);
-    SYSINIT_PANIC_ASSERT(rc == 0);
-}
-
-void
-os_msys_init(void)
-{
-    os_msys_reset();
-
-#if MYNEWT_VAL(MSYS_1_BLOCK_COUNT) > 0
-    os_msys_init_once(os_msys_init_1_data,
-                      &os_msys_init_1_mempool,
-                      &os_msys_init_1_mbuf_pool,
-                      MYNEWT_VAL(MSYS_1_BLOCK_COUNT),
-                      SYSINIT_MSYS_1_MEMBLOCK_SIZE,
-                      "msys_1");
-#endif
-
-#if MYNEWT_VAL(MSYS_2_BLOCK_COUNT) > 0
-    os_msys_init_once(os_msys_init_2_data,
-                      &os_msys_init_2_mempool,
-                      &os_msys_init_2_mbuf_pool,
-                      MYNEWT_VAL(MSYS_2_BLOCK_COUNT),
-                      SYSINIT_MSYS_2_MEMBLOCK_SIZE,
-                      "msys_2");
-#endif
-
-#if MYNEWT_VAL(MSYS_3_BLOCK_COUNT) > 0
-    os_msys_init_once(os_msys_init_3_data,
-                      &os_msys_init_3_mempool,
-                      &os_msys_init_3_mbuf_pool,
-                      MYNEWT_VAL(MSYS_3_BLOCK_COUNT),
-                      SYSINIT_MSYS_3_MEMBLOCK_SIZE,
-                      "msys_3");
-#endif
-
-#if MYNEWT_VAL(MSYS_4_BLOCK_COUNT) > 0
-    os_msys_init_once(os_msys_init_4_data,
-                      &os_msys_init_4_mempool,
-                      &os_msys_init_4_mbuf_pool,
-                      MYNEWT_VAL(MSYS_4_BLOCK_COUNT),
-                      SYSINIT_MSYS_4_MEMBLOCK_SIZE,
-                      "msys_4");
-#endif
-
-#if MYNEWT_VAL(MSYS_5_BLOCK_COUNT) > 0
-    os_msys_init_once(os_msys_init_5_data,
-                      &os_msys_init_5_mempool,
-                      &os_msys_init_5_mbuf_pool,
-                      MYNEWT_VAL(MSYS_5_BLOCK_COUNT),
-                      SYSINIT_MSYS_5_MEMBLOCK_SIZE,
-                      "msys_5");
-#endif
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/src/os_mutex.c
----------------------------------------------------------------------
diff --git a/libs/os/src/os_mutex.c b/libs/os/src/os_mutex.c
deleted file mode 100644
index 6519292..0000000
--- a/libs/os/src/os_mutex.c
+++ /dev/null
@@ -1,236 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include "os/os.h"
-#include <assert.h>
-
-/**
- * os mutex create
- *  
- * Create a mutex and initialize it. 
- * 
- * @param mu Pointer to mutex
- * 
- * @return os_error_t 
- *      OS_INVALID_PARM     Mutex passed in was NULL.
- *      OS_OK               no error.
- */
-os_error_t
-os_mutex_init(struct os_mutex *mu)
-{
-    if (!mu) {
-        return OS_INVALID_PARM;
-    }
-
-    /* Initialize to 0 */
-    mu->mu_prio = 0;
-    mu->mu_level = 0;
-    mu->mu_owner = NULL;
-    SLIST_FIRST(&mu->mu_head) = NULL;
-
-    return OS_OK;
-}
-
-/**
- * os mutex release
- *  
- * Release a mutex. 
- * 
- * @param mu Pointer to the mutex to be released
- * 
- * @return os_error_t 
- *      OS_INVALID_PARM Mutex passed in was NULL.
- *      OS_BAD_MUTEX    Mutex was not granted to current task (not owner).
- *      OS_OK           No error
- */
-os_error_t
-os_mutex_release(struct os_mutex *mu)
-{
-    int resched;
-    os_sr_t sr;
-    struct os_task *current;
-    struct os_task *rdy;
-
-    /* Check if OS is started */
-    if (!g_os_started) {
-        return (OS_NOT_STARTED);
-    }
-
-    /* Check for valid mutex */
-    if (!mu) {
-        return OS_INVALID_PARM;
-    }
-
-    /* We better own this mutex! */
-    current = os_sched_get_current_task();
-    if ((mu->mu_level == 0) || (mu->mu_owner != current)) {
-        return (OS_BAD_MUTEX);
-    }
-
-    /* Decrement nesting level by 1. If not zero, nested (so dont release!) */
-    --mu->mu_level;
-    if (mu->mu_level != 0) {
-        return (OS_OK);
-    }
-
-    OS_ENTER_CRITICAL(sr);
-
-    /* Restore owner task's priority; resort list if different  */
-    if (current->t_prio != mu->mu_prio) {
-        current->t_prio = mu->mu_prio;
-        os_sched_resort(current);
-    }
-
-    /* Check if tasks are waiting for the mutex */
-    rdy = SLIST_FIRST(&mu->mu_head);
-    if (rdy) {
-        /* There is one waiting. Wake it up */
-        assert(rdy->t_obj);
-        os_sched_wakeup(rdy);
-
-        /* Set mutex internals */
-        mu->mu_level = 1;
-        mu->mu_prio = rdy->t_prio;
-    }
-
-    /* Set new owner of mutex (or NULL if not owned) */
-    mu->mu_owner = rdy;
-
-    /* Do we need to re-schedule? */
-    resched = 0;
-    rdy = os_sched_next_task();
-    if (rdy != current) {
-        resched = 1;
-    }
-    OS_EXIT_CRITICAL(sr);
-
-    /* Re-schedule if needed */
-    if (resched) {
-        os_sched(rdy);
-    }
-
-    return OS_OK;
-}
-
-/**
- * os mutex pend 
- *  
- * Pend (wait) for a mutex. 
- * 
- * @param mu Pointer to mutex.
- * @param timeout Timeout, in os ticks. A timeout of 0 means do 
- *                not wait if not available. A timeout of
- *                0xFFFFFFFF means wait forever.
- *              
- * 
- * @return os_error_t 
- *      OS_INVALID_PARM     Mutex passed in was NULL.
- *      OS_TIMEOUT          Mutex was owned by another task and timeout=0
- *      OS_OK               no error.
- */ 
-os_error_t
-os_mutex_pend(struct os_mutex *mu, uint32_t timeout)
-{
-    os_sr_t sr;
-    os_error_t rc;
-    struct os_task *current;
-    struct os_task *entry;
-    struct os_task *last;
-
-    /* OS must be started when calling this function */
-    if (!g_os_started) {
-        return (OS_NOT_STARTED);
-    }
-
-    /* Check for valid mutex */
-    if (!mu) {
-        return OS_INVALID_PARM;
-    }
-
-    OS_ENTER_CRITICAL(sr);
-
-    /* Is this owned? */
-    current = os_sched_get_current_task();
-    if (mu->mu_level == 0) {
-        mu->mu_owner = current;
-        mu->mu_prio  = current->t_prio;
-        mu->mu_level = 1;
-        OS_EXIT_CRITICAL(sr);
-        return OS_OK;
-    }
-
-    /* Are we owner? */
-    if (mu->mu_owner == current) {
-        ++mu->mu_level;
-        OS_EXIT_CRITICAL(sr);
-        return OS_OK;
-    }
-
-    /* Mutex is not owned by us. If timeout is 0, return immediately */
-    if (timeout == 0) {
-        OS_EXIT_CRITICAL(sr);
-        return OS_TIMEOUT;
-    }
-
-    /* Change priority of owner if needed */
-    if (mu->mu_owner->t_prio > current->t_prio) {
-        mu->mu_owner->t_prio = current->t_prio;
-        os_sched_resort(mu->mu_owner);
-    }
-
-    /* Link current task to tasks waiting for mutex */
-    last = NULL;
-    if (!SLIST_EMPTY(&mu->mu_head)) {
-        /* Insert in priority order */
-        SLIST_FOREACH(entry, &mu->mu_head, t_obj_list) {
-            if (current->t_prio < entry->t_prio) { 
-                break;
-            }
-            last = entry;
-        }
-    }
-
-    if (last) {
-        SLIST_INSERT_AFTER(last, current, t_obj_list);
-    } else {
-        SLIST_INSERT_HEAD(&mu->mu_head, current, t_obj_list);
-    }
-
-    /* Set mutex pointer in task */
-    current->t_obj = mu;
-    current->t_flags |= OS_TASK_FLAG_MUTEX_WAIT;
-    os_sched_sleep(current, timeout);
-    OS_EXIT_CRITICAL(sr);
-
-    os_sched(NULL);
-
-    OS_ENTER_CRITICAL(sr);
-    current->t_flags &= ~OS_TASK_FLAG_MUTEX_WAIT;
-    OS_EXIT_CRITICAL(sr);
-
-    /* If we are owner we did not time out. */
-    if (mu->mu_owner == current) {
-        rc = OS_OK; 
-    } else {
-        rc = OS_TIMEOUT;
-    }
-
-    return rc;
-}
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/src/os_priv.h
----------------------------------------------------------------------
diff --git a/libs/os/src/os_priv.h b/libs/os/src/os_priv.h
deleted file mode 100644
index 7745a0a..0000000
--- a/libs/os/src/os_priv.h
+++ /dev/null
@@ -1,38 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 H_OS_PRIV_
-#define H_OS_PRIV_
-
-#include "os/queue.h"
-
-TAILQ_HEAD(os_task_list, os_task);
-TAILQ_HEAD(os_callout_list, os_callout);
-STAILQ_HEAD(os_task_stailq, os_task);
-
-extern struct os_task g_idle_task;
-extern struct os_task_list g_os_run_list;
-extern struct os_task_list g_os_sleep_list;
-extern struct os_task_stailq g_os_task_list;
-extern struct os_task *g_current_task;
-extern struct os_callout_list g_callout_list;
-
-void os_msys_init(void);
-
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/src/os_sanity.c
----------------------------------------------------------------------
diff --git a/libs/os/src/os_sanity.c b/libs/os/src/os_sanity.c
deleted file mode 100644
index f0aa5d2..0000000
--- a/libs/os/src/os_sanity.c
+++ /dev/null
@@ -1,238 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include <assert.h>
-#include <string.h>
-
-#include "os/os.h"
-
-SLIST_HEAD(, os_sanity_check) g_os_sanity_check_list =
-    SLIST_HEAD_INITIALIZER(os_sanity_check_list);
-
-struct os_mutex g_os_sanity_check_mu;
-
-/**
- * Initialize a sanity check
- *
- * @param sc The sanity check to initialize
- *
- * @return 0 on success, error code on failure.
- */
-int
-os_sanity_check_init(struct os_sanity_check *sc)
-{
-    memset(sc, 0, sizeof(*sc));
-
-    return (0);
-}
-
-/**
- * Lock the sanity check list
- *
- * @return 0 on success, error code on failure.
- */
-static int
-os_sanity_check_list_lock(void)
-{
-    int rc;
-
-    if (!g_os_started) {
-        return (0);
-    }
-
-    rc = os_mutex_pend(&g_os_sanity_check_mu, OS_WAIT_FOREVER);
-    if (rc != OS_OK) {
-        goto err;
-    }
-
-    return (0);
-err:
-    return (rc);
-}
-
-/**
- * Unlock the sanity check list
- *
- * @return 0 on success, error code on failure
- */
-static int
-os_sanity_check_list_unlock(void)
-{
-    int rc;
-
-    if (!g_os_started) {
-        return (0);
-    }
-
-    rc = os_mutex_release(&g_os_sanity_check_mu);
-    if (rc != 0) {
-        goto err;
-    }
-
-    return (0);
-err:
-    return (rc);
-}
-
-/**
- * Provide a "task checkin" for the sanity task.
- *
- * @param t The task to check in
- *
- * @return 0 on success, error code on failure
- */
-int
-os_sanity_task_checkin(struct os_task *t)
-{
-    int rc;
-
-    if (t == NULL) {
-        t = os_sched_get_current_task();
-    }
-
-    rc = os_sanity_check_reset(&t->t_sanity_check);
-    if (rc != OS_OK) {
-        goto err;
-    }
-
-    return (0);
-err:
-    return (rc);
-}
-
-
-/**
- * Register a sanity check
- *
- * @param sc The sanity check to register
- *
- * @return 0 on success, error code on failure
- */
-int
-os_sanity_check_register(struct os_sanity_check *sc)
-{
-    int rc;
-
-    rc = os_sanity_check_list_lock();
-    if (rc != OS_OK) {
-        goto err;
-    }
-
-    SLIST_INSERT_HEAD(&g_os_sanity_check_list, sc, sc_next);
-
-    rc = os_sanity_check_list_unlock();
-    if (rc != OS_OK) {
-        goto err;
-    }
-
-    return (0);
-err:
-    return (rc);
-}
-
-
-/**
- * Reset the os sanity check, so that it doesn't trip up the
- * sanity timer.
- *
- * @param sc The sanity check to reset
- *
- * @return 0 on success, error code on failure
- */
-int
-os_sanity_check_reset(struct os_sanity_check *sc)
-{
-    int rc;
-
-    rc = os_sanity_check_list_lock();
-    if (rc != OS_OK) {
-        goto err;
-    }
-
-    sc->sc_checkin_last = os_time_get();
-
-    rc = os_sanity_check_list_unlock();
-    if (rc != OS_OK) {
-        goto err;
-    }
-
-    return (0);
-err:
-    return (rc);
-}
-
-/*
- * Called from the IDLE task context, every MYNEWT_VAL(SANITY_INTERVAL) msecs.
- *
- * Goes through the sanity check list, and performs sanity checks.  If any of
- * these checks failed, or tasks have not checked in, it resets the processor.
- */
-void
-os_sanity_run(void)
-{
-    struct os_sanity_check *sc;
-    int rc;
-
-    rc = os_sanity_check_list_lock();
-    if (rc != 0) {
-        assert(0);
-    }
-
-    SLIST_FOREACH(sc, &g_os_sanity_check_list, sc_next) {
-        rc = OS_OK;
-
-        if (sc->sc_func) {
-            rc = sc->sc_func(sc, sc->sc_arg);
-            if (rc == OS_OK) {
-                sc->sc_checkin_last = os_time_get();
-                continue;
-            }
-        }
-
-        if (OS_TIME_TICK_GT(os_time_get(),
-                    sc->sc_checkin_last + sc->sc_checkin_itvl)) {
-            assert(0);
-        }
-    }
-
-    rc = os_sanity_check_list_unlock();
-    if (rc != 0) {
-        assert(0);
-    }
-}
-
-/**
- * Initialize the sanity task and mutex.
- *
- * @return 0 on success, error code on failure
- */
-int
-os_sanity_init(void)
-{
-    int rc;
-
-    rc = os_mutex_init(&g_os_sanity_check_mu);
-    if (rc != 0) {
-        goto err;
-    }
-
-    return (0);
-err:
-    return (rc);
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/src/os_sched.c
----------------------------------------------------------------------
diff --git a/libs/os/src/os_sched.c b/libs/os/src/os_sched.c
deleted file mode 100644
index 3d81dba..0000000
--- a/libs/os/src/os_sched.c
+++ /dev/null
@@ -1,330 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include "os/os.h"
-#include "os/queue.h"
-
-#include <assert.h>
-
-TAILQ_HEAD(, os_task) g_os_run_list = TAILQ_HEAD_INITIALIZER(g_os_run_list); 
-
-TAILQ_HEAD(, os_task) g_os_sleep_list = TAILQ_HEAD_INITIALIZER(g_os_sleep_list); 
-
-struct os_task *g_current_task; 
-
-extern os_time_t g_os_time;
-os_time_t g_os_last_ctx_sw_time;
-
-/**
- * os sched insert
- *  
- * Insert a task into the scheduler list. This causes the task to be evaluated
- * for running when os_sched is called. 
- * 
- * @param t     Pointer to task to insert in run list
- * 
- * @return int  OS_OK: task was inserted into run list 
- *              OS_EINVAL: Task was not in ready state. 
- */
-os_error_t
-os_sched_insert(struct os_task *t) 
-{
-    struct os_task *entry; 
-    os_sr_t sr; 
-    os_error_t rc;
-
-    if (t->t_state != OS_TASK_READY) {
-        rc = OS_EINVAL;
-        goto err;
-    }
-
-    entry = NULL;
-    OS_ENTER_CRITICAL(sr); 
-    TAILQ_FOREACH(entry, &g_os_run_list, t_os_list) {
-        if (t->t_prio < entry->t_prio) { 
-            break;
-        }
-    }
-    if (entry) {
-        TAILQ_INSERT_BEFORE(entry, (struct os_task *) t, t_os_list);
-    } else {
-        TAILQ_INSERT_TAIL(&g_os_run_list, (struct os_task *) t, t_os_list);
-    }
-    OS_EXIT_CRITICAL(sr);
-
-    return (0);
-err:
-    return (rc);
-}
-
-void
-os_sched_ctx_sw_hook(struct os_task *next_t)
-{
-    if (g_current_task == next_t) {
-        return;
-    }
-
-    next_t->t_ctx_sw_cnt++;
-    g_current_task->t_run_time += g_os_time - g_os_last_ctx_sw_time;
-    g_os_last_ctx_sw_time = g_os_time;
-}
-
-
-/**
- * os sched get current task 
- *  
- * Returns the currently running task. Note that this task may or may not be 
- * the highest priority task ready to run. 
- * 
- * 
- * @return struct os_task* 
- */
-struct os_task * 
-os_sched_get_current_task(void)
-{
-    return (g_current_task);
-}
-
-/**
- * os sched set current task 
- *  
- * Sets the currently running task to 't'. Note that this function simply sets 
- * the global variable holding the currently running task. It does not perform 
- * a context switch or change the os run or sleep list. 
- * 
- * @param t Pointer to currently running task.
- */
-void 
-os_sched_set_current_task(struct os_task *t) 
-{
-    g_current_task = t;
-}
-
-/**
- * os sched 
- *  
- * Performs a context switch. When called, it will either find the highest 
- * priority task ready to run if next_t is NULL (i.e. the head of the os run 
- * list) or will schedule next_t as the task to run.
- * 
- * @param next_t Task to run
- */
-void
-os_sched(struct os_task *next_t)
-{
-    os_sr_t sr;
-
-    OS_ENTER_CRITICAL(sr);
-
-    if (!next_t) {
-        next_t = os_sched_next_task();
-    }
-
-    if (next_t != g_current_task) {
-        os_arch_ctx_sw(next_t);
-    }
-
-    OS_EXIT_CRITICAL(sr);
-}
-
-/**
- * os sched sleep 
- *  
- * Removes the task from the run list and puts it on the sleep list. 
- * 
- * @param t Task to put to sleep
- * @param nticks Number of ticks to put task to sleep
- * 
- * @return int
- *  
- * NOTE: must be called with interrupts disabled! This function does not call 
- * the scheduler 
- */
-int 
-os_sched_sleep(struct os_task *t, os_time_t nticks) 
-{
-    struct os_task *entry;
-
-    entry = NULL; 
-
-    TAILQ_REMOVE(&g_os_run_list, t, t_os_list);
-    t->t_state = OS_TASK_SLEEP;
-    t->t_next_wakeup = os_time_get() + nticks;
-    if (nticks == OS_TIMEOUT_NEVER) {
-        t->t_flags |= OS_TASK_FLAG_NO_TIMEOUT;
-        TAILQ_INSERT_TAIL(&g_os_sleep_list, t, t_os_list); 
-    } else {
-        TAILQ_FOREACH(entry, &g_os_sleep_list, t_os_list) {
-            if ((entry->t_flags & OS_TASK_FLAG_NO_TIMEOUT) ||
-                    OS_TIME_TICK_GT(entry->t_next_wakeup, t->t_next_wakeup)) {
-                break;
-            }
-        }
-        if (entry) {
-            TAILQ_INSERT_BEFORE(entry, t, t_os_list); 
-        } else {
-            TAILQ_INSERT_TAIL(&g_os_sleep_list, t, t_os_list); 
-        }
-    }
-
-    return (0);
-}
-
-/**
- * os sched wakeup 
- *  
- * Called to wake up a task. Waking up a task consists of setting the task state
- * to READY and moving it from the sleep list to the run list. 
- * 
- * @param t     Pointer to task to wake up. 
- * 
- * @return int 
- *  
- * NOTE: This function must be called with interrupts disabled. 
- */
-int 
-os_sched_wakeup(struct os_task *t) 
-{
-    struct os_task_obj *os_obj;
-
-    assert(t->t_state == OS_TASK_SLEEP);
-
-    /* Remove self from object list if waiting on one */
-    if (t->t_obj) {
-        os_obj = (struct os_task_obj *)t->t_obj;
-        assert(!SLIST_EMPTY(&os_obj->obj_head));
-        SLIST_REMOVE(&os_obj->obj_head, t, os_task, t_obj_list);
-        SLIST_NEXT(t, t_obj_list) = NULL;
-        t->t_obj = NULL; 
-    }
-
-    /* Remove task from sleep list */
-    t->t_state = OS_TASK_READY;
-    t->t_next_wakeup = 0;
-    t->t_flags &= ~OS_TASK_FLAG_NO_TIMEOUT;
-    TAILQ_REMOVE(&g_os_sleep_list, t, t_os_list);
-    os_sched_insert(t);
-
-    return (0);
-}
-
-/**
- * os sched os timer exp 
- *  
- * Called when the OS tick timer expires. Search the sleep list for any tasks 
- * that need waking up. This occurs when the current OS time exceeds the next 
- * wakeup time stored in the task. Any tasks that need waking up will be 
- * removed from the sleep list and added to the run list. 
- * 
- */
-void
-os_sched_os_timer_exp(void)
-{
-    struct os_task *t;
-    struct os_task *next;
-    os_time_t now; 
-    os_sr_t sr;
-
-    now = os_time_get();
-
-    OS_ENTER_CRITICAL(sr);
-
-    /*
-     * Wakeup any tasks that have their sleep timer expired
-     */
-    t = TAILQ_FIRST(&g_os_sleep_list);
-    while (t) {
-        /* If task waiting forever, do not check next wakeup time */
-        if (t->t_flags & OS_TASK_FLAG_NO_TIMEOUT) {
-            break;
-        }
-        next = TAILQ_NEXT(t, t_os_list);
-        if (OS_TIME_TICK_GEQ(now, t->t_next_wakeup)) {
-            os_sched_wakeup(t);
-        } else {
-            break;
-        }
-        t = next;
-    }
-
-    OS_EXIT_CRITICAL(sr); 
-}
-
-/*
- * Return the number of ticks until the first sleep timer expires.If there are
- * no such tasks then return OS_TIMEOUT_NEVER instead.
- */
-os_time_t
-os_sched_wakeup_ticks(os_time_t now)
-{
-    os_time_t rt;
-    struct os_task *t;
-
-    OS_ASSERT_CRITICAL();
-
-    t = TAILQ_FIRST(&g_os_sleep_list);
-    if (t == NULL || (t->t_flags & OS_TASK_FLAG_NO_TIMEOUT)) {
-        rt = OS_TIMEOUT_NEVER;
-    } else if (OS_TIME_TICK_GEQ(t->t_next_wakeup, now)) {
-        rt = t->t_next_wakeup - now;   
-    } else {
-        rt = 0;     /* wakeup time was in the past */
-    }
-    return (rt);
-}
-
-/**
- * os sched next task 
- *  
- * Returns the task that we should be running. This is the task at the head 
- * of the run list. 
- *  
- * NOTE: if you want to guarantee that the os run list does not change after 
- * calling this function you have to call it with interrupts disabled. 
- * 
- * @return struct os_task* 
- */
-struct os_task *  
-os_sched_next_task(void) 
-{
-    return (TAILQ_FIRST(&g_os_run_list));
-}
-
-/**
- * os sched resort 
- *  
- * Resort a task that is in the ready list as its priority has 
- * changed. If the task is not in the ready state, there is 
- * nothing to do. 
- * 
- * @param t Pointer to task to insert back into ready to run 
- *          list.
- *  
- * NOTE: this function expects interrupts to be disabled so they 
- * are not disabled here. 
- */
-void 
-os_sched_resort(struct os_task *t) 
-{
-    if (t->t_state == OS_TASK_READY) {
-        TAILQ_REMOVE(&g_os_run_list, t, t_os_list);
-        os_sched_insert(t);
-    }
-}
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/src/os_sem.c
----------------------------------------------------------------------
diff --git a/libs/os/src/os_sem.c b/libs/os/src/os_sem.c
deleted file mode 100644
index 181e5de..0000000
--- a/libs/os/src/os_sem.c
+++ /dev/null
@@ -1,212 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include "os/os.h"
-#include <assert.h>
-
-/* XXX:
- * 1) Should I check to see if we are within an ISR for some of these?
- * 2) Would I do anything different for os_sem_release() if we were in an
- *    ISR when this was called?
- */
-
-/**
- * os sem create
- *  
- * Create a semaphore and initialize it. 
- * 
- * @param sem Pointer to semaphore 
- *        tokens: # of tokens the semaphore should contain initially.   
- * 
- * @return os_error_t 
- *      OS_INVALID_PARM     Semaphore passed in was NULL.
- *      OS_OK               no error.
- */
-os_error_t
-os_sem_init(struct os_sem *sem, uint16_t tokens)
-{
-    if (!sem) {
-        return OS_INVALID_PARM;
-    }
-
-    sem->sem_tokens = tokens;
-    SLIST_FIRST(&sem->sem_head) = NULL;
-
-    return OS_OK;
-}
-
-/**
- * os sem release
- *  
- * Release a semaphore. 
- * 
- * @param sem Pointer to the semaphore to be released
- * 
- * @return os_error_t 
- *      OS_INVALID_PARM Semaphore passed in was NULL.
- *      OS_OK No error
- */
-os_error_t
-os_sem_release(struct os_sem *sem)
-{
-    int resched;
-    os_sr_t sr;
-    struct os_task *current;
-    struct os_task *rdy;
-
-    /* OS must be started to release semaphores */ 
-    if (!g_os_started) {
-        return (OS_NOT_STARTED);
-    }
-
-    /* Check for valid semaphore */
-    if (!sem) {
-        return OS_INVALID_PARM;
-    }
-
-    /* Get current task */
-    resched = 0;
-    current = os_sched_get_current_task();
-
-    OS_ENTER_CRITICAL(sr);
-
-    /* Check if tasks are waiting for the semaphore */
-    rdy = SLIST_FIRST(&sem->sem_head);
-    if (rdy) {
-        /* Clear flag that we are waiting on the semaphore; wake up task */
-        rdy->t_flags &= ~OS_TASK_FLAG_SEM_WAIT;
-        os_sched_wakeup(rdy);
-
-        /* Schedule if waiting task higher priority */
-        if (current->t_prio > rdy->t_prio) {
-            resched = 1;
-        }
-    } else {
-        /* Add to the number of tokens */
-        sem->sem_tokens++;
-    }
-
-    OS_EXIT_CRITICAL(sr);
-
-    /* Re-schedule if needed */
-    if (resched) {
-        os_sched(rdy);
-    }
-
-    return OS_OK;
-}
-
-/**
- * os sem pend 
- *  
- * Pend (wait) for a semaphore. 
- * 
- * @param mu Pointer to semaphore.
- * @param timeout Timeout, in os ticks. A timeout of 0 means do 
- *                not wait if not available. A timeout of
- *                0xFFFFFFFF means wait forever.
- *              
- * 
- * @return os_error_t 
- *      OS_INVALID_PARM     Semaphore passed in was NULL.
- *      OS_TIMEOUT          Semaphore was owned by another task and timeout=0
- *      OS_OK               no error.
- */ 
-os_error_t
-os_sem_pend(struct os_sem *sem, uint32_t timeout)
-{
-    os_sr_t sr;
-    os_error_t rc;
-    int sched;
-    struct os_task *current;
-    struct os_task *entry;
-    struct os_task *last;
-
-    /* Check if OS is started */
-    if (!g_os_started) {
-        return (OS_NOT_STARTED);
-    }
-
-    /* Check for valid semaphore */
-    if (!sem) {
-        return OS_INVALID_PARM;
-    }
-
-    /* Assume we dont have to put task to sleep; get current task */
-    sched = 0;
-    current = os_sched_get_current_task();
-
-    OS_ENTER_CRITICAL(sr);
-
-    /* 
-     * If there is a token available, take it. If no token, either return
-     * with error if timeout was 0 or put this task to sleep.
-     */
-    if (sem->sem_tokens != 0) {
-        sem->sem_tokens--;
-        rc = OS_OK;
-    } else if (timeout == 0) {
-        rc = OS_TIMEOUT;
-    } else {
-        /* Silence gcc maybe-uninitialized warning. */
-        rc = OS_OK;
-
-        /* Link current task to tasks waiting for semaphore */
-        current->t_obj = sem; 
-        current->t_flags |= OS_TASK_FLAG_SEM_WAIT;
-        last = NULL;
-        if (!SLIST_EMPTY(&sem->sem_head)) {
-            /* Insert in priority order */
-            SLIST_FOREACH(entry, &sem->sem_head, t_obj_list) {
-                if (current->t_prio < entry->t_prio) { 
-                    break;
-                }
-                last = entry;
-            }
-        }
-
-        if (last) {
-            SLIST_INSERT_AFTER(last, current, t_obj_list);
-        } else {
-            SLIST_INSERT_HEAD(&sem->sem_head, current, t_obj_list);
-        }
-
-        /* We will put this task to sleep */
-        sched = 1;
-        os_sched_sleep(current, timeout);
-    }
-
-    OS_EXIT_CRITICAL(sr);
-
-    if (sched) {
-        os_sched(NULL);
-        /* Check if we timed out or got the semaphore */
-        if (current->t_flags & OS_TASK_FLAG_SEM_WAIT) {
-            OS_ENTER_CRITICAL(sr);
-            current->t_flags &= ~OS_TASK_FLAG_SEM_WAIT;
-            OS_EXIT_CRITICAL(sr);
-            rc = OS_TIMEOUT;
-        } else {
-            rc = OS_OK; 
-        }
-    }
-
-    return rc;
-}
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/src/os_task.c
----------------------------------------------------------------------
diff --git a/libs/os/src/os_task.c b/libs/os/src/os_task.c
deleted file mode 100644
index 9e2860b..0000000
--- a/libs/os/src/os_task.c
+++ /dev/null
@@ -1,216 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-
-#include "os/os.h"
-#include "os_priv.h"
-
-#include <string.h>
-
-uint8_t g_task_id;
-
-struct os_task_stailq g_os_task_list;
-
-static void
-_clear_stack(os_stack_t *stack_bottom, int size)
-{
-    int i;
-
-    for (i = 0; i < size; i++) {
-        stack_bottom[i] = OS_STACK_PATTERN;
-    }
-}
-
-static inline uint8_t
-os_task_next_id(void)
-{
-    uint8_t rc;
-    os_sr_t sr;
-
-    OS_ENTER_CRITICAL(sr);
-    rc = g_task_id;
-    g_task_id++;
-    OS_EXIT_CRITICAL(sr);
-
-    return (rc);
-}
-
-/**
- * Return the number of tasks initialized.
- *
- * @return number of tasks initialized
- */
-uint8_t
-os_task_count(void)
-{
-    return (g_task_id);
-}
-
-/**
- * Initialize a task.
- *
- * This function initializes the task structure pointed to by t,
- * clearing and setting it's stack pointer, provides sane defaults
- * and sets the task as ready to run, and inserts it into the operating
- * system scheduler.
- *
- * @param t The task to initialize
- * @param name The name of the task to initialize
- * @param func The task function to call
- * @param arg The argument to pass to this task function
- * @param prio The priority at which to run this task
- * @param sanity_itvl The time at which this task should check in with the
- *                    sanity task.  OS_WAIT_FOREVER means never check in
- *                    here.
- * @param stack_bottom A pointer to the bottom of a task's stack
- * @param stack_size The overall size of the task's stack.
- *
- * @return 0 on success, non-zero on failure.
- */
-int
-os_task_init(struct os_task *t, const char *name, os_task_func_t func,
-        void *arg, uint8_t prio, os_time_t sanity_itvl,
-        os_stack_t *stack_bottom, uint16_t stack_size)
-{
-    struct os_sanity_check *sc;
-    int rc;
-
-    memset(t, 0, sizeof(*t));
-
-    t->t_func = func;
-    t->t_arg = arg;
-
-    t->t_taskid = os_task_next_id();
-    t->t_prio = prio;
-
-    t->t_state = OS_TASK_READY;
-    t->t_name = name;
-    t->t_next_wakeup = 0;
-
-    rc = os_sanity_check_init(&t->t_sanity_check);
-    if (rc != OS_OK) {
-        goto err;
-    }
-
-    if (sanity_itvl != OS_WAIT_FOREVER) {
-        sc = (struct os_sanity_check *) &t->t_sanity_check;
-        sc->sc_checkin_itvl = sanity_itvl;
-
-        rc = os_sanity_check_register(sc);
-        if (rc != OS_OK) {
-            goto err;
-        }
-    }
-
-    _clear_stack(stack_bottom, stack_size);
-    t->t_stackptr = os_arch_task_stack_init(t, &stack_bottom[stack_size],
-            stack_size);
-    t->t_stacktop = &stack_bottom[stack_size];
-    t->t_stacksize = stack_size;
-
-    /* insert this task into the task list */
-    STAILQ_INSERT_TAIL(&g_os_task_list, t, t_os_task_list);
-
-    /* insert this task into the scheduler list */
-    rc = os_sched_insert(t);
-    if (rc != OS_OK) {
-        goto err;
-    }
-
-
-    return (0);
-err:
-    return (rc);
-}
-
-/**
- * Iterate through tasks, and return the following information about them:
- *
- * - Priority
- * - Task ID
- * - State (ACTIVE, SLEEP)
- * - Total Stack Usage
- * - Stack Size
- * - Context Switch Count
- * - Runtime
- * - Last & Next Sanity checkin
- * - Task Name
- *
- * To get the first task in the list, call os_task_info_get_next() with a
- * NULL pointer in the prev argument, and os_task_info_get_next() will
- * return a pointer to the task structure, and fill out the os_task_info
- * structure pointed to by oti.
- *
- * To get the next task in the list, provide the task structure returned
- * by the previous call to os_task_info_get_next(), and os_task_info_get_next()
- * will fill out the task structure pointed to by oti again, and return
- * the next task in the list.
- *
- * @param prev The previous task returned by os_task_info_get_next(), or NULL
- *             to begin iteration.
- * @param oti  The OS task info structure to fill out.
- *
- * @return A pointer to the OS task that has been read, or NULL when finished
- *         iterating through all tasks.
- */
-struct os_task *
-os_task_info_get_next(const struct os_task *prev, struct os_task_info *oti)
-{
-    struct os_task *next;
-    os_stack_t *top;
-    os_stack_t *bottom;
-
-    if (prev != NULL) {
-        next = STAILQ_NEXT(prev, t_os_task_list);
-    } else {
-        next = STAILQ_FIRST(&g_os_task_list);
-    }
-
-    if (next == NULL) {
-        return (NULL);
-    }
-
-    /* Otherwise, copy OS task information into the OTI structure, and
-     * return 1, which means continue
-     */
-    oti->oti_prio = next->t_prio;
-    oti->oti_taskid = next->t_taskid;
-    oti->oti_state = next->t_state;
-
-    top = next->t_stacktop;
-    bottom = next->t_stacktop - next->t_stacksize;
-    while (bottom < top) {
-        if (*bottom != OS_STACK_PATTERN) {
-            break;
-        }
-        ++bottom;
-    }
-
-    oti->oti_stkusage = (uint16_t) (next->t_stacktop - bottom);
-    oti->oti_stksize = next->t_stacksize;
-    oti->oti_cswcnt = next->t_ctx_sw_cnt;
-    oti->oti_runtime = next->t_run_time;
-    oti->oti_last_checkin = next->t_sanity_check.sc_checkin_last;
-    oti->oti_next_checkin = next->t_sanity_check.sc_checkin_last +
-        next->t_sanity_check.sc_checkin_itvl;
-    strncpy(oti->oti_name, next->t_name, sizeof(oti->oti_name));
-
-    return (next);
-}
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/src/os_time.c
----------------------------------------------------------------------
diff --git a/libs/os/src/os_time.c b/libs/os/src/os_time.c
deleted file mode 100644
index 4ef439f..0000000
--- a/libs/os/src/os_time.c
+++ /dev/null
@@ -1,248 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include <util/util.h>
-#include <assert.h>
-
-#include "os/os.h"
-#include "os/queue.h"
-
-CTASSERT(sizeof(os_time_t) == 4);
-
-#define OS_USEC_PER_TICK    (1000000 / OS_TICKS_PER_SEC)
-
-os_time_t g_os_time;
-
-/*
- * Time-of-day collateral.
- */
-static struct {
-    os_time_t ostime;
-    struct os_timeval uptime;
-    struct os_timeval utctime;
-    struct os_timezone timezone;
-} basetod;
-
-static void
-os_deltatime(os_time_t delta, const struct os_timeval *base,
-    struct os_timeval *result)
-{
-    struct os_timeval tvdelta;
-
-    tvdelta.tv_sec = delta / OS_TICKS_PER_SEC;
-    tvdelta.tv_usec = (delta % OS_TICKS_PER_SEC) * OS_USEC_PER_TICK;
-    os_timeradd(base, &tvdelta, result);
-}
-
-/**
- * Get the current OS time in ticks
- *
- * @return OS time in ticks
- */
-os_time_t
-os_time_get(void)
-{
-    return (g_os_time);
-}
-
-static void
-os_time_tick(int ticks)
-{
-    os_sr_t sr;
-    os_time_t delta, prev_os_time;
-
-    assert(ticks >= 0);
-
-    OS_ENTER_CRITICAL(sr);
-    prev_os_time = g_os_time;
-    g_os_time += ticks;
-
-    /*
-     * Update 'basetod' when 'g_os_time' crosses the 0x00000000 and
-     * 0x80000000 thresholds.
-     */
-    if ((prev_os_time ^ g_os_time) >> 31) {
-        delta = g_os_time - basetod.ostime;
-        os_deltatime(delta, &basetod.uptime, &basetod.uptime);
-        os_deltatime(delta, &basetod.utctime, &basetod.utctime);
-        basetod.ostime = g_os_time;
-    }
-    OS_EXIT_CRITICAL(sr);
-}
-
-/**
- * Move OS time forward ticks.
- *
- * @param ticks The number of ticks to move time forward.
- */
-void
-os_time_advance(int ticks)
-{
-    assert(ticks >= 0);
-
-    if (ticks > 0) {
-        if (!os_started()) {
-            g_os_time += ticks;
-        } else {
-            os_time_tick(ticks);
-            os_callout_tick();
-            os_sched_os_timer_exp();
-            os_sched(NULL);
-        }
-    }
-}
-
-/**
- * Puts the current task to sleep for the specified number of os ticks. There
- * is no delay if ticks is <= 0.
- *
- * @param osticks Number of ticks to delay (<= 0 means no delay).
- */
-void
-os_time_delay(int32_t osticks)
-{
-    os_sr_t sr;
-
-    if (osticks > 0) {
-        OS_ENTER_CRITICAL(sr);
-        os_sched_sleep(os_sched_get_current_task(), (os_time_t)osticks);
-        OS_EXIT_CRITICAL(sr);
-        os_sched(NULL);
-    }
-}
-
-/**
- * Set the time of day.  This does not modify os time, but rather just modifies
- * the offset by which we are tracking real time against os time.
- *
- * @param utctime A timeval representing the UTC time we are setting
- * @param tz The time-zone to apply against the utctime being set.
- *
- * @return 0 on success, non-zero on failure.
- */
-int
-os_settimeofday(struct os_timeval *utctime, struct os_timezone *tz)
-{
-    os_sr_t sr;
-    os_time_t delta;
-
-    OS_ENTER_CRITICAL(sr);
-    if (utctime != NULL) {
-        /*
-         * Update all time-of-day base values.
-         */
-        delta = os_time_get() - basetod.ostime;
-        os_deltatime(delta, &basetod.uptime, &basetod.uptime);
-        basetod.utctime = *utctime;
-        basetod.ostime += delta;
-    }
-
-    if (tz != NULL) {
-        basetod.timezone = *tz;
-    }
-    OS_EXIT_CRITICAL(sr);
-
-    return (0);
-}
-
-/**
- * Get the current time of day.  Returns the time of day in UTC
- * into the tv argument, and returns the timezone (if set) into
- * tz.
- *
- * @param tv The structure to put the UTC time of day into
- * @param tz The structure to put the timezone information into
- *
- * @return 0 on success, non-zero on failure
- */
-int
-os_gettimeofday(struct os_timeval *tv, struct os_timezone *tz)
-{
-    os_sr_t sr;
-    os_time_t delta;
-
-    OS_ENTER_CRITICAL(sr);
-    if (tv != NULL) {
-        delta = os_time_get() - basetod.ostime;
-        os_deltatime(delta, &basetod.utctime, tv);
-    }
-
-    if (tz != NULL) {
-        *tz = basetod.timezone;
-    }
-    OS_EXIT_CRITICAL(sr);
-
-    return (0);
-}
-
-/**
- * Get time since boot in microseconds.
- *
- * @return time since boot in microseconds
- */
-int64_t
-os_get_uptime_usec(void)
-{
-  struct os_timeval tv;
-  os_time_t delta;
-  os_sr_t sr;
-  os_time_t ostime;
-
-
-  OS_ENTER_CRITICAL(sr);
-  tv = basetod.uptime;
-  ostime = basetod.ostime;
-  delta = os_time_get() - ostime;
-  OS_EXIT_CRITICAL(sr);
-
-  os_deltatime(delta, &tv, &tv);
-
-  return(tv.tv_sec * 1000000 + tv.tv_usec);
-}
-
-/**
- * Converts milliseconds to OS ticks.
- *
- * @param ms                    The milliseconds input.
- * @param out_ticks             The OS ticks output.
- *
- * @return                      0 on success; OS_EINVAL if the result is too
- *                                  large to fit in a uint32_t.
- */
-int
-os_time_ms_to_ticks(uint32_t ms, uint32_t *out_ticks)
-{
-    uint64_t ticks;
-
-#if OS_TICKS_PER_SEC == 1000
-    *out_ticks = ms;
-    return 0;
-#endif
-
-    _Static_assert(OS_TICKS_PER_SEC <= UINT32_MAX,
-                   "OS_TICKS_PER_SEC must be <= UINT32_MAX");
-
-    ticks = (uint64_t)ms * OS_TICKS_PER_SEC / 1000;
-    if (ticks > UINT32_MAX) {
-        return OS_EINVAL;
-    }
-
-    *out_ticks = ticks;
-    return 0;
-}



[25/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/cmsis-core/src/ext/core_cm4.h
----------------------------------------------------------------------
diff --git a/libs/cmsis-core/src/ext/core_cm4.h b/libs/cmsis-core/src/ext/core_cm4.h
deleted file mode 100644
index 13db4ed..0000000
--- a/libs/cmsis-core/src/ext/core_cm4.h
+++ /dev/null
@@ -1,1772 +0,0 @@
-/**************************************************************************//**
- * @file     core_cm4.h
- * @brief    CMSIS Cortex-M4 Core Peripheral Access Layer Header File
- * @version  V3.20
- * @date     25. February 2013
- *
- * @note
- *
- ******************************************************************************/
-/* Copyright (c) 2009 - 2013 ARM LIMITED
-
-   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 ARM 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 COPYRIGHT HOLDERS AND CONTRIBUTORS BE
-   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-   POSSIBILITY OF SUCH DAMAGE.
-   ---------------------------------------------------------------------------*/
-
-
-#if defined ( __ICCARM__ )
- #pragma system_include  /* treat file as system include file for MISRA check */
-#endif
-
-#ifdef __cplusplus
- extern "C" {
-#endif
-
-#ifndef __CORE_CM4_H_GENERIC
-#define __CORE_CM4_H_GENERIC
-
-/** \page CMSIS_MISRA_Exceptions  MISRA-C:2004 Compliance Exceptions
-  CMSIS violates the following MISRA-C:2004 rules:
-
-   \li Required Rule 8.5, object/function definition in header file.<br>
-     Function definitions in header files are used to allow 'inlining'.
-
-   \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.<br>
-     Unions are used for effective representation of core registers.
-
-   \li Advisory Rule 19.7, Function-like macro defined.<br>
-     Function-like macros are used to allow more efficient code.
- */
-
-
-/*******************************************************************************
- *                 CMSIS definitions
- ******************************************************************************/
-/** \ingroup Cortex_M4
-  @{
- */
-
-/*  CMSIS CM4 definitions */
-#define __CM4_CMSIS_VERSION_MAIN  (0x03)                                   /*!< [31:16] CMSIS HAL main version   */
-#define __CM4_CMSIS_VERSION_SUB   (0x20)                                   /*!< [15:0]  CMSIS HAL sub version    */
-#define __CM4_CMSIS_VERSION       ((__CM4_CMSIS_VERSION_MAIN << 16) | \
-                                    __CM4_CMSIS_VERSION_SUB          )     /*!< CMSIS HAL version number         */
-
-#define __CORTEX_M                (0x04)                                   /*!< Cortex-M Core                    */
-
-
-#if   defined ( __CC_ARM )
-  #define __ASM            __asm                                      /*!< asm keyword for ARM Compiler          */
-  #define __INLINE         __inline                                   /*!< inline keyword for ARM Compiler       */
-  #define __STATIC_INLINE  static __inline
-
-#elif defined ( __ICCARM__ )
-  #define __ASM            __asm                                      /*!< asm keyword for IAR Compiler          */
-  #define __INLINE         inline                                     /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */
-  #define __STATIC_INLINE  static inline
-
-#elif defined ( __TMS470__ )
-  #define __ASM            __asm                                      /*!< asm keyword for TI CCS Compiler       */
-  #define __STATIC_INLINE  static inline
-
-#elif defined ( __GNUC__ )
-  #define __ASM            __asm                                      /*!< asm keyword for GNU Compiler          */
-  #define __INLINE         inline                                     /*!< inline keyword for GNU Compiler       */
-  #define __STATIC_INLINE  static inline
-
-#elif defined ( __TASKING__ )
-  #define __ASM            __asm                                      /*!< asm keyword for TASKING Compiler      */
-  #define __INLINE         inline                                     /*!< inline keyword for TASKING Compiler   */
-  #define __STATIC_INLINE  static inline
-
-#endif
-
-/** __FPU_USED indicates whether an FPU is used or not. For this, __FPU_PRESENT has to be checked prior to making use of FPU specific registers and functions.
-*/
-#if defined ( __CC_ARM )
-  #if defined __TARGET_FPU_VFP
-    #if (__FPU_PRESENT == 1)
-      #define __FPU_USED       1
-    #else
-      #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
-      #define __FPU_USED       0
-    #endif
-  #else
-    #define __FPU_USED         0
-  #endif
-
-#elif defined ( __ICCARM__ )
-  #if defined __ARMVFP__
-    #if (__FPU_PRESENT == 1)
-      #define __FPU_USED       1
-    #else
-      #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
-      #define __FPU_USED       0
-    #endif
-  #else
-    #define __FPU_USED         0
-  #endif
-
-#elif defined ( __TMS470__ )
-  #if defined __TI_VFP_SUPPORT__
-    #if (__FPU_PRESENT == 1)
-      #define __FPU_USED       1
-    #else
-      #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
-      #define __FPU_USED       0
-    #endif
-  #else
-    #define __FPU_USED         0
-  #endif
-
-#elif defined ( __GNUC__ )
-  #if defined (__VFP_FP__) && !defined(__SOFTFP__)
-    #if (__FPU_PRESENT == 1)
-      #define __FPU_USED       1
-    #else
-      #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
-      #define __FPU_USED       0
-    #endif
-  #else
-    #define __FPU_USED         0
-  #endif
-
-#elif defined ( __TASKING__ )
-  #if defined __FPU_VFP__
-    #if (__FPU_PRESENT == 1)
-      #define __FPU_USED       1
-    #else
-      #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
-      #define __FPU_USED       0
-    #endif
-  #else
-    #define __FPU_USED         0
-  #endif
-#endif
-
-#include <stdint.h>                      /* standard types definitions                      */
-#include <core_cmInstr.h>     /* Core Instruction Access                         */
-#include <core_cmFunc.h>      /* Core Function Access                            */
-#include <core_cm4_simd.h>    /* Compiler specific SIMD Intrinsics               */
-
-#endif /* __CORE_CM4_H_GENERIC */
-
-#ifndef __CMSIS_GENERIC
-
-#ifndef __CORE_CM4_H_DEPENDANT
-#define __CORE_CM4_H_DEPENDANT
-
-/* check device defines and use defaults */
-#if defined __CHECK_DEVICE_DEFINES
-  #ifndef __CM4_REV
-    #define __CM4_REV               0x0000
-    #warning "__CM4_REV not defined in device header file; using default!"
-  #endif
-
-  #ifndef __FPU_PRESENT
-    #define __FPU_PRESENT             0
-    #warning "__FPU_PRESENT not defined in device header file; using default!"
-  #endif
-
-  #ifndef __MPU_PRESENT
-    #define __MPU_PRESENT             0
-    #warning "__MPU_PRESENT not defined in device header file; using default!"
-  #endif
-
-  #ifndef __NVIC_PRIO_BITS
-    #define __NVIC_PRIO_BITS          4
-    #warning "__NVIC_PRIO_BITS not defined in device header file; using default!"
-  #endif
-
-  #ifndef __Vendor_SysTickConfig
-    #define __Vendor_SysTickConfig    0
-    #warning "__Vendor_SysTickConfig not defined in device header file; using default!"
-  #endif
-#endif
-
-/* IO definitions (access restrictions to peripheral registers) */
-/**
-    \defgroup CMSIS_glob_defs CMSIS Global Defines
-
-    <strong>IO Type Qualifiers</strong> are used
-    \li to specify the access to peripheral variables.
-    \li for automatic generation of peripheral register debug information.
-*/
-#ifdef __cplusplus
-  #define   __I     volatile             /*!< Defines 'read only' permissions                 */
-#else
-  #define   __I     volatile const       /*!< Defines 'read only' permissions                 */
-#endif
-#define     __O     volatile             /*!< Defines 'write only' permissions                */
-#define     __IO    volatile             /*!< Defines 'read / write' permissions              */
-
-/*@} end of group Cortex_M4 */
-
-
-
-/*******************************************************************************
- *                 Register Abstraction
-  Core Register contain:
-  - Core Register
-  - Core NVIC Register
-  - Core SCB Register
-  - Core SysTick Register
-  - Core Debug Register
-  - Core MPU Register
-  - Core FPU Register
- ******************************************************************************/
-/** \defgroup CMSIS_core_register Defines and Type Definitions
-    \brief Type definitions and defines for Cortex-M processor based devices.
-*/
-
-/** \ingroup    CMSIS_core_register
-    \defgroup   CMSIS_CORE  Status and Control Registers
-    \brief  Core Register type definitions.
-  @{
- */
-
-/** \brief  Union type to access the Application Program Status Register (APSR).
- */
-typedef union
-{
-  struct
-  {
-#if (__CORTEX_M != 0x04)
-    uint32_t _reserved0:27;              /*!< bit:  0..26  Reserved                           */
-#else
-    uint32_t _reserved0:16;              /*!< bit:  0..15  Reserved                           */
-    uint32_t GE:4;                       /*!< bit: 16..19  Greater than or Equal flags        */
-    uint32_t _reserved1:7;               /*!< bit: 20..26  Reserved                           */
-#endif
-    uint32_t Q:1;                        /*!< bit:     27  Saturation condition flag          */
-    uint32_t V:1;                        /*!< bit:     28  Overflow condition code flag       */
-    uint32_t C:1;                        /*!< bit:     29  Carry condition code flag          */
-    uint32_t Z:1;                        /*!< bit:     30  Zero condition code flag           */
-    uint32_t N:1;                        /*!< bit:     31  Negative condition code flag       */
-  } b;                                   /*!< Structure used for bit  access                  */
-  uint32_t w;                            /*!< Type      used for word access                  */
-} APSR_Type;
-
-
-/** \brief  Union type to access the Interrupt Program Status Register (IPSR).
- */
-typedef union
-{
-  struct
-  {
-    uint32_t ISR:9;                      /*!< bit:  0.. 8  Exception number                   */
-    uint32_t _reserved0:23;              /*!< bit:  9..31  Reserved                           */
-  } b;                                   /*!< Structure used for bit  access                  */
-  uint32_t w;                            /*!< Type      used for word access                  */
-} IPSR_Type;
-
-
-/** \brief  Union type to access the Special-Purpose Program Status Registers (xPSR).
- */
-typedef union
-{
-  struct
-  {
-    uint32_t ISR:9;                      /*!< bit:  0.. 8  Exception number                   */
-#if (__CORTEX_M != 0x04)
-    uint32_t _reserved0:15;              /*!< bit:  9..23  Reserved                           */
-#else
-    uint32_t _reserved0:7;               /*!< bit:  9..15  Reserved                           */
-    uint32_t GE:4;                       /*!< bit: 16..19  Greater than or Equal flags        */
-    uint32_t _reserved1:4;               /*!< bit: 20..23  Reserved                           */
-#endif
-    uint32_t T:1;                        /*!< bit:     24  Thumb bit        (read 0)          */
-    uint32_t IT:2;                       /*!< bit: 25..26  saved IT state   (read 0)          */
-    uint32_t Q:1;                        /*!< bit:     27  Saturation condition flag          */
-    uint32_t V:1;                        /*!< bit:     28  Overflow condition code flag       */
-    uint32_t C:1;                        /*!< bit:     29  Carry condition code flag          */
-    uint32_t Z:1;                        /*!< bit:     30  Zero condition code flag           */
-    uint32_t N:1;                        /*!< bit:     31  Negative condition code flag       */
-  } b;                                   /*!< Structure used for bit  access                  */
-  uint32_t w;                            /*!< Type      used for word access                  */
-} xPSR_Type;
-
-
-/** \brief  Union type to access the Control Registers (CONTROL).
- */
-typedef union
-{
-  struct
-  {
-    uint32_t nPRIV:1;                    /*!< bit:      0  Execution privilege in Thread mode */
-    uint32_t SPSEL:1;                    /*!< bit:      1  Stack to be used                   */
-    uint32_t FPCA:1;                     /*!< bit:      2  FP extension active flag           */
-    uint32_t _reserved0:29;              /*!< bit:  3..31  Reserved                           */
-  } b;                                   /*!< Structure used for bit  access                  */
-  uint32_t w;                            /*!< Type      used for word access                  */
-} CONTROL_Type;
-
-/*@} end of group CMSIS_CORE */
-
-
-/** \ingroup    CMSIS_core_register
-    \defgroup   CMSIS_NVIC  Nested Vectored Interrupt Controller (NVIC)
-    \brief      Type definitions for the NVIC Registers
-  @{
- */
-
-/** \brief  Structure type to access the Nested Vectored Interrupt Controller (NVIC).
- */
-typedef struct
-{
-  __IO uint32_t ISER[8];                 /*!< Offset: 0x000 (R/W)  Interrupt Set Enable Register           */
-       uint32_t RESERVED0[24];
-  __IO uint32_t ICER[8];                 /*!< Offset: 0x080 (R/W)  Interrupt Clear Enable Register         */
-       uint32_t RSERVED1[24];
-  __IO uint32_t ISPR[8];                 /*!< Offset: 0x100 (R/W)  Interrupt Set Pending Register          */
-       uint32_t RESERVED2[24];
-  __IO uint32_t ICPR[8];                 /*!< Offset: 0x180 (R/W)  Interrupt Clear Pending Register        */
-       uint32_t RESERVED3[24];
-  __IO uint32_t IABR[8];                 /*!< Offset: 0x200 (R/W)  Interrupt Active bit Register           */
-       uint32_t RESERVED4[56];
-  __IO uint8_t  IP[240];                 /*!< Offset: 0x300 (R/W)  Interrupt Priority Register (8Bit wide) */
-       uint32_t RESERVED5[644];
-  __O  uint32_t STIR;                    /*!< Offset: 0xE00 ( /W)  Software Trigger Interrupt Register     */
-}  NVIC_Type;
-
-/* Software Triggered Interrupt Register Definitions */
-#define NVIC_STIR_INTID_Pos                 0                                          /*!< STIR: INTLINESNUM Position */
-#define NVIC_STIR_INTID_Msk                (0x1FFUL << NVIC_STIR_INTID_Pos)            /*!< STIR: INTLINESNUM Mask */
-
-/*@} end of group CMSIS_NVIC */
-
-
-/** \ingroup  CMSIS_core_register
-    \defgroup CMSIS_SCB     System Control Block (SCB)
-    \brief      Type definitions for the System Control Block Registers
-  @{
- */
-
-/** \brief  Structure type to access the System Control Block (SCB).
- */
-typedef struct
-{
-  __I  uint32_t CPUID;                   /*!< Offset: 0x000 (R/ )  CPUID Base Register                                   */
-  __IO uint32_t ICSR;                    /*!< Offset: 0x004 (R/W)  Interrupt Control and State Register                  */
-  __IO uint32_t VTOR;                    /*!< Offset: 0x008 (R/W)  Vector Table Offset Register                          */
-  __IO uint32_t AIRCR;                   /*!< Offset: 0x00C (R/W)  Application Interrupt and Reset Control Register      */
-  __IO uint32_t SCR;                     /*!< Offset: 0x010 (R/W)  System Control Register                               */
-  __IO uint32_t CCR;                     /*!< Offset: 0x014 (R/W)  Configuration Control Register                        */
-  __IO uint8_t  SHP[12];                 /*!< Offset: 0x018 (R/W)  System Handlers Priority Registers (4-7, 8-11, 12-15) */
-  __IO uint32_t SHCSR;                   /*!< Offset: 0x024 (R/W)  System Handler Control and State Register             */
-  __IO uint32_t CFSR;                    /*!< Offset: 0x028 (R/W)  Configurable Fault Status Register                    */
-  __IO uint32_t HFSR;                    /*!< Offset: 0x02C (R/W)  HardFault Status Register                             */
-  __IO uint32_t DFSR;                    /*!< Offset: 0x030 (R/W)  Debug Fault Status Register                           */
-  __IO uint32_t MMFAR;                   /*!< Offset: 0x034 (R/W)  MemManage Fault Address Register                      */
-  __IO uint32_t BFAR;                    /*!< Offset: 0x038 (R/W)  BusFault Address Register                             */
-  __IO uint32_t AFSR;                    /*!< Offset: 0x03C (R/W)  Auxiliary Fault Status Register                       */
-  __I  uint32_t PFR[2];                  /*!< Offset: 0x040 (R/ )  Processor Feature Register                            */
-  __I  uint32_t DFR;                     /*!< Offset: 0x048 (R/ )  Debug Feature Register                                */
-  __I  uint32_t ADR;                     /*!< Offset: 0x04C (R/ )  Auxiliary Feature Register                            */
-  __I  uint32_t MMFR[4];                 /*!< Offset: 0x050 (R/ )  Memory Model Feature Register                         */
-  __I  uint32_t ISAR[5];                 /*!< Offset: 0x060 (R/ )  Instruction Set Attributes Register                   */
-       uint32_t RESERVED0[5];
-  __IO uint32_t CPACR;                   /*!< Offset: 0x088 (R/W)  Coprocessor Access Control Register                   */
-} SCB_Type;
-
-/* SCB CPUID Register Definitions */
-#define SCB_CPUID_IMPLEMENTER_Pos          24                                             /*!< SCB CPUID: IMPLEMENTER Position */
-#define SCB_CPUID_IMPLEMENTER_Msk          (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos)          /*!< SCB CPUID: IMPLEMENTER Mask */
-
-#define SCB_CPUID_VARIANT_Pos              20                                             /*!< SCB CPUID: VARIANT Position */
-#define SCB_CPUID_VARIANT_Msk              (0xFUL << SCB_CPUID_VARIANT_Pos)               /*!< SCB CPUID: VARIANT Mask */
-
-#define SCB_CPUID_ARCHITECTURE_Pos         16                                             /*!< SCB CPUID: ARCHITECTURE Position */
-#define SCB_CPUID_ARCHITECTURE_Msk         (0xFUL << SCB_CPUID_ARCHITECTURE_Pos)          /*!< SCB CPUID: ARCHITECTURE Mask */
-
-#define SCB_CPUID_PARTNO_Pos                4                                             /*!< SCB CPUID: PARTNO Position */
-#define SCB_CPUID_PARTNO_Msk               (0xFFFUL << SCB_CPUID_PARTNO_Pos)              /*!< SCB CPUID: PARTNO Mask */
-
-#define SCB_CPUID_REVISION_Pos              0                                             /*!< SCB CPUID: REVISION Position */
-#define SCB_CPUID_REVISION_Msk             (0xFUL << SCB_CPUID_REVISION_Pos)              /*!< SCB CPUID: REVISION Mask */
-
-/* SCB Interrupt Control State Register Definitions */
-#define SCB_ICSR_NMIPENDSET_Pos            31                                             /*!< SCB ICSR: NMIPENDSET Position */
-#define SCB_ICSR_NMIPENDSET_Msk            (1UL << SCB_ICSR_NMIPENDSET_Pos)               /*!< SCB ICSR: NMIPENDSET Mask */
-
-#define SCB_ICSR_PENDSVSET_Pos             28                                             /*!< SCB ICSR: PENDSVSET Position */
-#define SCB_ICSR_PENDSVSET_Msk             (1UL << SCB_ICSR_PENDSVSET_Pos)                /*!< SCB ICSR: PENDSVSET Mask */
-
-#define SCB_ICSR_PENDSVCLR_Pos             27                                             /*!< SCB ICSR: PENDSVCLR Position */
-#define SCB_ICSR_PENDSVCLR_Msk             (1UL << SCB_ICSR_PENDSVCLR_Pos)                /*!< SCB ICSR: PENDSVCLR Mask */
-
-#define SCB_ICSR_PENDSTSET_Pos             26                                             /*!< SCB ICSR: PENDSTSET Position */
-#define SCB_ICSR_PENDSTSET_Msk             (1UL << SCB_ICSR_PENDSTSET_Pos)                /*!< SCB ICSR: PENDSTSET Mask */
-
-#define SCB_ICSR_PENDSTCLR_Pos             25                                             /*!< SCB ICSR: PENDSTCLR Position */
-#define SCB_ICSR_PENDSTCLR_Msk             (1UL << SCB_ICSR_PENDSTCLR_Pos)                /*!< SCB ICSR: PENDSTCLR Mask */
-
-#define SCB_ICSR_ISRPREEMPT_Pos            23                                             /*!< SCB ICSR: ISRPREEMPT Position */
-#define SCB_ICSR_ISRPREEMPT_Msk            (1UL << SCB_ICSR_ISRPREEMPT_Pos)               /*!< SCB ICSR: ISRPREEMPT Mask */
-
-#define SCB_ICSR_ISRPENDING_Pos            22                                             /*!< SCB ICSR: ISRPENDING Position */
-#define SCB_ICSR_ISRPENDING_Msk            (1UL << SCB_ICSR_ISRPENDING_Pos)               /*!< SCB ICSR: ISRPENDING Mask */
-
-#define SCB_ICSR_VECTPENDING_Pos           12                                             /*!< SCB ICSR: VECTPENDING Position */
-#define SCB_ICSR_VECTPENDING_Msk           (0x1FFUL << SCB_ICSR_VECTPENDING_Pos)          /*!< SCB ICSR: VECTPENDING Mask */
-
-#define SCB_ICSR_RETTOBASE_Pos             11                                             /*!< SCB ICSR: RETTOBASE Position */
-#define SCB_ICSR_RETTOBASE_Msk             (1UL << SCB_ICSR_RETTOBASE_Pos)                /*!< SCB ICSR: RETTOBASE Mask */
-
-#define SCB_ICSR_VECTACTIVE_Pos             0                                             /*!< SCB ICSR: VECTACTIVE Position */
-#define SCB_ICSR_VECTACTIVE_Msk            (0x1FFUL << SCB_ICSR_VECTACTIVE_Pos)           /*!< SCB ICSR: VECTACTIVE Mask */
-
-/* SCB Vector Table Offset Register Definitions */
-#define SCB_VTOR_TBLOFF_Pos                 7                                             /*!< SCB VTOR: TBLOFF Position */
-#define SCB_VTOR_TBLOFF_Msk                (0x1FFFFFFUL << SCB_VTOR_TBLOFF_Pos)           /*!< SCB VTOR: TBLOFF Mask */
-
-/* SCB Application Interrupt and Reset Control Register Definitions */
-#define SCB_AIRCR_VECTKEY_Pos              16                                             /*!< SCB AIRCR: VECTKEY Position */
-#define SCB_AIRCR_VECTKEY_Msk              (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos)            /*!< SCB AIRCR: VECTKEY Mask */
-
-#define SCB_AIRCR_VECTKEYSTAT_Pos          16                                             /*!< SCB AIRCR: VECTKEYSTAT Position */
-#define SCB_AIRCR_VECTKEYSTAT_Msk          (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos)        /*!< SCB AIRCR: VECTKEYSTAT Mask */
-
-#define SCB_AIRCR_ENDIANESS_Pos            15                                             /*!< SCB AIRCR: ENDIANESS Position */
-#define SCB_AIRCR_ENDIANESS_Msk            (1UL << SCB_AIRCR_ENDIANESS_Pos)               /*!< SCB AIRCR: ENDIANESS Mask */
-
-#define SCB_AIRCR_PRIGROUP_Pos              8                                             /*!< SCB AIRCR: PRIGROUP Position */
-#define SCB_AIRCR_PRIGROUP_Msk             (7UL << SCB_AIRCR_PRIGROUP_Pos)                /*!< SCB AIRCR: PRIGROUP Mask */
-
-#define SCB_AIRCR_SYSRESETREQ_Pos           2                                             /*!< SCB AIRCR: SYSRESETREQ Position */
-#define SCB_AIRCR_SYSRESETREQ_Msk          (1UL << SCB_AIRCR_SYSRESETREQ_Pos)             /*!< SCB AIRCR: SYSRESETREQ Mask */
-
-#define SCB_AIRCR_VECTCLRACTIVE_Pos         1                                             /*!< SCB AIRCR: VECTCLRACTIVE Position */
-#define SCB_AIRCR_VECTCLRACTIVE_Msk        (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos)           /*!< SCB AIRCR: VECTCLRACTIVE Mask */
-
-#define SCB_AIRCR_VECTRESET_Pos             0                                             /*!< SCB AIRCR: VECTRESET Position */
-#define SCB_AIRCR_VECTRESET_Msk            (1UL << SCB_AIRCR_VECTRESET_Pos)               /*!< SCB AIRCR: VECTRESET Mask */
-
-/* SCB System Control Register Definitions */
-#define SCB_SCR_SEVONPEND_Pos               4                                             /*!< SCB SCR: SEVONPEND Position */
-#define SCB_SCR_SEVONPEND_Msk              (1UL << SCB_SCR_SEVONPEND_Pos)                 /*!< SCB SCR: SEVONPEND Mask */
-
-#define SCB_SCR_SLEEPDEEP_Pos               2                                             /*!< SCB SCR: SLEEPDEEP Position */
-#define SCB_SCR_SLEEPDEEP_Msk              (1UL << SCB_SCR_SLEEPDEEP_Pos)                 /*!< SCB SCR: SLEEPDEEP Mask */
-
-#define SCB_SCR_SLEEPONEXIT_Pos             1                                             /*!< SCB SCR: SLEEPONEXIT Position */
-#define SCB_SCR_SLEEPONEXIT_Msk            (1UL << SCB_SCR_SLEEPONEXIT_Pos)               /*!< SCB SCR: SLEEPONEXIT Mask */
-
-/* SCB Configuration Control Register Definitions */
-#define SCB_CCR_STKALIGN_Pos                9                                             /*!< SCB CCR: STKALIGN Position */
-#define SCB_CCR_STKALIGN_Msk               (1UL << SCB_CCR_STKALIGN_Pos)                  /*!< SCB CCR: STKALIGN Mask */
-
-#define SCB_CCR_BFHFNMIGN_Pos               8                                             /*!< SCB CCR: BFHFNMIGN Position */
-#define SCB_CCR_BFHFNMIGN_Msk              (1UL << SCB_CCR_BFHFNMIGN_Pos)                 /*!< SCB CCR: BFHFNMIGN Mask */
-
-#define SCB_CCR_DIV_0_TRP_Pos               4                                             /*!< SCB CCR: DIV_0_TRP Position */
-#define SCB_CCR_DIV_0_TRP_Msk              (1UL << SCB_CCR_DIV_0_TRP_Pos)                 /*!< SCB CCR: DIV_0_TRP Mask */
-
-#define SCB_CCR_UNALIGN_TRP_Pos             3                                             /*!< SCB CCR: UNALIGN_TRP Position */
-#define SCB_CCR_UNALIGN_TRP_Msk            (1UL << SCB_CCR_UNALIGN_TRP_Pos)               /*!< SCB CCR: UNALIGN_TRP Mask */
-
-#define SCB_CCR_USERSETMPEND_Pos            1                                             /*!< SCB CCR: USERSETMPEND Position */
-#define SCB_CCR_USERSETMPEND_Msk           (1UL << SCB_CCR_USERSETMPEND_Pos)              /*!< SCB CCR: USERSETMPEND Mask */
-
-#define SCB_CCR_NONBASETHRDENA_Pos          0                                             /*!< SCB CCR: NONBASETHRDENA Position */
-#define SCB_CCR_NONBASETHRDENA_Msk         (1UL << SCB_CCR_NONBASETHRDENA_Pos)            /*!< SCB CCR: NONBASETHRDENA Mask */
-
-/* SCB System Handler Control and State Register Definitions */
-#define SCB_SHCSR_USGFAULTENA_Pos          18                                             /*!< SCB SHCSR: USGFAULTENA Position */
-#define SCB_SHCSR_USGFAULTENA_Msk          (1UL << SCB_SHCSR_USGFAULTENA_Pos)             /*!< SCB SHCSR: USGFAULTENA Mask */
-
-#define SCB_SHCSR_BUSFAULTENA_Pos          17                                             /*!< SCB SHCSR: BUSFAULTENA Position */
-#define SCB_SHCSR_BUSFAULTENA_Msk          (1UL << SCB_SHCSR_BUSFAULTENA_Pos)             /*!< SCB SHCSR: BUSFAULTENA Mask */
-
-#define SCB_SHCSR_MEMFAULTENA_Pos          16                                             /*!< SCB SHCSR: MEMFAULTENA Position */
-#define SCB_SHCSR_MEMFAULTENA_Msk          (1UL << SCB_SHCSR_MEMFAULTENA_Pos)             /*!< SCB SHCSR: MEMFAULTENA Mask */
-
-#define SCB_SHCSR_SVCALLPENDED_Pos         15                                             /*!< SCB SHCSR: SVCALLPENDED Position */
-#define SCB_SHCSR_SVCALLPENDED_Msk         (1UL << SCB_SHCSR_SVCALLPENDED_Pos)            /*!< SCB SHCSR: SVCALLPENDED Mask */
-
-#define SCB_SHCSR_BUSFAULTPENDED_Pos       14                                             /*!< SCB SHCSR: BUSFAULTPENDED Position */
-#define SCB_SHCSR_BUSFAULTPENDED_Msk       (1UL << SCB_SHCSR_BUSFAULTPENDED_Pos)          /*!< SCB SHCSR: BUSFAULTPENDED Mask */
-
-#define SCB_SHCSR_MEMFAULTPENDED_Pos       13                                             /*!< SCB SHCSR: MEMFAULTPENDED Position */
-#define SCB_SHCSR_MEMFAULTPENDED_Msk       (1UL << SCB_SHCSR_MEMFAULTPENDED_Pos)          /*!< SCB SHCSR: MEMFAULTPENDED Mask */
-
-#define SCB_SHCSR_USGFAULTPENDED_Pos       12                                             /*!< SCB SHCSR: USGFAULTPENDED Position */
-#define SCB_SHCSR_USGFAULTPENDED_Msk       (1UL << SCB_SHCSR_USGFAULTPENDED_Pos)          /*!< SCB SHCSR: USGFAULTPENDED Mask */
-
-#define SCB_SHCSR_SYSTICKACT_Pos           11                                             /*!< SCB SHCSR: SYSTICKACT Position */
-#define SCB_SHCSR_SYSTICKACT_Msk           (1UL << SCB_SHCSR_SYSTICKACT_Pos)              /*!< SCB SHCSR: SYSTICKACT Mask */
-
-#define SCB_SHCSR_PENDSVACT_Pos            10                                             /*!< SCB SHCSR: PENDSVACT Position */
-#define SCB_SHCSR_PENDSVACT_Msk            (1UL << SCB_SHCSR_PENDSVACT_Pos)               /*!< SCB SHCSR: PENDSVACT Mask */
-
-#define SCB_SHCSR_MONITORACT_Pos            8                                             /*!< SCB SHCSR: MONITORACT Position */
-#define SCB_SHCSR_MONITORACT_Msk           (1UL << SCB_SHCSR_MONITORACT_Pos)              /*!< SCB SHCSR: MONITORACT Mask */
-
-#define SCB_SHCSR_SVCALLACT_Pos             7                                             /*!< SCB SHCSR: SVCALLACT Position */
-#define SCB_SHCSR_SVCALLACT_Msk            (1UL << SCB_SHCSR_SVCALLACT_Pos)               /*!< SCB SHCSR: SVCALLACT Mask */
-
-#define SCB_SHCSR_USGFAULTACT_Pos           3                                             /*!< SCB SHCSR: USGFAULTACT Position */
-#define SCB_SHCSR_USGFAULTACT_Msk          (1UL << SCB_SHCSR_USGFAULTACT_Pos)             /*!< SCB SHCSR: USGFAULTACT Mask */
-
-#define SCB_SHCSR_BUSFAULTACT_Pos           1                                             /*!< SCB SHCSR: BUSFAULTACT Position */
-#define SCB_SHCSR_BUSFAULTACT_Msk          (1UL << SCB_SHCSR_BUSFAULTACT_Pos)             /*!< SCB SHCSR: BUSFAULTACT Mask */
-
-#define SCB_SHCSR_MEMFAULTACT_Pos           0                                             /*!< SCB SHCSR: MEMFAULTACT Position */
-#define SCB_SHCSR_MEMFAULTACT_Msk          (1UL << SCB_SHCSR_MEMFAULTACT_Pos)             /*!< SCB SHCSR: MEMFAULTACT Mask */
-
-/* SCB Configurable Fault Status Registers Definitions */
-#define SCB_CFSR_USGFAULTSR_Pos            16                                             /*!< SCB CFSR: Usage Fault Status Register Position */
-#define SCB_CFSR_USGFAULTSR_Msk            (0xFFFFUL << SCB_CFSR_USGFAULTSR_Pos)          /*!< SCB CFSR: Usage Fault Status Register Mask */
-
-#define SCB_CFSR_BUSFAULTSR_Pos             8                                             /*!< SCB CFSR: Bus Fault Status Register Position */
-#define SCB_CFSR_BUSFAULTSR_Msk            (0xFFUL << SCB_CFSR_BUSFAULTSR_Pos)            /*!< SCB CFSR: Bus Fault Status Register Mask */
-
-#define SCB_CFSR_MEMFAULTSR_Pos             0                                             /*!< SCB CFSR: Memory Manage Fault Status Register Position */
-#define SCB_CFSR_MEMFAULTSR_Msk            (0xFFUL << SCB_CFSR_MEMFAULTSR_Pos)            /*!< SCB CFSR: Memory Manage Fault Status Register Mask */
-
-/* SCB Hard Fault Status Registers Definitions */
-#define SCB_HFSR_DEBUGEVT_Pos              31                                             /*!< SCB HFSR: DEBUGEVT Position */
-#define SCB_HFSR_DEBUGEVT_Msk              (1UL << SCB_HFSR_DEBUGEVT_Pos)                 /*!< SCB HFSR: DEBUGEVT Mask */
-
-#define SCB_HFSR_FORCED_Pos                30                                             /*!< SCB HFSR: FORCED Position */
-#define SCB_HFSR_FORCED_Msk                (1UL << SCB_HFSR_FORCED_Pos)                   /*!< SCB HFSR: FORCED Mask */
-
-#define SCB_HFSR_VECTTBL_Pos                1                                             /*!< SCB HFSR: VECTTBL Position */
-#define SCB_HFSR_VECTTBL_Msk               (1UL << SCB_HFSR_VECTTBL_Pos)                  /*!< SCB HFSR: VECTTBL Mask */
-
-/* SCB Debug Fault Status Register Definitions */
-#define SCB_DFSR_EXTERNAL_Pos               4                                             /*!< SCB DFSR: EXTERNAL Position */
-#define SCB_DFSR_EXTERNAL_Msk              (1UL << SCB_DFSR_EXTERNAL_Pos)                 /*!< SCB DFSR: EXTERNAL Mask */
-
-#define SCB_DFSR_VCATCH_Pos                 3                                             /*!< SCB DFSR: VCATCH Position */
-#define SCB_DFSR_VCATCH_Msk                (1UL << SCB_DFSR_VCATCH_Pos)                   /*!< SCB DFSR: VCATCH Mask */
-
-#define SCB_DFSR_DWTTRAP_Pos                2                                             /*!< SCB DFSR: DWTTRAP Position */
-#define SCB_DFSR_DWTTRAP_Msk               (1UL << SCB_DFSR_DWTTRAP_Pos)                  /*!< SCB DFSR: DWTTRAP Mask */
-
-#define SCB_DFSR_BKPT_Pos                   1                                             /*!< SCB DFSR: BKPT Position */
-#define SCB_DFSR_BKPT_Msk                  (1UL << SCB_DFSR_BKPT_Pos)                     /*!< SCB DFSR: BKPT Mask */
-
-#define SCB_DFSR_HALTED_Pos                 0                                             /*!< SCB DFSR: HALTED Position */
-#define SCB_DFSR_HALTED_Msk                (1UL << SCB_DFSR_HALTED_Pos)                   /*!< SCB DFSR: HALTED Mask */
-
-/*@} end of group CMSIS_SCB */
-
-
-/** \ingroup  CMSIS_core_register
-    \defgroup CMSIS_SCnSCB System Controls not in SCB (SCnSCB)
-    \brief      Type definitions for the System Control and ID Register not in the SCB
-  @{
- */
-
-/** \brief  Structure type to access the System Control and ID Register not in the SCB.
- */
-typedef struct
-{
-       uint32_t RESERVED0[1];
-  __I  uint32_t ICTR;                    /*!< Offset: 0x004 (R/ )  Interrupt Controller Type Register      */
-  __IO uint32_t ACTLR;                   /*!< Offset: 0x008 (R/W)  Auxiliary Control Register              */
-} SCnSCB_Type;
-
-/* Interrupt Controller Type Register Definitions */
-#define SCnSCB_ICTR_INTLINESNUM_Pos         0                                          /*!< ICTR: INTLINESNUM Position */
-#define SCnSCB_ICTR_INTLINESNUM_Msk        (0xFUL << SCnSCB_ICTR_INTLINESNUM_Pos)      /*!< ICTR: INTLINESNUM Mask */
-
-/* Auxiliary Control Register Definitions */
-#define SCnSCB_ACTLR_DISOOFP_Pos            9                                          /*!< ACTLR: DISOOFP Position */
-#define SCnSCB_ACTLR_DISOOFP_Msk           (1UL << SCnSCB_ACTLR_DISOOFP_Pos)           /*!< ACTLR: DISOOFP Mask */
-
-#define SCnSCB_ACTLR_DISFPCA_Pos            8                                          /*!< ACTLR: DISFPCA Position */
-#define SCnSCB_ACTLR_DISFPCA_Msk           (1UL << SCnSCB_ACTLR_DISFPCA_Pos)           /*!< ACTLR: DISFPCA Mask */
-
-#define SCnSCB_ACTLR_DISFOLD_Pos            2                                          /*!< ACTLR: DISFOLD Position */
-#define SCnSCB_ACTLR_DISFOLD_Msk           (1UL << SCnSCB_ACTLR_DISFOLD_Pos)           /*!< ACTLR: DISFOLD Mask */
-
-#define SCnSCB_ACTLR_DISDEFWBUF_Pos         1                                          /*!< ACTLR: DISDEFWBUF Position */
-#define SCnSCB_ACTLR_DISDEFWBUF_Msk        (1UL << SCnSCB_ACTLR_DISDEFWBUF_Pos)        /*!< ACTLR: DISDEFWBUF Mask */
-
-#define SCnSCB_ACTLR_DISMCYCINT_Pos         0                                          /*!< ACTLR: DISMCYCINT Position */
-#define SCnSCB_ACTLR_DISMCYCINT_Msk        (1UL << SCnSCB_ACTLR_DISMCYCINT_Pos)        /*!< ACTLR: DISMCYCINT Mask */
-
-/*@} end of group CMSIS_SCnotSCB */
-
-
-/** \ingroup  CMSIS_core_register
-    \defgroup CMSIS_SysTick     System Tick Timer (SysTick)
-    \brief      Type definitions for the System Timer Registers.
-  @{
- */
-
-/** \brief  Structure type to access the System Timer (SysTick).
- */
-typedef struct
-{
-  __IO uint32_t CTRL;                    /*!< Offset: 0x000 (R/W)  SysTick Control and Status Register */
-  __IO uint32_t LOAD;                    /*!< Offset: 0x004 (R/W)  SysTick Reload Value Register       */
-  __IO uint32_t VAL;                     /*!< Offset: 0x008 (R/W)  SysTick Current Value Register      */
-  __I  uint32_t CALIB;                   /*!< Offset: 0x00C (R/ )  SysTick Calibration Register        */
-} SysTick_Type;
-
-/* SysTick Control / Status Register Definitions */
-#define SysTick_CTRL_COUNTFLAG_Pos         16                                             /*!< SysTick CTRL: COUNTFLAG Position */
-#define SysTick_CTRL_COUNTFLAG_Msk         (1UL << SysTick_CTRL_COUNTFLAG_Pos)            /*!< SysTick CTRL: COUNTFLAG Mask */
-
-#define SysTick_CTRL_CLKSOURCE_Pos          2                                             /*!< SysTick CTRL: CLKSOURCE Position */
-#define SysTick_CTRL_CLKSOURCE_Msk         (1UL << SysTick_CTRL_CLKSOURCE_Pos)            /*!< SysTick CTRL: CLKSOURCE Mask */
-
-#define SysTick_CTRL_TICKINT_Pos            1                                             /*!< SysTick CTRL: TICKINT Position */
-#define SysTick_CTRL_TICKINT_Msk           (1UL << SysTick_CTRL_TICKINT_Pos)              /*!< SysTick CTRL: TICKINT Mask */
-
-#define SysTick_CTRL_ENABLE_Pos             0                                             /*!< SysTick CTRL: ENABLE Position */
-#define SysTick_CTRL_ENABLE_Msk            (1UL << SysTick_CTRL_ENABLE_Pos)               /*!< SysTick CTRL: ENABLE Mask */
-
-/* SysTick Reload Register Definitions */
-#define SysTick_LOAD_RELOAD_Pos             0                                             /*!< SysTick LOAD: RELOAD Position */
-#define SysTick_LOAD_RELOAD_Msk            (0xFFFFFFUL << SysTick_LOAD_RELOAD_Pos)        /*!< SysTick LOAD: RELOAD Mask */
-
-/* SysTick Current Register Definitions */
-#define SysTick_VAL_CURRENT_Pos             0                                             /*!< SysTick VAL: CURRENT Position */
-#define SysTick_VAL_CURRENT_Msk            (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos)        /*!< SysTick VAL: CURRENT Mask */
-
-/* SysTick Calibration Register Definitions */
-#define SysTick_CALIB_NOREF_Pos            31                                             /*!< SysTick CALIB: NOREF Position */
-#define SysTick_CALIB_NOREF_Msk            (1UL << SysTick_CALIB_NOREF_Pos)               /*!< SysTick CALIB: NOREF Mask */
-
-#define SysTick_CALIB_SKEW_Pos             30                                             /*!< SysTick CALIB: SKEW Position */
-#define SysTick_CALIB_SKEW_Msk             (1UL << SysTick_CALIB_SKEW_Pos)                /*!< SysTick CALIB: SKEW Mask */
-
-#define SysTick_CALIB_TENMS_Pos             0                                             /*!< SysTick CALIB: TENMS Position */
-#define SysTick_CALIB_TENMS_Msk            (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos)        /*!< SysTick CALIB: TENMS Mask */
-
-/*@} end of group CMSIS_SysTick */
-
-
-/** \ingroup  CMSIS_core_register
-    \defgroup CMSIS_ITM     Instrumentation Trace Macrocell (ITM)
-    \brief      Type definitions for the Instrumentation Trace Macrocell (ITM)
-  @{
- */
-
-/** \brief  Structure type to access the Instrumentation Trace Macrocell Register (ITM).
- */
-typedef struct
-{
-  __O  union
-  {
-    __O  uint8_t    u8;                  /*!< Offset: 0x000 ( /W)  ITM Stimulus Port 8-bit                   */
-    __O  uint16_t   u16;                 /*!< Offset: 0x000 ( /W)  ITM Stimulus Port 16-bit                  */
-    __O  uint32_t   u32;                 /*!< Offset: 0x000 ( /W)  ITM Stimulus Port 32-bit                  */
-  }  PORT [32];                          /*!< Offset: 0x000 ( /W)  ITM Stimulus Port Registers               */
-       uint32_t RESERVED0[864];
-  __IO uint32_t TER;                     /*!< Offset: 0xE00 (R/W)  ITM Trace Enable Register                 */
-       uint32_t RESERVED1[15];
-  __IO uint32_t TPR;                     /*!< Offset: 0xE40 (R/W)  ITM Trace Privilege Register              */
-       uint32_t RESERVED2[15];
-  __IO uint32_t TCR;                     /*!< Offset: 0xE80 (R/W)  ITM Trace Control Register                */
-       uint32_t RESERVED3[29];
-  __O  uint32_t IWR;                     /*!< Offset: 0xEF8 ( /W)  ITM Integration Write Register            */
-  __I  uint32_t IRR;                     /*!< Offset: 0xEFC (R/ )  ITM Integration Read Register             */
-  __IO uint32_t IMCR;                    /*!< Offset: 0xF00 (R/W)  ITM Integration Mode Control Register     */
-       uint32_t RESERVED4[43];
-  __O  uint32_t LAR;                     /*!< Offset: 0xFB0 ( /W)  ITM Lock Access Register                  */
-  __I  uint32_t LSR;                     /*!< Offset: 0xFB4 (R/ )  ITM Lock Status Register                  */
-       uint32_t RESERVED5[6];
-  __I  uint32_t PID4;                    /*!< Offset: 0xFD0 (R/ )  ITM Peripheral Identification Register #4 */
-  __I  uint32_t PID5;                    /*!< Offset: 0xFD4 (R/ )  ITM Peripheral Identification Register #5 */
-  __I  uint32_t PID6;                    /*!< Offset: 0xFD8 (R/ )  ITM Peripheral Identification Register #6 */
-  __I  uint32_t PID7;                    /*!< Offset: 0xFDC (R/ )  ITM Peripheral Identification Register #7 */
-  __I  uint32_t PID0;                    /*!< Offset: 0xFE0 (R/ )  ITM Peripheral Identification Register #0 */
-  __I  uint32_t PID1;                    /*!< Offset: 0xFE4 (R/ )  ITM Peripheral Identification Register #1 */
-  __I  uint32_t PID2;                    /*!< Offset: 0xFE8 (R/ )  ITM Peripheral Identification Register #2 */
-  __I  uint32_t PID3;                    /*!< Offset: 0xFEC (R/ )  ITM Peripheral Identification Register #3 */
-  __I  uint32_t CID0;                    /*!< Offset: 0xFF0 (R/ )  ITM Component  Identification Register #0 */
-  __I  uint32_t CID1;                    /*!< Offset: 0xFF4 (R/ )  ITM Component  Identification Register #1 */
-  __I  uint32_t CID2;                    /*!< Offset: 0xFF8 (R/ )  ITM Component  Identification Register #2 */
-  __I  uint32_t CID3;                    /*!< Offset: 0xFFC (R/ )  ITM Component  Identification Register #3 */
-} ITM_Type;
-
-/* ITM Trace Privilege Register Definitions */
-#define ITM_TPR_PRIVMASK_Pos                0                                             /*!< ITM TPR: PRIVMASK Position */
-#define ITM_TPR_PRIVMASK_Msk               (0xFUL << ITM_TPR_PRIVMASK_Pos)                /*!< ITM TPR: PRIVMASK Mask */
-
-/* ITM Trace Control Register Definitions */
-#define ITM_TCR_BUSY_Pos                   23                                             /*!< ITM TCR: BUSY Position */
-#define ITM_TCR_BUSY_Msk                   (1UL << ITM_TCR_BUSY_Pos)                      /*!< ITM TCR: BUSY Mask */
-
-#define ITM_TCR_TraceBusID_Pos             16                                             /*!< ITM TCR: ATBID Position */
-#define ITM_TCR_TraceBusID_Msk             (0x7FUL << ITM_TCR_TraceBusID_Pos)             /*!< ITM TCR: ATBID Mask */
-
-#define ITM_TCR_GTSFREQ_Pos                10                                             /*!< ITM TCR: Global timestamp frequency Position */
-#define ITM_TCR_GTSFREQ_Msk                (3UL << ITM_TCR_GTSFREQ_Pos)                   /*!< ITM TCR: Global timestamp frequency Mask */
-
-#define ITM_TCR_TSPrescale_Pos              8                                             /*!< ITM TCR: TSPrescale Position */
-#define ITM_TCR_TSPrescale_Msk             (3UL << ITM_TCR_TSPrescale_Pos)                /*!< ITM TCR: TSPrescale Mask */
-
-#define ITM_TCR_SWOENA_Pos                  4                                             /*!< ITM TCR: SWOENA Position */
-#define ITM_TCR_SWOENA_Msk                 (1UL << ITM_TCR_SWOENA_Pos)                    /*!< ITM TCR: SWOENA Mask */
-
-#define ITM_TCR_DWTENA_Pos                  3                                             /*!< ITM TCR: DWTENA Position */
-#define ITM_TCR_DWTENA_Msk                 (1UL << ITM_TCR_DWTENA_Pos)                    /*!< ITM TCR: DWTENA Mask */
-
-#define ITM_TCR_SYNCENA_Pos                 2                                             /*!< ITM TCR: SYNCENA Position */
-#define ITM_TCR_SYNCENA_Msk                (1UL << ITM_TCR_SYNCENA_Pos)                   /*!< ITM TCR: SYNCENA Mask */
-
-#define ITM_TCR_TSENA_Pos                   1                                             /*!< ITM TCR: TSENA Position */
-#define ITM_TCR_TSENA_Msk                  (1UL << ITM_TCR_TSENA_Pos)                     /*!< ITM TCR: TSENA Mask */
-
-#define ITM_TCR_ITMENA_Pos                  0                                             /*!< ITM TCR: ITM Enable bit Position */
-#define ITM_TCR_ITMENA_Msk                 (1UL << ITM_TCR_ITMENA_Pos)                    /*!< ITM TCR: ITM Enable bit Mask */
-
-/* ITM Integration Write Register Definitions */
-#define ITM_IWR_ATVALIDM_Pos                0                                             /*!< ITM IWR: ATVALIDM Position */
-#define ITM_IWR_ATVALIDM_Msk               (1UL << ITM_IWR_ATVALIDM_Pos)                  /*!< ITM IWR: ATVALIDM Mask */
-
-/* ITM Integration Read Register Definitions */
-#define ITM_IRR_ATREADYM_Pos                0                                             /*!< ITM IRR: ATREADYM Position */
-#define ITM_IRR_ATREADYM_Msk               (1UL << ITM_IRR_ATREADYM_Pos)                  /*!< ITM IRR: ATREADYM Mask */
-
-/* ITM Integration Mode Control Register Definitions */
-#define ITM_IMCR_INTEGRATION_Pos            0                                             /*!< ITM IMCR: INTEGRATION Position */
-#define ITM_IMCR_INTEGRATION_Msk           (1UL << ITM_IMCR_INTEGRATION_Pos)              /*!< ITM IMCR: INTEGRATION Mask */
-
-/* ITM Lock Status Register Definitions */
-#define ITM_LSR_ByteAcc_Pos                 2                                             /*!< ITM LSR: ByteAcc Position */
-#define ITM_LSR_ByteAcc_Msk                (1UL << ITM_LSR_ByteAcc_Pos)                   /*!< ITM LSR: ByteAcc Mask */
-
-#define ITM_LSR_Access_Pos                  1                                             /*!< ITM LSR: Access Position */
-#define ITM_LSR_Access_Msk                 (1UL << ITM_LSR_Access_Pos)                    /*!< ITM LSR: Access Mask */
-
-#define ITM_LSR_Present_Pos                 0                                             /*!< ITM LSR: Present Position */
-#define ITM_LSR_Present_Msk                (1UL << ITM_LSR_Present_Pos)                   /*!< ITM LSR: Present Mask */
-
-/*@}*/ /* end of group CMSIS_ITM */
-
-
-/** \ingroup  CMSIS_core_register
-    \defgroup CMSIS_DWT     Data Watchpoint and Trace (DWT)
-    \brief      Type definitions for the Data Watchpoint and Trace (DWT)
-  @{
- */
-
-/** \brief  Structure type to access the Data Watchpoint and Trace Register (DWT).
- */
-typedef struct
-{
-  __IO uint32_t CTRL;                    /*!< Offset: 0x000 (R/W)  Control Register                          */
-  __IO uint32_t CYCCNT;                  /*!< Offset: 0x004 (R/W)  Cycle Count Register                      */
-  __IO uint32_t CPICNT;                  /*!< Offset: 0x008 (R/W)  CPI Count Register                        */
-  __IO uint32_t EXCCNT;                  /*!< Offset: 0x00C (R/W)  Exception Overhead Count Register         */
-  __IO uint32_t SLEEPCNT;                /*!< Offset: 0x010 (R/W)  Sleep Count Register                      */
-  __IO uint32_t LSUCNT;                  /*!< Offset: 0x014 (R/W)  LSU Count Register                        */
-  __IO uint32_t FOLDCNT;                 /*!< Offset: 0x018 (R/W)  Folded-instruction Count Register         */
-  __I  uint32_t PCSR;                    /*!< Offset: 0x01C (R/ )  Program Counter Sample Register           */
-  __IO uint32_t COMP0;                   /*!< Offset: 0x020 (R/W)  Comparator Register 0                     */
-  __IO uint32_t MASK0;                   /*!< Offset: 0x024 (R/W)  Mask Register 0                           */
-  __IO uint32_t FUNCTION0;               /*!< Offset: 0x028 (R/W)  Function Register 0                       */
-       uint32_t RESERVED0[1];
-  __IO uint32_t COMP1;                   /*!< Offset: 0x030 (R/W)  Comparator Register 1                     */
-  __IO uint32_t MASK1;                   /*!< Offset: 0x034 (R/W)  Mask Register 1                           */
-  __IO uint32_t FUNCTION1;               /*!< Offset: 0x038 (R/W)  Function Register 1                       */
-       uint32_t RESERVED1[1];
-  __IO uint32_t COMP2;                   /*!< Offset: 0x040 (R/W)  Comparator Register 2                     */
-  __IO uint32_t MASK2;                   /*!< Offset: 0x044 (R/W)  Mask Register 2                           */
-  __IO uint32_t FUNCTION2;               /*!< Offset: 0x048 (R/W)  Function Register 2                       */
-       uint32_t RESERVED2[1];
-  __IO uint32_t COMP3;                   /*!< Offset: 0x050 (R/W)  Comparator Register 3                     */
-  __IO uint32_t MASK3;                   /*!< Offset: 0x054 (R/W)  Mask Register 3                           */
-  __IO uint32_t FUNCTION3;               /*!< Offset: 0x058 (R/W)  Function Register 3                       */
-} DWT_Type;
-
-/* DWT Control Register Definitions */
-#define DWT_CTRL_NUMCOMP_Pos               28                                          /*!< DWT CTRL: NUMCOMP Position */
-#define DWT_CTRL_NUMCOMP_Msk               (0xFUL << DWT_CTRL_NUMCOMP_Pos)             /*!< DWT CTRL: NUMCOMP Mask */
-
-#define DWT_CTRL_NOTRCPKT_Pos              27                                          /*!< DWT CTRL: NOTRCPKT Position */
-#define DWT_CTRL_NOTRCPKT_Msk              (0x1UL << DWT_CTRL_NOTRCPKT_Pos)            /*!< DWT CTRL: NOTRCPKT Mask */
-
-#define DWT_CTRL_NOEXTTRIG_Pos             26                                          /*!< DWT CTRL: NOEXTTRIG Position */
-#define DWT_CTRL_NOEXTTRIG_Msk             (0x1UL << DWT_CTRL_NOEXTTRIG_Pos)           /*!< DWT CTRL: NOEXTTRIG Mask */
-
-#define DWT_CTRL_NOCYCCNT_Pos              25                                          /*!< DWT CTRL: NOCYCCNT Position */
-#define DWT_CTRL_NOCYCCNT_Msk              (0x1UL << DWT_CTRL_NOCYCCNT_Pos)            /*!< DWT CTRL: NOCYCCNT Mask */
-
-#define DWT_CTRL_NOPRFCNT_Pos              24                                          /*!< DWT CTRL: NOPRFCNT Position */
-#define DWT_CTRL_NOPRFCNT_Msk              (0x1UL << DWT_CTRL_NOPRFCNT_Pos)            /*!< DWT CTRL: NOPRFCNT Mask */
-
-#define DWT_CTRL_CYCEVTENA_Pos             22                                          /*!< DWT CTRL: CYCEVTENA Position */
-#define DWT_CTRL_CYCEVTENA_Msk             (0x1UL << DWT_CTRL_CYCEVTENA_Pos)           /*!< DWT CTRL: CYCEVTENA Mask */
-
-#define DWT_CTRL_FOLDEVTENA_Pos            21                                          /*!< DWT CTRL: FOLDEVTENA Position */
-#define DWT_CTRL_FOLDEVTENA_Msk            (0x1UL << DWT_CTRL_FOLDEVTENA_Pos)          /*!< DWT CTRL: FOLDEVTENA Mask */
-
-#define DWT_CTRL_LSUEVTENA_Pos             20                                          /*!< DWT CTRL: LSUEVTENA Position */
-#define DWT_CTRL_LSUEVTENA_Msk             (0x1UL << DWT_CTRL_LSUEVTENA_Pos)           /*!< DWT CTRL: LSUEVTENA Mask */
-
-#define DWT_CTRL_SLEEPEVTENA_Pos           19                                          /*!< DWT CTRL: SLEEPEVTENA Position */
-#define DWT_CTRL_SLEEPEVTENA_Msk           (0x1UL << DWT_CTRL_SLEEPEVTENA_Pos)         /*!< DWT CTRL: SLEEPEVTENA Mask */
-
-#define DWT_CTRL_EXCEVTENA_Pos             18                                          /*!< DWT CTRL: EXCEVTENA Position */
-#define DWT_CTRL_EXCEVTENA_Msk             (0x1UL << DWT_CTRL_EXCEVTENA_Pos)           /*!< DWT CTRL: EXCEVTENA Mask */
-
-#define DWT_CTRL_CPIEVTENA_Pos             17                                          /*!< DWT CTRL: CPIEVTENA Position */
-#define DWT_CTRL_CPIEVTENA_Msk             (0x1UL << DWT_CTRL_CPIEVTENA_Pos)           /*!< DWT CTRL: CPIEVTENA Mask */
-
-#define DWT_CTRL_EXCTRCENA_Pos             16                                          /*!< DWT CTRL: EXCTRCENA Position */
-#define DWT_CTRL_EXCTRCENA_Msk             (0x1UL << DWT_CTRL_EXCTRCENA_Pos)           /*!< DWT CTRL: EXCTRCENA Mask */
-
-#define DWT_CTRL_PCSAMPLENA_Pos            12                                          /*!< DWT CTRL: PCSAMPLENA Position */
-#define DWT_CTRL_PCSAMPLENA_Msk            (0x1UL << DWT_CTRL_PCSAMPLENA_Pos)          /*!< DWT CTRL: PCSAMPLENA Mask */
-
-#define DWT_CTRL_SYNCTAP_Pos               10                                          /*!< DWT CTRL: SYNCTAP Position */
-#define DWT_CTRL_SYNCTAP_Msk               (0x3UL << DWT_CTRL_SYNCTAP_Pos)             /*!< DWT CTRL: SYNCTAP Mask */
-
-#define DWT_CTRL_CYCTAP_Pos                 9                                          /*!< DWT CTRL: CYCTAP Position */
-#define DWT_CTRL_CYCTAP_Msk                (0x1UL << DWT_CTRL_CYCTAP_Pos)              /*!< DWT CTRL: CYCTAP Mask */
-
-#define DWT_CTRL_POSTINIT_Pos               5                                          /*!< DWT CTRL: POSTINIT Position */
-#define DWT_CTRL_POSTINIT_Msk              (0xFUL << DWT_CTRL_POSTINIT_Pos)            /*!< DWT CTRL: POSTINIT Mask */
-
-#define DWT_CTRL_POSTPRESET_Pos             1                                          /*!< DWT CTRL: POSTPRESET Position */
-#define DWT_CTRL_POSTPRESET_Msk            (0xFUL << DWT_CTRL_POSTPRESET_Pos)          /*!< DWT CTRL: POSTPRESET Mask */
-
-#define DWT_CTRL_CYCCNTENA_Pos              0                                          /*!< DWT CTRL: CYCCNTENA Position */
-#define DWT_CTRL_CYCCNTENA_Msk             (0x1UL << DWT_CTRL_CYCCNTENA_Pos)           /*!< DWT CTRL: CYCCNTENA Mask */
-
-/* DWT CPI Count Register Definitions */
-#define DWT_CPICNT_CPICNT_Pos               0                                          /*!< DWT CPICNT: CPICNT Position */
-#define DWT_CPICNT_CPICNT_Msk              (0xFFUL << DWT_CPICNT_CPICNT_Pos)           /*!< DWT CPICNT: CPICNT Mask */
-
-/* DWT Exception Overhead Count Register Definitions */
-#define DWT_EXCCNT_EXCCNT_Pos               0                                          /*!< DWT EXCCNT: EXCCNT Position */
-#define DWT_EXCCNT_EXCCNT_Msk              (0xFFUL << DWT_EXCCNT_EXCCNT_Pos)           /*!< DWT EXCCNT: EXCCNT Mask */
-
-/* DWT Sleep Count Register Definitions */
-#define DWT_SLEEPCNT_SLEEPCNT_Pos           0                                          /*!< DWT SLEEPCNT: SLEEPCNT Position */
-#define DWT_SLEEPCNT_SLEEPCNT_Msk          (0xFFUL << DWT_SLEEPCNT_SLEEPCNT_Pos)       /*!< DWT SLEEPCNT: SLEEPCNT Mask */
-
-/* DWT LSU Count Register Definitions */
-#define DWT_LSUCNT_LSUCNT_Pos               0                                          /*!< DWT LSUCNT: LSUCNT Position */
-#define DWT_LSUCNT_LSUCNT_Msk              (0xFFUL << DWT_LSUCNT_LSUCNT_Pos)           /*!< DWT LSUCNT: LSUCNT Mask */
-
-/* DWT Folded-instruction Count Register Definitions */
-#define DWT_FOLDCNT_FOLDCNT_Pos             0                                          /*!< DWT FOLDCNT: FOLDCNT Position */
-#define DWT_FOLDCNT_FOLDCNT_Msk            (0xFFUL << DWT_FOLDCNT_FOLDCNT_Pos)         /*!< DWT FOLDCNT: FOLDCNT Mask */
-
-/* DWT Comparator Mask Register Definitions */
-#define DWT_MASK_MASK_Pos                   0                                          /*!< DWT MASK: MASK Position */
-#define DWT_MASK_MASK_Msk                  (0x1FUL << DWT_MASK_MASK_Pos)               /*!< DWT MASK: MASK Mask */
-
-/* DWT Comparator Function Register Definitions */
-#define DWT_FUNCTION_MATCHED_Pos           24                                          /*!< DWT FUNCTION: MATCHED Position */
-#define DWT_FUNCTION_MATCHED_Msk           (0x1UL << DWT_FUNCTION_MATCHED_Pos)         /*!< DWT FUNCTION: MATCHED Mask */
-
-#define DWT_FUNCTION_DATAVADDR1_Pos        16                                          /*!< DWT FUNCTION: DATAVADDR1 Position */
-#define DWT_FUNCTION_DATAVADDR1_Msk        (0xFUL << DWT_FUNCTION_DATAVADDR1_Pos)      /*!< DWT FUNCTION: DATAVADDR1 Mask */
-
-#define DWT_FUNCTION_DATAVADDR0_Pos        12                                          /*!< DWT FUNCTION: DATAVADDR0 Position */
-#define DWT_FUNCTION_DATAVADDR0_Msk        (0xFUL << DWT_FUNCTION_DATAVADDR0_Pos)      /*!< DWT FUNCTION: DATAVADDR0 Mask */
-
-#define DWT_FUNCTION_DATAVSIZE_Pos         10                                          /*!< DWT FUNCTION: DATAVSIZE Position */
-#define DWT_FUNCTION_DATAVSIZE_Msk         (0x3UL << DWT_FUNCTION_DATAVSIZE_Pos)       /*!< DWT FUNCTION: DATAVSIZE Mask */
-
-#define DWT_FUNCTION_LNK1ENA_Pos            9                                          /*!< DWT FUNCTION: LNK1ENA Position */
-#define DWT_FUNCTION_LNK1ENA_Msk           (0x1UL << DWT_FUNCTION_LNK1ENA_Pos)         /*!< DWT FUNCTION: LNK1ENA Mask */
-
-#define DWT_FUNCTION_DATAVMATCH_Pos         8                                          /*!< DWT FUNCTION: DATAVMATCH Position */
-#define DWT_FUNCTION_DATAVMATCH_Msk        (0x1UL << DWT_FUNCTION_DATAVMATCH_Pos)      /*!< DWT FUNCTION: DATAVMATCH Mask */
-
-#define DWT_FUNCTION_CYCMATCH_Pos           7                                          /*!< DWT FUNCTION: CYCMATCH Position */
-#define DWT_FUNCTION_CYCMATCH_Msk          (0x1UL << DWT_FUNCTION_CYCMATCH_Pos)        /*!< DWT FUNCTION: CYCMATCH Mask */
-
-#define DWT_FUNCTION_EMITRANGE_Pos          5                                          /*!< DWT FUNCTION: EMITRANGE Position */
-#define DWT_FUNCTION_EMITRANGE_Msk         (0x1UL << DWT_FUNCTION_EMITRANGE_Pos)       /*!< DWT FUNCTION: EMITRANGE Mask */
-
-#define DWT_FUNCTION_FUNCTION_Pos           0                                          /*!< DWT FUNCTION: FUNCTION Position */
-#define DWT_FUNCTION_FUNCTION_Msk          (0xFUL << DWT_FUNCTION_FUNCTION_Pos)        /*!< DWT FUNCTION: FUNCTION Mask */
-
-/*@}*/ /* end of group CMSIS_DWT */
-
-
-/** \ingroup  CMSIS_core_register
-    \defgroup CMSIS_TPI     Trace Port Interface (TPI)
-    \brief      Type definitions for the Trace Port Interface (TPI)
-  @{
- */
-
-/** \brief  Structure type to access the Trace Port Interface Register (TPI).
- */
-typedef struct
-{
-  __IO uint32_t SSPSR;                   /*!< Offset: 0x000 (R/ )  Supported Parallel Port Size Register     */
-  __IO uint32_t CSPSR;                   /*!< Offset: 0x004 (R/W)  Current Parallel Port Size Register */
-       uint32_t RESERVED0[2];
-  __IO uint32_t ACPR;                    /*!< Offset: 0x010 (R/W)  Asynchronous Clock Prescaler Register */
-       uint32_t RESERVED1[55];
-  __IO uint32_t SPPR;                    /*!< Offset: 0x0F0 (R/W)  Selected Pin Protocol Register */
-       uint32_t RESERVED2[131];
-  __I  uint32_t FFSR;                    /*!< Offset: 0x300 (R/ )  Formatter and Flush Status Register */
-  __IO uint32_t FFCR;                    /*!< Offset: 0x304 (R/W)  Formatter and Flush Control Register */
-  __I  uint32_t FSCR;                    /*!< Offset: 0x308 (R/ )  Formatter Synchronization Counter Register */
-       uint32_t RESERVED3[759];
-  __I  uint32_t TRIGGER;                 /*!< Offset: 0xEE8 (R/ )  TRIGGER */
-  __I  uint32_t FIFO0;                   /*!< Offset: 0xEEC (R/ )  Integration ETM Data */
-  __I  uint32_t ITATBCTR2;               /*!< Offset: 0xEF0 (R/ )  ITATBCTR2 */
-       uint32_t RESERVED4[1];
-  __I  uint32_t ITATBCTR0;               /*!< Offset: 0xEF8 (R/ )  ITATBCTR0 */
-  __I  uint32_t FIFO1;                   /*!< Offset: 0xEFC (R/ )  Integration ITM Data */
-  __IO uint32_t ITCTRL;                  /*!< Offset: 0xF00 (R/W)  Integration Mode Control */
-       uint32_t RESERVED5[39];
-  __IO uint32_t CLAIMSET;                /*!< Offset: 0xFA0 (R/W)  Claim tag set */
-  __IO uint32_t CLAIMCLR;                /*!< Offset: 0xFA4 (R/W)  Claim tag clear */
-       uint32_t RESERVED7[8];
-  __I  uint32_t DEVID;                   /*!< Offset: 0xFC8 (R/ )  TPIU_DEVID */
-  __I  uint32_t DEVTYPE;                 /*!< Offset: 0xFCC (R/ )  TPIU_DEVTYPE */
-} TPI_Type;
-
-/* TPI Asynchronous Clock Prescaler Register Definitions */
-#define TPI_ACPR_PRESCALER_Pos              0                                          /*!< TPI ACPR: PRESCALER Position */
-#define TPI_ACPR_PRESCALER_Msk             (0x1FFFUL << TPI_ACPR_PRESCALER_Pos)        /*!< TPI ACPR: PRESCALER Mask */
-
-/* TPI Selected Pin Protocol Register Definitions */
-#define TPI_SPPR_TXMODE_Pos                 0                                          /*!< TPI SPPR: TXMODE Position */
-#define TPI_SPPR_TXMODE_Msk                (0x3UL << TPI_SPPR_TXMODE_Pos)              /*!< TPI SPPR: TXMODE Mask */
-
-/* TPI Formatter and Flush Status Register Definitions */
-#define TPI_FFSR_FtNonStop_Pos              3                                          /*!< TPI FFSR: FtNonStop Position */
-#define TPI_FFSR_FtNonStop_Msk             (0x1UL << TPI_FFSR_FtNonStop_Pos)           /*!< TPI FFSR: FtNonStop Mask */
-
-#define TPI_FFSR_TCPresent_Pos              2                                          /*!< TPI FFSR: TCPresent Position */
-#define TPI_FFSR_TCPresent_Msk             (0x1UL << TPI_FFSR_TCPresent_Pos)           /*!< TPI FFSR: TCPresent Mask */
-
-#define TPI_FFSR_FtStopped_Pos              1                                          /*!< TPI FFSR: FtStopped Position */
-#define TPI_FFSR_FtStopped_Msk             (0x1UL << TPI_FFSR_FtStopped_Pos)           /*!< TPI FFSR: FtStopped Mask */
-
-#define TPI_FFSR_FlInProg_Pos               0                                          /*!< TPI FFSR: FlInProg Position */
-#define TPI_FFSR_FlInProg_Msk              (0x1UL << TPI_FFSR_FlInProg_Pos)            /*!< TPI FFSR: FlInProg Mask */
-
-/* TPI Formatter and Flush Control Register Definitions */
-#define TPI_FFCR_TrigIn_Pos                 8                                          /*!< TPI FFCR: TrigIn Position */
-#define TPI_FFCR_TrigIn_Msk                (0x1UL << TPI_FFCR_TrigIn_Pos)              /*!< TPI FFCR: TrigIn Mask */
-
-#define TPI_FFCR_EnFCont_Pos                1                                          /*!< TPI FFCR: EnFCont Position */
-#define TPI_FFCR_EnFCont_Msk               (0x1UL << TPI_FFCR_EnFCont_Pos)             /*!< TPI FFCR: EnFCont Mask */
-
-/* TPI TRIGGER Register Definitions */
-#define TPI_TRIGGER_TRIGGER_Pos             0                                          /*!< TPI TRIGGER: TRIGGER Position */
-#define TPI_TRIGGER_TRIGGER_Msk            (0x1UL << TPI_TRIGGER_TRIGGER_Pos)          /*!< TPI TRIGGER: TRIGGER Mask */
-
-/* TPI Integration ETM Data Register Definitions (FIFO0) */
-#define TPI_FIFO0_ITM_ATVALID_Pos          29                                          /*!< TPI FIFO0: ITM_ATVALID Position */
-#define TPI_FIFO0_ITM_ATVALID_Msk          (0x3UL << TPI_FIFO0_ITM_ATVALID_Pos)        /*!< TPI FIFO0: ITM_ATVALID Mask */
-
-#define TPI_FIFO0_ITM_bytecount_Pos        27                                          /*!< TPI FIFO0: ITM_bytecount Position */
-#define TPI_FIFO0_ITM_bytecount_Msk        (0x3UL << TPI_FIFO0_ITM_bytecount_Pos)      /*!< TPI FIFO0: ITM_bytecount Mask */
-
-#define TPI_FIFO0_ETM_ATVALID_Pos          26                                          /*!< TPI FIFO0: ETM_ATVALID Position */
-#define TPI_FIFO0_ETM_ATVALID_Msk          (0x3UL << TPI_FIFO0_ETM_ATVALID_Pos)        /*!< TPI FIFO0: ETM_ATVALID Mask */
-
-#define TPI_FIFO0_ETM_bytecount_Pos        24                                          /*!< TPI FIFO0: ETM_bytecount Position */
-#define TPI_FIFO0_ETM_bytecount_Msk        (0x3UL << TPI_FIFO0_ETM_bytecount_Pos)      /*!< TPI FIFO0: ETM_bytecount Mask */
-
-#define TPI_FIFO0_ETM2_Pos                 16                                          /*!< TPI FIFO0: ETM2 Position */
-#define TPI_FIFO0_ETM2_Msk                 (0xFFUL << TPI_FIFO0_ETM2_Pos)              /*!< TPI FIFO0: ETM2 Mask */
-
-#define TPI_FIFO0_ETM1_Pos                  8                                          /*!< TPI FIFO0: ETM1 Position */
-#define TPI_FIFO0_ETM1_Msk                 (0xFFUL << TPI_FIFO0_ETM1_Pos)              /*!< TPI FIFO0: ETM1 Mask */
-
-#define TPI_FIFO0_ETM0_Pos                  0                                          /*!< TPI FIFO0: ETM0 Position */
-#define TPI_FIFO0_ETM0_Msk                 (0xFFUL << TPI_FIFO0_ETM0_Pos)              /*!< TPI FIFO0: ETM0 Mask */
-
-/* TPI ITATBCTR2 Register Definitions */
-#define TPI_ITATBCTR2_ATREADY_Pos           0                                          /*!< TPI ITATBCTR2: ATREADY Position */
-#define TPI_ITATBCTR2_ATREADY_Msk          (0x1UL << TPI_ITATBCTR2_ATREADY_Pos)        /*!< TPI ITATBCTR2: ATREADY Mask */
-
-/* TPI Integration ITM Data Register Definitions (FIFO1) */
-#define TPI_FIFO1_ITM_ATVALID_Pos          29                                          /*!< TPI FIFO1: ITM_ATVALID Position */
-#define TPI_FIFO1_ITM_ATVALID_Msk          (0x3UL << TPI_FIFO1_ITM_ATVALID_Pos)        /*!< TPI FIFO1: ITM_ATVALID Mask */
-
-#define TPI_FIFO1_ITM_bytecount_Pos        27                                          /*!< TPI FIFO1: ITM_bytecount Position */
-#define TPI_FIFO1_ITM_bytecount_Msk        (0x3UL << TPI_FIFO1_ITM_bytecount_Pos)      /*!< TPI FIFO1: ITM_bytecount Mask */
-
-#define TPI_FIFO1_ETM_ATVALID_Pos          26                                          /*!< TPI FIFO1: ETM_ATVALID Position */
-#define TPI_FIFO1_ETM_ATVALID_Msk          (0x3UL << TPI_FIFO1_ETM_ATVALID_Pos)        /*!< TPI FIFO1: ETM_ATVALID Mask */
-
-#define TPI_FIFO1_ETM_bytecount_Pos        24                                          /*!< TPI FIFO1: ETM_bytecount Position */
-#define TPI_FIFO1_ETM_bytecount_Msk        (0x3UL << TPI_FIFO1_ETM_bytecount_Pos)      /*!< TPI FIFO1: ETM_bytecount Mask */
-
-#define TPI_FIFO1_ITM2_Pos                 16                                          /*!< TPI FIFO1: ITM2 Position */
-#define TPI_FIFO1_ITM2_Msk                 (0xFFUL << TPI_FIFO1_ITM2_Pos)              /*!< TPI FIFO1: ITM2 Mask */
-
-#define TPI_FIFO1_ITM1_Pos                  8                                          /*!< TPI FIFO1: ITM1 Position */
-#define TPI_FIFO1_ITM1_Msk                 (0xFFUL << TPI_FIFO1_ITM1_Pos)              /*!< TPI FIFO1: ITM1 Mask */
-
-#define TPI_FIFO1_ITM0_Pos                  0                                          /*!< TPI FIFO1: ITM0 Position */
-#define TPI_FIFO1_ITM0_Msk                 (0xFFUL << TPI_FIFO1_ITM0_Pos)              /*!< TPI FIFO1: ITM0 Mask */
-
-/* TPI ITATBCTR0 Register Definitions */
-#define TPI_ITATBCTR0_ATREADY_Pos           0                                          /*!< TPI ITATBCTR0: ATREADY Position */
-#define TPI_ITATBCTR0_ATREADY_Msk          (0x1UL << TPI_ITATBCTR0_ATREADY_Pos)        /*!< TPI ITATBCTR0: ATREADY Mask */
-
-/* TPI Integration Mode Control Register Definitions */
-#define TPI_ITCTRL_Mode_Pos                 0                                          /*!< TPI ITCTRL: Mode Position */
-#define TPI_ITCTRL_Mode_Msk                (0x1UL << TPI_ITCTRL_Mode_Pos)              /*!< TPI ITCTRL: Mode Mask */
-
-/* TPI DEVID Register Definitions */
-#define TPI_DEVID_NRZVALID_Pos             11                                          /*!< TPI DEVID: NRZVALID Position */
-#define TPI_DEVID_NRZVALID_Msk             (0x1UL << TPI_DEVID_NRZVALID_Pos)           /*!< TPI DEVID: NRZVALID Mask */
-
-#define TPI_DEVID_MANCVALID_Pos            10                                          /*!< TPI DEVID: MANCVALID Position */
-#define TPI_DEVID_MANCVALID_Msk            (0x1UL << TPI_DEVID_MANCVALID_Pos)          /*!< TPI DEVID: MANCVALID Mask */
-
-#define TPI_DEVID_PTINVALID_Pos             9                                          /*!< TPI DEVID: PTINVALID Position */
-#define TPI_DEVID_PTINVALID_Msk            (0x1UL << TPI_DEVID_PTINVALID_Pos)          /*!< TPI DEVID: PTINVALID Mask */
-
-#define TPI_DEVID_MinBufSz_Pos              6                                          /*!< TPI DEVID: MinBufSz Position */
-#define TPI_DEVID_MinBufSz_Msk             (0x7UL << TPI_DEVID_MinBufSz_Pos)           /*!< TPI DEVID: MinBufSz Mask */
-
-#define TPI_DEVID_AsynClkIn_Pos             5                                          /*!< TPI DEVID: AsynClkIn Position */
-#define TPI_DEVID_AsynClkIn_Msk            (0x1UL << TPI_DEVID_AsynClkIn_Pos)          /*!< TPI DEVID: AsynClkIn Mask */
-
-#define TPI_DEVID_NrTraceInput_Pos          0                                          /*!< TPI DEVID: NrTraceInput Position */
-#define TPI_DEVID_NrTraceInput_Msk         (0x1FUL << TPI_DEVID_NrTraceInput_Pos)      /*!< TPI DEVID: NrTraceInput Mask */
-
-/* TPI DEVTYPE Register Definitions */
-#define TPI_DEVTYPE_SubType_Pos             0                                          /*!< TPI DEVTYPE: SubType Position */
-#define TPI_DEVTYPE_SubType_Msk            (0xFUL << TPI_DEVTYPE_SubType_Pos)          /*!< TPI DEVTYPE: SubType Mask */
-
-#define TPI_DEVTYPE_MajorType_Pos           4                                          /*!< TPI DEVTYPE: MajorType Position */
-#define TPI_DEVTYPE_MajorType_Msk          (0xFUL << TPI_DEVTYPE_MajorType_Pos)        /*!< TPI DEVTYPE: MajorType Mask */
-
-/*@}*/ /* end of group CMSIS_TPI */
-
-
-#if (__MPU_PRESENT == 1)
-/** \ingroup  CMSIS_core_register
-    \defgroup CMSIS_MPU     Memory Protection Unit (MPU)
-    \brief      Type definitions for the Memory Protection Unit (MPU)
-  @{
- */
-
-/** \brief  Structure type to access the Memory Protection Unit (MPU).
- */
-typedef struct
-{
-  __I  uint32_t TYPE;                    /*!< Offset: 0x000 (R/ )  MPU Type Register                              */
-  __IO uint32_t CTRL;                    /*!< Offset: 0x004 (R/W)  MPU Control Register                           */
-  __IO uint32_t RNR;                     /*!< Offset: 0x008 (R/W)  MPU Region RNRber Register                     */
-  __IO uint32_t RBAR;                    /*!< Offset: 0x00C (R/W)  MPU Region Base Address Register               */
-  __IO uint32_t RASR;                    /*!< Offset: 0x010 (R/W)  MPU Region Attribute and Size Register         */
-  __IO uint32_t RBAR_A1;                 /*!< Offset: 0x014 (R/W)  MPU Alias 1 Region Base Address Register       */
-  __IO uint32_t RASR_A1;                 /*!< Offset: 0x018 (R/W)  MPU Alias 1 Region Attribute and Size Register */
-  __IO uint32_t RBAR_A2;                 /*!< Offset: 0x01C (R/W)  MPU Alias 2 Region Base Address Register       */
-  __IO uint32_t RASR_A2;                 /*!< Offset: 0x020 (R/W)  MPU Alias 2 Region Attribute and Size Register */
-  __IO uint32_t RBAR_A3;                 /*!< Offset: 0x024 (R/W)  MPU Alias 3 Region Base Address Register       */
-  __IO uint32_t RASR_A3;                 /*!< Offset: 0x028 (R/W)  MPU Alias 3 Region Attribute and Size Register */
-} MPU_Type;
-
-/* MPU Type Register */
-#define MPU_TYPE_IREGION_Pos               16                                             /*!< MPU TYPE: IREGION Position */
-#define MPU_TYPE_IREGION_Msk               (0xFFUL << MPU_TYPE_IREGION_Pos)               /*!< MPU TYPE: IREGION Mask */
-
-#define MPU_TYPE_DREGION_Pos                8                                             /*!< MPU TYPE: DREGION Position */
-#define MPU_TYPE_DREGION_Msk               (0xFFUL << MPU_TYPE_DREGION_Pos)               /*!< MPU TYPE: DREGION Mask */
-
-#define MPU_TYPE_SEPARATE_Pos               0                                             /*!< MPU TYPE: SEPARATE Position */
-#define MPU_TYPE_SEPARATE_Msk              (1UL << MPU_TYPE_SEPARATE_Pos)                 /*!< MPU TYPE: SEPARATE Mask */
-
-/* MPU Control Register */
-#define MPU_CTRL_PRIVDEFENA_Pos             2                                             /*!< MPU CTRL: PRIVDEFENA Position */
-#define MPU_CTRL_PRIVDEFENA_Msk            (1UL << MPU_CTRL_PRIVDEFENA_Pos)               /*!< MPU CTRL: PRIVDEFENA Mask */
-
-#define MPU_CTRL_HFNMIENA_Pos               1                                             /*!< MPU CTRL: HFNMIENA Position */
-#define MPU_CTRL_HFNMIENA_Msk              (1UL << MPU_CTRL_HFNMIENA_Pos)                 /*!< MPU CTRL: HFNMIENA Mask */
-
-#define MPU_CTRL_ENABLE_Pos                 0                                             /*!< MPU CTRL: ENABLE Position */
-#define MPU_CTRL_ENABLE_Msk                (1UL << MPU_CTRL_ENABLE_Pos)                   /*!< MPU CTRL: ENABLE Mask */
-
-/* MPU Region Number Register */
-#define MPU_RNR_REGION_Pos                  0                                             /*!< MPU RNR: REGION Position */
-#define MPU_RNR_REGION_Msk                 (0xFFUL << MPU_RNR_REGION_Pos)                 /*!< MPU RNR: REGION Mask */
-
-/* MPU Region Base Address Register */
-#define MPU_RBAR_ADDR_Pos                   5                                             /*!< MPU RBAR: ADDR Position */
-#define MPU_RBAR_ADDR_Msk                  (0x7FFFFFFUL << MPU_RBAR_ADDR_Pos)             /*!< MPU RBAR: ADDR Mask */
-
-#define MPU_RBAR_VALID_Pos                  4                                             /*!< MPU RBAR: VALID Position */
-#define MPU_RBAR_VALID_Msk                 (1UL << MPU_RBAR_VALID_Pos)                    /*!< MPU RBAR: VALID Mask */
-
-#define MPU_RBAR_REGION_Pos                 0                                             /*!< MPU RBAR: REGION Position */
-#define MPU_RBAR_REGION_Msk                (0xFUL << MPU_RBAR_REGION_Pos)                 /*!< MPU RBAR: REGION Mask */
-
-/* MPU Region Attribute and Size Register */
-#define MPU_RASR_ATTRS_Pos                 16                                             /*!< MPU RASR: MPU Region Attribute field Position */
-#define MPU_RASR_ATTRS_Msk                 (0xFFFFUL << MPU_RASR_ATTRS_Pos)               /*!< MPU RASR: MPU Region Attribute field Mask */
-
-#define MPU_RASR_XN_Pos                    28                                             /*!< MPU RASR: ATTRS.XN Position */
-#define MPU_RASR_XN_Msk                    (1UL << MPU_RASR_XN_Pos)                       /*!< MPU RASR: ATTRS.XN Mask */
-
-#define MPU_RASR_AP_Pos                    24                                             /*!< MPU RASR: ATTRS.AP Position */
-#define MPU_RASR_AP_Msk                    (0x7UL << MPU_RASR_AP_Pos)                     /*!< MPU RASR: ATTRS.AP Mask */
-
-#define MPU_RASR_TEX_Pos                   19                                             /*!< MPU RASR: ATTRS.TEX Position */
-#define MPU_RASR_TEX_Msk                   (0x7UL << MPU_RASR_TEX_Pos)                    /*!< MPU RASR: ATTRS.TEX Mask */
-
-#define MPU_RASR_S_Pos                     18                                             /*!< MPU RASR: ATTRS.S Position */
-#define MPU_RASR_S_Msk                     (1UL << MPU_RASR_S_Pos)                        /*!< MPU RASR: ATTRS.S Mask */
-
-#define MPU_RASR_C_Pos                     17                                             /*!< MPU RASR: ATTRS.C Position */
-#define MPU_RASR_C_Msk                     (1UL << MPU_RASR_C_Pos)                        /*!< MPU RASR: ATTRS.C Mask */
-
-#define MPU_RASR_B_Pos                     16                                             /*!< MPU RASR: ATTRS.B Position */
-#define MPU_RASR_B_Msk                     (1UL << MPU_RASR_B_Pos)                        /*!< MPU RASR: ATTRS.B Mask */
-
-#define MPU_RASR_SRD_Pos                    8                                             /*!< MPU RASR: Sub-Region Disable Position */
-#define MPU_RASR_SRD_Msk                   (0xFFUL << MPU_RASR_SRD_Pos)                   /*!< MPU RASR: Sub-Region Disable Mask */
-
-#define MPU_RASR_SIZE_Pos                   1                                             /*!< MPU RASR: Region Size Field Position */
-#define MPU_RASR_SIZE_Msk                  (0x1FUL << MPU_RASR_SIZE_Pos)                  /*!< MPU RASR: Region Size Field Mask */
-
-#define MPU_RASR_ENABLE_Pos                 0                                             /*!< MPU RASR: Region enable bit Position */
-#define MPU_RASR_ENABLE_Msk                (1UL << MPU_RASR_ENABLE_Pos)                   /*!< MPU RASR: Region enable bit Disable Mask */
-
-/*@} end of group CMSIS_MPU */
-#endif
-
-
-#if (__FPU_PRESENT == 1)
-/** \ingroup  CMSIS_core_register
-    \defgroup CMSIS_FPU     Floating Point Unit (FPU)
-    \brief      Type definitions for the Floating Point Unit (FPU)
-  @{
- */
-
-/** \brief  Structure type to access the Floating Point Unit (FPU).
- */
-typedef struct
-{
-       uint32_t RESERVED0[1];
-  __IO uint32_t FPCCR;                   /*!< Offset: 0x004 (R/W)  Floating-Point Context Control Register               */
-  __IO uint32_t FPCAR;                   /*!< Offset: 0x008 (R/W)  Floating-Point Context Address Register               */
-  __IO uint32_t FPDSCR;                  /*!< Offset: 0x00C (R/W)  Floating-Point Default Status Control Register        */
-  __I  uint32_t MVFR0;                   /*!< Offset: 0x010 (R/ )  Media and FP Feature Register 0                       */
-  __I  uint32_t MVFR1;                   /*!< Offset: 0x014 (R/ )  Media and FP Feature Register 1                       */
-} FPU_Type;
-
-/* Floating-Point Context Control Register */
-#define FPU_FPCCR_ASPEN_Pos                31                                             /*!< FPCCR: ASPEN bit Position */
-#define FPU_FPCCR_ASPEN_Msk                (1UL << FPU_FPCCR_ASPEN_Pos)                   /*!< FPCCR: ASPEN bit Mask */
-
-#define FPU_FPCCR_LSPEN_Pos                30                                             /*!< FPCCR: LSPEN Position */
-#define FPU_FPCCR_LSPEN_Msk                (1UL << FPU_FPCCR_LSPEN_Pos)                   /*!< FPCCR: LSPEN bit Mask */
-
-#define FPU_FPCCR_MONRDY_Pos                8                                             /*!< FPCCR: MONRDY Position */
-#define FPU_FPCCR_MONRDY_Msk               (1UL << FPU_FPCCR_MONRDY_Pos)                  /*!< FPCCR: MONRDY bit Mask */
-
-#define FPU_FPCCR_BFRDY_Pos                 6                                             /*!< FPCCR: BFRDY Position */
-#define FPU_FPCCR_BFRDY_Msk                (1UL << FPU_FPCCR_BFRDY_Pos)                   /*!< FPCCR: BFRDY bit Mask */
-
-#define FPU_FPCCR_MMRDY_Pos                 5                                             /*!< FPCCR: MMRDY Position */
-#define FPU_FPCCR_MMRDY_Msk                (1UL << FPU_FPCCR_MMRDY_Pos)                   /*!< FPCCR: MMRDY bit Mask */
-
-#define FPU_FPCCR_HFRDY_Pos                 4                                             /*!< FPCCR: HFRDY Position */
-#define FPU_FPCCR_HFRDY_Msk                (1UL << FPU_FPCCR_HFRDY_Pos)                   /*!< FPCCR: HFRDY bit Mask */
-
-#define FPU_FPCCR_THREAD_Pos                3                                             /*!< FPCCR: processor mode bit Position */
-#define FPU_FPCCR_THREAD_Msk               (1UL << FPU_FPCCR_THREAD_Pos)                  /*!< FPCCR: processor mode active bit Mask */
-
-#define FPU_FPCCR_USER_Pos                  1                                             /*!< FPCCR: privilege level bit Position */
-#define FPU_FPCCR_USER_Msk                 (1UL << FPU_FPCCR_USER_Pos)                    /*!< FPCCR: privilege level bit Mask */
-
-#define FPU_FPCCR_LSPACT_Pos                0                                             /*!< FPCCR: Lazy state preservation active bit Position */
-#define FPU_FPCCR_LSPACT_Msk               (1UL << FPU_FPCCR_LSPACT_Pos)                  /*!< FPCCR: Lazy state preservation active bit Mask */
-
-/* Floating-Point Context Address Register */
-#define FPU_FPCAR_ADDRESS_Pos               3                                             /*!< FPCAR: ADDRESS bit Position */
-#define FPU_FPCAR_ADDRESS_Msk              (0x1FFFFFFFUL << FPU_FPCAR_ADDRESS_Pos)        /*!< FPCAR: ADDRESS bit Mask */
-
-/* Floating-Point Default Status Control Register */
-#define FPU_FPDSCR_AHP_Pos                 26                                             /*!< FPDSCR: AHP bit Position */
-#define FPU_FPDSCR_AHP_Msk                 (1UL << FPU_FPDSCR_AHP_Pos)                    /*!< FPDSCR: AHP bit Mask */
-
-#define FPU_FPDSCR_DN_Pos                  25                                             /*!< FPDSCR: DN bit Position */
-#define FPU_FPDSCR_DN_Msk                  (1UL << FPU_FPDSCR_DN_Pos)                     /*!< FPDSCR: DN bit Mask */
-
-#define FPU_FPDSCR_FZ_Pos                  24                                             /*!< FPDSCR: FZ bit Position */
-#define FPU_FPDSCR_FZ_Msk                  (1UL << FPU_FPDSCR_FZ_Pos)                     /*!< FPDSCR: FZ bit Mask */
-
-#define FPU_FPDSCR_RMode_Pos               22                                             /*!< FPDSCR: RMode bit Position */
-#define FPU_FPDSCR_RMode_Msk               (3UL << FPU_FPDSCR_RMode_Pos)                  /*!< FPDSCR: RMode bit Mask */
-
-/* Media and FP Feature Register 0 */
-#define FPU_MVFR0_FP_rounding_modes_Pos    28                                             /*!< MVFR0: FP rounding modes bits Position */
-#define FPU_MVFR0_FP_rounding_modes_Msk    (0xFUL << FPU_MVFR0_FP_rounding_modes_Pos)     /*!< MVFR0: FP rounding modes bits Mask */
-
-#define FPU_MVFR0_Short_vectors_Pos        24                                             /*!< MVFR0: Short vectors bits Position */
-#define FPU_MVFR0_Short_vectors_Msk        (0xFUL << FPU_MVFR0_Short_vectors_Pos)         /*!< MVFR0: Short vectors bits Mask */
-
-#define FPU_MVFR0_Square_root_Pos          20                                             /*!< MVFR0: Square root bits Position */
-#define FPU_MVFR0_Square_root_Msk          (0xFUL << FPU_MVFR0_Square_root_Pos)           /*!< MVFR0: Square root bits Mask */
-
-#define FPU_MVFR0_Divide_Pos               16                                             /*!< MVFR0: Divide bits Position */
-#define FPU_MVFR0_Divide_Msk               (0xFUL << FPU_MVFR0_Divide_Pos)                /*!< MVFR0: Divide bits Mask */
-
-#define FPU_MVFR0_FP_excep_trapping_Pos    12                                             /*!< MVFR0: FP exception trapping bits Position */
-#define FPU_MVFR0_FP_excep_trapping_Msk    (0xFUL << FPU_MVFR0_FP_excep_trapping_Pos)     /*!< MVFR0: FP exception trapping bits Mask */
-
-#define FPU_MVFR0_Double_precision_Pos      8                                             /*!< MVFR0: Double-precision bits Position */
-#define FPU_MVFR0_Double_precision_Msk     (0xFUL << FPU_MVFR0_Double_precision_Pos)      /*!< MVFR0: Double-precision bits Mask */
-
-#define FPU_MVFR0_Single_precision_Pos      4                                             /*!< MVFR0: Single-precision bits Position */
-#define FPU_MVFR0_Single_precision_Msk     (0xFUL << FPU_MVFR0_Single_precision_Pos)      /*!< MVFR0: Single-precision bits Mask */
-
-#define FPU_MVFR0_A_SIMD_registers_Pos      0                                             /*!< MVFR0: A_SIMD registers bits Position */
-#define FPU_MVFR0_A_SIMD_registers_Msk     (0xFUL << FPU_MVFR0_A_SIMD_registers_Pos)      /*!< MVFR0: A_SIMD registers bits Mask */
-
-/* Media and FP Feature Register 1 */
-#define FPU_MVFR1_FP_fused_MAC_Pos         28                                             /*!< MVFR1: FP fused MAC bits Position */
-#define FPU_MVFR1_FP_fused_MAC_Msk         (0xFUL << FPU_MVFR1_FP_fused_MAC_Pos)          /*!< MVFR1: FP fused MAC bits Mask */
-
-#define FPU_MVFR1_FP_HPFP_Pos              24                                             /*!< MVFR1: FP HPFP bits Position */
-#define FPU_MVFR1_FP_HPFP_Msk              (0xFUL << FPU_MVFR1_FP_HPFP_Pos)               /*!< MVFR1: FP HPFP bits Mask */
-
-#define FPU_MVFR1_D_NaN_mode_Pos            4                                             /*!< MVFR1: D_NaN mode bits Position */
-#define FPU_MVFR1_D_NaN_mode_Msk           (0xFUL << FPU_MVFR1_D_NaN_mode_Pos)            /*!< MVFR1: D_NaN mode bits Mask */
-
-#define FPU_MVFR1_FtZ_mode_Pos              0                                             /*!< MVFR1: FtZ mode bits Position */
-#define FPU_MVFR1_FtZ_mode_Msk             (0xFUL << FPU_MVFR1_FtZ_mode_Pos)              /*!< MVFR1: FtZ mode bits Mask */
-
-/*@} end of group CMSIS_FPU */
-#endif
-
-
-/** \ingroup  CMSIS_core_register
-    \defgroup CMSIS_CoreDebug       Core Debug Registers (CoreDebug)
-    \brief      Type definitions for the Core Debug Registers
-  @{
- */
-
-/** \brief  Structure type to access the Core Debug Register (CoreDebug).
- */
-typedef struct
-{
-  __IO uint32_t DHCSR;                   /*!< Offset: 0x000 (R/W)  Debug Halting Control and Status Register    */
-  __O  uint32_t DCRSR;                   /*!< Offset: 0x004 ( /W)  Debug Core Register Selector Register        */
-  __IO uint32_t DCRDR;                   /*!< Offset: 0x008 (R/W)  Debug Core Register Data Register            */
-  __IO uint32_t DEMCR;                   /*!< Offset: 0x00C (R/W)  Debug Exception and Monitor Control Register */
-} CoreDebug_Type;
-
-/* Debug Halting Control and Status Register */
-#define CoreDebug_DHCSR_DBGKEY_Pos         16                                             /*!< CoreDebug DHCSR: DBGKEY Position */
-#define CoreDebug_DHCSR_DBGKEY_Msk         (0xFFFFUL << CoreDebug_DHCSR_DBGKEY_Pos)       /*!< CoreDebug DHCSR: DBGKEY Mask */
-
-#define CoreDebug_DHCSR_S_RESET_ST_Pos     25                                             /*!< CoreDebug DHCSR: S_RESET_ST Position */
-#define CoreDebug_DHCSR_S_RESET_ST_Msk     (1UL << CoreDebug_DHCSR_S_RESET_ST_Pos)        /*!< CoreDebug DHCSR: S_RESET_ST Mask */
-
-#define CoreDebug_DHCSR_S_RETIRE_ST_Pos    24                                             /*!< CoreDebug DHCSR: S_RETIRE_ST Position */
-#define CoreDebug_DHCSR_S_RETIRE_ST_Msk    (1UL << CoreDebug_DHCSR_S_RETIRE_ST_Pos)       /*!< CoreDebug DHCSR: S_RETIRE_ST Mask */
-
-#define CoreDebug_DHCSR_S_LOCKUP_Pos       19                                             /*!< CoreDebug DHCSR: S_LOCKUP Position */
-#define CoreDebug_DHCSR_S_LOCKUP_Msk       (1UL << CoreDebug_DHCSR_S_LOCKUP_Pos)          /*!< CoreDebug DHCSR: S_LOCKUP Mask */
-
-#define CoreDebug_DHCSR_S_SLEEP_Pos        18                                             /*!< CoreDebug DHCSR: S_SLEEP Position */
-#define CoreDebug_DHCSR_S_SLEEP_Msk        (1UL << CoreDebug_DHCSR_S_SLEEP_Pos)           /*!< CoreDebug DHCSR: S_SLEEP Mask */
-
-#define CoreDebug_DHCSR_S_HALT_Pos         17                                             /*!< CoreDebug DHCSR: S_HALT Position */
-#define CoreDebug_DHCSR_S_HALT_Msk         (1UL << CoreDebug_DHCSR_S_HALT_Pos)            /*!< CoreDebug DHCSR: S_HALT Mask */
-
-#define CoreDebug_DHCSR_S_REGRDY_Pos       16                                             /*!< CoreDebug DHCSR: S_REGRDY Position */
-#define CoreDebug_DHCSR_S_REGRDY_Msk       (1UL << CoreDebug_DHCSR_S_REGRDY_Pos)          /*!< CoreDebug DHCSR: S_REGRDY Mask */
-
-#define CoreDebug_DHCSR_C_SNAPSTALL_Pos     5                                             /*!< CoreDebug DHCSR: C_SNAPSTALL Position */
-#define CoreDebug_DHCSR_C_SNAPSTALL_Msk    (1UL << CoreDebug_DHCSR_C_SNAPSTALL_Pos)       /*!< CoreDebug DHCSR: C_SNAPSTALL Mask */
-
-#define CoreDebug_DHCSR_C_MASKINTS_Pos      3                                             /*!< CoreDebug DHCSR: C_MASKINTS Position */
-#define CoreDebug_DHCSR_C_MASKINTS_Msk     (1UL << CoreDebug_DHCSR_C_MASKINTS_Pos)        /*!< CoreDebug DHCSR: C_MASKINTS Mask */
-
-#define CoreDebug_DHCSR_C_STEP_Pos          2                                             /*!< CoreDebug DHCSR: C_STEP Position */
-#define CoreDebug_DHCSR_C_STEP_Msk         (1UL << CoreDebug_DHCSR_C_STEP_Pos)            /*!< CoreDebug DHCSR: C_STEP Mask */
-
-#define CoreDebug_DHCSR_C_HALT_Pos          1                                             /*!< CoreDebug DHCSR: C_HALT Position */
-#define CoreDebug_DHCSR_C_HALT_Msk         (1UL << CoreDebug_DHCSR_C_HALT_Pos)            /*!< CoreDebug DHCSR: C_HALT Mask */
-
-#define CoreDebug_DHCSR_C_DEBUGEN_Pos       0                                             /*!< CoreDebug DHCSR: C_DEBUGEN Position */
-#define CoreDebug_DHCSR_C_DEBUGEN_Msk      (1UL << CoreDebug_DHCSR_C_DEBUGEN_Pos)         /*!< CoreDebug DHCSR: C_DEBUGEN Mask */
-
-/* Debug Core Register Selector Register */
-#define CoreDebug_DCRSR_REGWnR_Pos         16                                             /*!< CoreDebug DCRSR: REGWnR Position */
-#define CoreDebug_DCRSR_REGWnR_Msk         (1UL << CoreDebug_DCRSR_REGWnR_Pos)            /*!< CoreDebug DCRSR: REGWnR Mask */
-
-#define CoreDebug_DCRSR_REGSEL_Pos          0                                             /*!< CoreDebug DCRSR: REGSEL Position */
-#define CoreDebug_DCRSR_REGSEL_Msk         (0x1FUL << CoreDebug_DCRSR_REGSEL_Pos)         /*!< CoreDebug DCRSR: REGSEL Mask */
-
-/* Debug Exception and Monitor Control Register */
-#define CoreDebug_DEMCR_TRCENA_Pos         24                                             /*!< CoreDebug DEMCR: TRCENA Position */
-#define CoreDebug_DEMCR_TRCENA_Msk         (1UL << CoreDebug_DEMCR_TRCENA_Pos)            /*!< CoreDebug DEMCR: TRCENA Mask */
-
-#define CoreDebug_DEMCR_MON_REQ_Pos        19                                             /*!< CoreDebug 

<TRUNCATED>


[49/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
directory re-org


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/6a7432f4
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/6a7432f4
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/6a7432f4

Branch: refs/heads/develop
Commit: 6a7432f493900f8adad0fe9416b65d477fc5b316
Parents: 797b341
Author: Sterling Hughes <st...@apache.org>
Authored: Wed Sep 28 16:34:02 2016 -0700
Committer: Sterling Hughes <st...@apache.org>
Committed: Wed Sep 28 18:32:22 2016 -0700

----------------------------------------------------------------------
 apps/blecent/pkg.yml                            |    6 +-
 apps/blehci/pkg.yml                             |    6 +-
 apps/bleprph/pkg.yml                            |    6 +-
 apps/bletest/pkg.yml                            |    6 +-
 apps/bletiny/pkg.yml                            |    6 +-
 apps/bleuart/pkg.yml                            |    8 +-
 apps/blinky/pkg.yml                             |    6 +-
 apps/boot/pkg.yml                               |   10 +-
 apps/ffs2native/pkg.yml                         |    4 +-
 apps/luatest/pkg.yml                            |   31 -
 apps/luatest/src/main.c                         |   75 -
 apps/ocf_sample/pkg.yml                         |    6 +-
 apps/sblinky/pkg.yml                            |   36 -
 apps/sblinky/src/main.c                         |  599 ------
 apps/slinky/pkg.yml                             |   12 +-
 apps/splitty/pkg.yml                            |   10 +-
 apps/test/pkg.yml                               |   10 +-
 .../include/boot_serial/boot_serial.h           |   33 +
 boot/boot_serial/pkg.yml                        |   36 +
 boot/boot_serial/src/boot_serial.c              |  403 ++++
 boot/boot_serial/src/boot_serial_priv.h         |   61 +
 boot/boot_serial/test/pkg.yml                   |   33 +
 boot/boot_serial/test/src/boot_test.c           |  231 +++
 boot/bootutil/design.txt                        |  413 ++++
 boot/bootutil/include/bootutil/bootutil_misc.h  |   28 +
 boot/bootutil/include/bootutil/bootutil_test.h  |   25 +
 boot/bootutil/include/bootutil/image.h          |   89 +
 boot/bootutil/include/bootutil/loader.h         |   84 +
 boot/bootutil/include/bootutil/sign_key.h       |   33 +
 boot/bootutil/pkg.yml                           |   41 +
 boot/bootutil/signed_images.md                  |   91 +
 boot/bootutil/src/bootutil_misc.c               |  319 ++++
 boot/bootutil/src/bootutil_priv.h               |   75 +
 boot/bootutil/src/image_ec.c                    |  121 ++
 boot/bootutil/src/image_rsa.c                   |  144 ++
 boot/bootutil/src/image_validate.c              |  198 ++
 boot/bootutil/src/loader.c                      |  652 +++++++
 boot/bootutil/test/pkg.yml                      |   30 +
 boot/bootutil/test/src/boot_test.c              | 1169 ++++++++++++
 boot/split/README.md                            |   63 +
 boot/split/include/split/split.h                |   57 +
 boot/split/include/split/split_priv.h           |   30 +
 boot/split/pkg.yml                              |   30 +
 boot/split/src/split.c                          |   77 +
 boot/split/src/split_config.c                   |   95 +
 boot/split/src/split_netmgr.c                   |  149 ++
 .../include/adc_stm32f4/adc_stm32f4.h           |   62 -
 drivers/adc/adc_stm32f4/pkg.yml                 |   34 -
 drivers/adc/adc_stm32f4/src/adc_stm32f4.c       |  735 --------
 encoding/base64/include/base64/base64.h         |   32 +
 encoding/base64/include/base64/hex.h            |   25 +
 encoding/base64/pkg.yml                         |   26 +
 encoding/base64/src/base64.c                    |  181 ++
 encoding/base64/src/hex.c                       |  101 +
 encoding/base64/test/pkg.yml                    |   30 +
 encoding/base64/test/src/encoding_test.c        |   46 +
 encoding/base64/test/src/encoding_test_priv.h   |   25 +
 encoding/base64/test/src/hex_test.c             |  125 ++
 encoding/crc/include/crc/base64.h               |   32 +
 encoding/crc/include/crc/crc16.h                |   36 +
 encoding/crc/include/crc/crc8.h                 |   32 +
 encoding/crc/include/crc/hex.h                  |   25 +
 encoding/crc/pkg.yml                            |   28 +
 encoding/crc/src/crc16.c                        |   83 +
 encoding/crc/src/crc8.c                         |   74 +
 encoding/crc/test/pkg.yml                       |   30 +
 encoding/crc/test/src/encoding_test.c           |   46 +
 encoding/crc/test/src/encoding_test_priv.h      |   25 +
 encoding/crc/test/src/hex_test.c                |  125 ++
 encoding/json/MSJSON_COPYING                    |   28 +
 encoding/json/include/json/json.h               |  245 +++
 encoding/json/pkg.yml                           |   26 +
 encoding/json/src/json_decode.c                 |  670 +++++++
 encoding/json/src/json_encode.c                 |  248 +++
 encoding/json/test/pkg.yml                      |   30 +
 encoding/json/test/src/test_json.c              |   43 +
 encoding/json/test/src/test_json.h              |   27 +
 encoding/json/test/src/test_json_simple.c       |  360 ++++
 encoding/tinycbor/include/tinycbor/assert_p.h   |   29 +
 encoding/tinycbor/include/tinycbor/cbor.h       |  479 +++++
 .../tinycbor/include/tinycbor/cborconstants_p.h |   52 +
 encoding/tinycbor/include/tinycbor/cborjson.h   |   62 +
 .../include/tinycbor/compilersupport_p.h        |  218 +++
 .../include/tinycbor/extract_number_p.h         |   78 +
 .../tinycbor/include/tinycbor/math_support_p.h  |   47 +
 encoding/tinycbor/pkg.yml                       |   26 +
 encoding/tinycbor/src/cborencoder.c             |  629 +++++++
 .../src/cborencoder_close_container_checked.c   |   82 +
 encoding/tinycbor/src/cborerrorstrings.c        |  165 ++
 encoding/tinycbor/src/cborparser.c              | 1293 +++++++++++++
 encoding/tinycbor/src/cborparser_dup_string.c   |  113 ++
 encoding/tinycbor/src/cborpretty.c              |  470 +++++
 encoding/tinycbor/src/cbortojson.c              |  686 +++++++
 encoding/tinycbor/src/open_memstream.c          |  117 ++
 fs/fcb/README.md                                |   58 +
 fs/fcb/include/fcb/fcb.h                        |  134 ++
 fs/fcb/pkg.yml                                  |   29 +
 fs/fcb/src/fcb.c                                |  258 +++
 fs/fcb/src/fcb_append.c                         |  143 ++
 fs/fcb/src/fcb_elem_info.c                      |  101 +
 fs/fcb/src/fcb_getnext.c                        |  132 ++
 fs/fcb/src/fcb_priv.h                           |   57 +
 fs/fcb/src/fcb_rotate.c                         |   56 +
 fs/fcb/src/fcb_walk.c                           |   53 +
 fs/fcb/test/pkg.yml                             |   30 +
 fs/fcb/test/src/fcb_test.c                      |  672 +++++++
 fs/nffs/pkg.yml                                 |    5 +-
 fs/nffs/src/nffs_priv.h                         |    4 +-
 fs/nffs/test/pkg.yml                            |    4 +-
 hw/bsp/arduino_primo_nrf52/pkg.yml              |    2 +-
 hw/bsp/bmd300eval/pkg.yml                       |    2 +-
 hw/bsp/nrf51-arduino_101/pkg.yml                |    2 +-
 hw/bsp/nrf51-blenano/pkg.yml                    |    2 +-
 hw/bsp/nrf51dk-16kbram/pkg.yml                  |    2 +-
 hw/bsp/nrf51dk/pkg.yml                          |    2 +-
 hw/bsp/nrf52dk/pkg.yml                          |    2 +-
 hw/bsp/nrf52pdk/pkg.yml                         |    2 +-
 hw/bsp/nucleo-f401re/pkg.yml                    |    2 +-
 hw/bsp/olimex_stm32-e407_devboard/pkg.yml       |    2 +-
 hw/bsp/stm32f4discovery/pkg.yml                 |    2 +-
 hw/cmsis-core/pkg.yml                           |   27 +
 hw/cmsis-core/src/cmsis_nvic.c                  |   73 +
 hw/cmsis-core/src/ext/core_ca9.h                |  271 +++
 hw/cmsis-core/src/ext/core_caFunc.h             | 1161 ++++++++++++
 hw/cmsis-core/src/ext/core_caInstr.h            |   45 +
 hw/cmsis-core/src/ext/core_ca_mmu.h             |  848 +++++++++
 hw/cmsis-core/src/ext/core_cm0.h                |  682 +++++++
 hw/cmsis-core/src/ext/core_cm0plus.h            |  793 ++++++++
 hw/cmsis-core/src/ext/core_cm3.h                | 1627 ++++++++++++++++
 hw/cmsis-core/src/ext/core_cm4.h                | 1772 ++++++++++++++++++
 hw/cmsis-core/src/ext/core_cm4_simd.h           |  673 +++++++
 hw/cmsis-core/src/ext/core_cmFunc.h             |  636 +++++++
 hw/cmsis-core/src/ext/core_cmInstr.h            |  688 +++++++
 .../include/adc_stm32f4/adc_stm32f4.h           |   62 +
 hw/drivers/adc/adc_stm32f4/pkg.yml              |   34 +
 hw/drivers/adc/adc_stm32f4/src/adc_stm32f4.c    |  735 ++++++++
 hw/hal/pkg.yml                                  |    2 +-
 hw/mcu/nordic/nrf51xxx/pkg.yml                  |    2 +-
 hw/mcu/nordic/nrf52xxx/pkg.yml                  |    2 +-
 hw/mcu/nordic/pkg.yml                           |    2 +-
 hw/mcu/stm/stm32f4xx/pkg.yml                    |    2 +-
 hw/mcu/stm/stm32f4xx/src/hal_watchdog.c         |    2 +-
 .../os/include/os/arch/cortex_m0/os/os_arch.h   |   74 +
 .../os/include/os/arch/cortex_m4/os/os_arch.h   |   75 +
 kernel/os/include/os/arch/sim/os/os_arch.h      |   74 +
 kernel/os/include/os/endian.h                   |   92 +
 kernel/os/include/os/os.h                       |  101 +
 kernel/os/include/os/os_callout.h               |   60 +
 kernel/os/include/os/os_cfg.h                   |   25 +
 kernel/os/include/os/os_dev.h                   |  114 ++
 kernel/os/include/os/os_eventq.h                |   51 +
 kernel/os/include/os/os_heap.h                  |   30 +
 kernel/os/include/os/os_malloc.h                |   34 +
 kernel/os/include/os/os_mbuf.h                  |  297 +++
 kernel/os/include/os/os_mempool.h               |   94 +
 kernel/os/include/os/os_mutex.h                 |   59 +
 kernel/os/include/os/os_sanity.h                |   56 +
 kernel/os/include/os/os_sched.h                 |   37 +
 kernel/os/include/os/os_sem.h                   |   52 +
 kernel/os/include/os/os_task.h                  |  114 ++
 kernel/os/include/os/os_test.h                  |   25 +
 kernel/os/include/os/os_time.h                  |  111 ++
 kernel/os/include/os/queue.h                    |  514 +++++
 kernel/os/pkg.yml                               |   84 +
 kernel/os/src/arch/cortex_m0/m0/HAL_CM0.s       |  277 +++
 kernel/os/src/arch/cortex_m0/m0/SVC_Table.s     |   56 +
 kernel/os/src/arch/cortex_m0/os_arch_arm.c      |  333 ++++
 kernel/os/src/arch/cortex_m0/os_fault.c         |  158 ++
 kernel/os/src/arch/cortex_m4/m4/HAL_CM4.s       |  224 +++
 kernel/os/src/arch/cortex_m4/m4/SVC_Table.s     |   56 +
 kernel/os/src/arch/cortex_m4/os_arch_arm.c      |  328 ++++
 kernel/os/src/arch/cortex_m4/os_fault.c         |  160 ++
 kernel/os/src/arch/sim/os_arch_sim.c            |  462 +++++
 kernel/os/src/arch/sim/os_arch_stack_frame.s    |  101 +
 kernel/os/src/arch/sim/os_fault.c               |   34 +
 kernel/os/src/os.c                              |  191 ++
 kernel/os/src/os_callout.c                      |  200 ++
 kernel/os/src/os_dev.c                          |  309 +++
 kernel/os/src/os_eventq.c                       |  235 +++
 kernel/os/src/os_heap.c                         |  106 ++
 kernel/os/src/os_mbuf.c                         | 1270 +++++++++++++
 kernel/os/src/os_mempool.c                      |  233 +++
 kernel/os/src/os_msys_init.c                    |  147 ++
 kernel/os/src/os_mutex.c                        |  236 +++
 kernel/os/src/os_priv.h                         |   38 +
 kernel/os/src/os_sanity.c                       |  238 +++
 kernel/os/src/os_sched.c                        |  330 ++++
 kernel/os/src/os_sem.c                          |  212 +++
 kernel/os/src/os_task.c                         |  216 +++
 kernel/os/src/os_time.c                         |  248 +++
 kernel/os/test/pkg.yml                          |   30 +
 .../test/src/arch/cortex_m4/os_test_arch_arm.c  |   27 +
 kernel/os/test/src/arch/sim/os_test_arch_sim.c  |   52 +
 kernel/os/test/src/callout_test.c               |  330 ++++
 kernel/os/test/src/eventq_test.c                |  416 ++++
 kernel/os/test/src/mbuf_test.c                  |  420 +++++
 kernel/os/test/src/mempool_test.c               |  227 +++
 kernel/os/test/src/mutex_test.c                 |  407 ++++
 kernel/os/test/src/os_test.c                    |   53 +
 kernel/os/test/src/os_test_priv.h               |   32 +
 kernel/os/test/src/sem_test.c                   |  401 ++++
 libc/baselibc/LICENSE                           |  133 ++
 libc/baselibc/Makefile                          |   46 +
 libc/baselibc/README.md                         |    6 +
 libc/baselibc/include/assert.h                  |   28 +
 libc/baselibc/include/ctype.h                   |   86 +
 libc/baselibc/include/inttypes.h                |  229 +++
 libc/baselibc/include/klibc/extern.h            |   16 +
 libc/baselibc/include/klibc/inline.h            |   12 +
 libc/baselibc/include/stdio.h                   |  124 ++
 libc/baselibc/include/stdlib.h                  |  101 +
 libc/baselibc/include/string.h                  |   59 +
 libc/baselibc/pkg.yml                           |   28 +
 libc/baselibc/src/asprintf.c                    |   30 +
 libc/baselibc/src/atoi.c                        |    3 +
 libc/baselibc/src/atol.c                        |    3 +
 libc/baselibc/src/atoll.c                       |    3 +
 .../baselibc_test/printf_tests.c.donotcompile   |   22 +
 .../src/baselibc_test/tests_glue.c.donotcompile |   33 +
 libc/baselibc/src/baselibc_test/unittests.h     |   36 +
 libc/baselibc/src/bsearch.c                     |   26 +
 libc/baselibc/src/bzero.c                       |    6 +
 libc/baselibc/src/calloc.c                      |   20 +
 libc/baselibc/src/fgets.c                       |   31 +
 libc/baselibc/src/inline.c                      |    5 +
 libc/baselibc/src/jrand48.c                     |   24 +
 libc/baselibc/src/lrand48.c                     |   13 +
 libc/baselibc/src/malloc.c                      |  274 +++
 libc/baselibc/src/malloc.h                      |   43 +
 libc/baselibc/src/memccpy.c                     |   23 +
 libc/baselibc/src/memchr.c                      |   19 +
 libc/baselibc/src/memcmp.c                      |   19 +
 libc/baselibc/src/memcpy.c                      |   29 +
 libc/baselibc/src/memfile.c                     |   33 +
 libc/baselibc/src/memmem.c                      |   52 +
 libc/baselibc/src/memmove.c                     |   36 +
 libc/baselibc/src/memrchr.c                     |   19 +
 libc/baselibc/src/memset.c                      |   30 +
 libc/baselibc/src/memswap.c                     |   24 +
 libc/baselibc/src/mrand48.c                     |   13 +
 libc/baselibc/src/mynewt.c                      |   47 +
 libc/baselibc/src/nrand48.c                     |   11 +
 libc/baselibc/src/qsort.c                       |   46 +
 libc/baselibc/src/realloc.c                     |   50 +
 libc/baselibc/src/sprintf.c                     |   18 +
 libc/baselibc/src/srand48.c                     |   15 +
 libc/baselibc/src/sscanf.c                      |   17 +
 libc/baselibc/src/strcasecmp.c                  |   24 +
 libc/baselibc/src/strcat.c                      |   11 +
 libc/baselibc/src/strchr.c                      |   17 +
 libc/baselibc/src/strcmp.c                      |   21 +
 libc/baselibc/src/strcpy.c                      |   20 +
 libc/baselibc/src/strcspn.c                     |   51 +
 libc/baselibc/src/strdup.c                      |   17 +
 libc/baselibc/src/strlcat.c                     |   30 +
 libc/baselibc/src/strlcpy.c                     |   26 +
 libc/baselibc/src/strlen.c                      |   13 +
 libc/baselibc/src/strncasecmp.c                 |   24 +
 libc/baselibc/src/strncat.c                     |   21 +
 libc/baselibc/src/strncmp.c                     |   21 +
 libc/baselibc/src/strncpy.c                     |   24 +
 libc/baselibc/src/strndup.c                     |   19 +
 libc/baselibc/src/strnlen.c                     |   18 +
 libc/baselibc/src/strntoimax.c                  |   13 +
 libc/baselibc/src/strntoumax.c                  |   77 +
 libc/baselibc/src/strpbrk.c                     |   55 +
 libc/baselibc/src/strrchr.c                     |   19 +
 libc/baselibc/src/strsep.c                      |   21 +
 libc/baselibc/src/strspn.c                      |   56 +
 libc/baselibc/src/strstr.c                      |   11 +
 libc/baselibc/src/strtoimax.c                   |    3 +
 libc/baselibc/src/strtok.c                      |   12 +
 libc/baselibc/src/strtok_r.c                    |   13 +
 libc/baselibc/src/strtol.c                      |    3 +
 libc/baselibc/src/strtoll.c                     |    3 +
 libc/baselibc/src/strtoul.c                     |    3 +
 libc/baselibc/src/strtoull.c                    |    3 +
 libc/baselibc/src/strtoumax.c                   |    3 +
 libc/baselibc/src/templates/atox.c.template     |   14 +
 libc/baselibc/src/templates/strtox.c.template   |   14 +
 libc/baselibc/src/tinyprintf.c                  |  362 ++++
 libc/baselibc/src/vasprintf.c                   |   25 +
 libc/baselibc/src/vprintf.c                     |   11 +
 libc/baselibc/src/vsprintf.c                    |   11 +
 libc/baselibc/src/vsscanf.c                     |  400 ++++
 libs/baselibc/LICENSE                           |  133 --
 libs/baselibc/Makefile                          |   46 -
 libs/baselibc/README.md                         |    6 -
 libs/baselibc/include/assert.h                  |   28 -
 libs/baselibc/include/ctype.h                   |   86 -
 libs/baselibc/include/inttypes.h                |  229 ---
 libs/baselibc/include/klibc/extern.h            |   16 -
 libs/baselibc/include/klibc/inline.h            |   12 -
 libs/baselibc/include/stdio.h                   |  124 --
 libs/baselibc/include/stdlib.h                  |  101 -
 libs/baselibc/include/string.h                  |   59 -
 libs/baselibc/pkg.yml                           |   28 -
 libs/baselibc/src/asprintf.c                    |   30 -
 libs/baselibc/src/atoi.c                        |    3 -
 libs/baselibc/src/atol.c                        |    3 -
 libs/baselibc/src/atoll.c                       |    3 -
 .../baselibc_test/printf_tests.c.donotcompile   |   22 -
 .../src/baselibc_test/tests_glue.c.donotcompile |   33 -
 libs/baselibc/src/baselibc_test/unittests.h     |   36 -
 libs/baselibc/src/bsearch.c                     |   26 -
 libs/baselibc/src/bzero.c                       |    6 -
 libs/baselibc/src/calloc.c                      |   20 -
 libs/baselibc/src/fgets.c                       |   31 -
 libs/baselibc/src/inline.c                      |    5 -
 libs/baselibc/src/jrand48.c                     |   24 -
 libs/baselibc/src/lrand48.c                     |   13 -
 libs/baselibc/src/malloc.c                      |  274 ---
 libs/baselibc/src/malloc.h                      |   43 -
 libs/baselibc/src/memccpy.c                     |   23 -
 libs/baselibc/src/memchr.c                      |   19 -
 libs/baselibc/src/memcmp.c                      |   19 -
 libs/baselibc/src/memcpy.c                      |   29 -
 libs/baselibc/src/memfile.c                     |   33 -
 libs/baselibc/src/memmem.c                      |   52 -
 libs/baselibc/src/memmove.c                     |   36 -
 libs/baselibc/src/memrchr.c                     |   19 -
 libs/baselibc/src/memset.c                      |   30 -
 libs/baselibc/src/memswap.c                     |   24 -
 libs/baselibc/src/mrand48.c                     |   13 -
 libs/baselibc/src/mynewt.c                      |   47 -
 libs/baselibc/src/nrand48.c                     |   11 -
 libs/baselibc/src/qsort.c                       |   46 -
 libs/baselibc/src/realloc.c                     |   50 -
 libs/baselibc/src/sprintf.c                     |   18 -
 libs/baselibc/src/srand48.c                     |   15 -
 libs/baselibc/src/sscanf.c                      |   17 -
 libs/baselibc/src/strcasecmp.c                  |   24 -
 libs/baselibc/src/strcat.c                      |   11 -
 libs/baselibc/src/strchr.c                      |   17 -
 libs/baselibc/src/strcmp.c                      |   21 -
 libs/baselibc/src/strcpy.c                      |   20 -
 libs/baselibc/src/strcspn.c                     |   51 -
 libs/baselibc/src/strdup.c                      |   17 -
 libs/baselibc/src/strlcat.c                     |   30 -
 libs/baselibc/src/strlcpy.c                     |   26 -
 libs/baselibc/src/strlen.c                      |   13 -
 libs/baselibc/src/strncasecmp.c                 |   24 -
 libs/baselibc/src/strncat.c                     |   21 -
 libs/baselibc/src/strncmp.c                     |   21 -
 libs/baselibc/src/strncpy.c                     |   24 -
 libs/baselibc/src/strndup.c                     |   19 -
 libs/baselibc/src/strnlen.c                     |   18 -
 libs/baselibc/src/strntoimax.c                  |   13 -
 libs/baselibc/src/strntoumax.c                  |   77 -
 libs/baselibc/src/strpbrk.c                     |   55 -
 libs/baselibc/src/strrchr.c                     |   19 -
 libs/baselibc/src/strsep.c                      |   21 -
 libs/baselibc/src/strspn.c                      |   56 -
 libs/baselibc/src/strstr.c                      |   11 -
 libs/baselibc/src/strtoimax.c                   |    3 -
 libs/baselibc/src/strtok.c                      |   12 -
 libs/baselibc/src/strtok_r.c                    |   13 -
 libs/baselibc/src/strtol.c                      |    3 -
 libs/baselibc/src/strtoll.c                     |    3 -
 libs/baselibc/src/strtoul.c                     |    3 -
 libs/baselibc/src/strtoull.c                    |    3 -
 libs/baselibc/src/strtoumax.c                   |    3 -
 libs/baselibc/src/templates/atox.c.template     |   14 -
 libs/baselibc/src/templates/strtox.c.template   |   14 -
 libs/baselibc/src/tinyprintf.c                  |  362 ----
 libs/baselibc/src/vasprintf.c                   |   25 -
 libs/baselibc/src/vprintf.c                     |   11 -
 libs/baselibc/src/vsprintf.c                    |   11 -
 libs/baselibc/src/vsscanf.c                     |  400 ----
 libs/bleuart/include/bleuart/bleuart.h          |   34 -
 libs/bleuart/pkg.yml                            |   42 -
 libs/bleuart/src/bleuart.c                      |  201 --
 .../include/boot_serial/boot_serial.h           |   33 -
 libs/boot_serial/pkg.yml                        |   35 -
 libs/boot_serial/src/boot_serial.c              |  403 ----
 libs/boot_serial/src/boot_serial_priv.h         |   61 -
 libs/boot_serial/test/pkg.yml                   |   33 -
 libs/boot_serial/test/src/boot_test.c           |  231 ---
 libs/bootutil/design.txt                        |  413 ----
 libs/bootutil/include/bootutil/bootutil_misc.h  |   28 -
 libs/bootutil/include/bootutil/bootutil_test.h  |   25 -
 libs/bootutil/include/bootutil/image.h          |   89 -
 libs/bootutil/include/bootutil/loader.h         |   84 -
 libs/bootutil/include/bootutil/sign_key.h       |   33 -
 libs/bootutil/pkg.yml                           |   41 -
 libs/bootutil/signed_images.md                  |   91 -
 libs/bootutil/src/bootutil_misc.c               |  319 ----
 libs/bootutil/src/bootutil_priv.h               |   75 -
 libs/bootutil/src/image_ec.c                    |  121 --
 libs/bootutil/src/image_rsa.c                   |  144 --
 libs/bootutil/src/image_validate.c              |  198 --
 libs/bootutil/src/loader.c                      |  652 -------
 libs/bootutil/test/pkg.yml                      |   30 -
 libs/bootutil/test/src/boot_test.c              | 1169 ------------
 libs/cmsis-core/pkg.yml                         |   27 -
 libs/cmsis-core/src/cmsis_nvic.c                |   73 -
 libs/cmsis-core/src/ext/core_ca9.h              |  271 ---
 libs/cmsis-core/src/ext/core_caFunc.h           | 1161 ------------
 libs/cmsis-core/src/ext/core_caInstr.h          |   45 -
 libs/cmsis-core/src/ext/core_ca_mmu.h           |  848 ---------
 libs/cmsis-core/src/ext/core_cm0.h              |  682 -------
 libs/cmsis-core/src/ext/core_cm0plus.h          |  793 --------
 libs/cmsis-core/src/ext/core_cm3.h              | 1627 ----------------
 libs/cmsis-core/src/ext/core_cm4.h              | 1772 ------------------
 libs/cmsis-core/src/ext/core_cm4_simd.h         |  673 -------
 libs/cmsis-core/src/ext/core_cmFunc.h           |  636 -------
 libs/cmsis-core/src/ext/core_cmInstr.h          |  688 -------
 libs/console/README.md                          |   33 -
 libs/console/full/include/console/console.h     |   38 -
 libs/console/full/include/console/prompt.h      |   33 -
 libs/console/full/pkg.yml                       |   44 -
 libs/console/full/src/cons_fmt.c                |   77 -
 libs/console/full/src/cons_tty.c                |  561 ------
 libs/console/full/src/prompt.c                  |   49 -
 libs/console/stub/include/console/console.h     |   71 -
 libs/console/stub/include/console/prompt.h      |   35 -
 libs/console/stub/pkg.yml                       |   27 -
 libs/crash_test/include/crash_test/crash_test.h |   27 -
 libs/crash_test/pkg.yml                         |   42 -
 libs/crash_test/src/crash_cli.c                 |   49 -
 libs/crash_test/src/crash_nmgr.c                |   75 -
 libs/crash_test/src/crash_test.c                |   72 -
 libs/crash_test/src/crash_test_priv.h           |   31 -
 libs/elua/README.md                             |    7 -
 libs/elua/elua_base/LICENSE                     |   62 -
 libs/elua/elua_base/LICENSE.luarpc              |   32 -
 libs/elua/elua_base/include/elua_base/elua.h    |   27 -
 libs/elua/elua_base/pkg.yml                     |   50 -
 libs/elua/elua_base/src/lapi.c                  | 1161 ------------
 libs/elua/elua_base/src/lapi.h                  |   16 -
 libs/elua/elua_base/src/lauxlib.c               |  867 ---------
 libs/elua/elua_base/src/lauxlib.h               |  179 --
 libs/elua/elua_base/src/lbaselib.c              |  718 -------
 libs/elua/elua_base/src/lcode.c                 |  831 --------
 libs/elua/elua_base/src/lcode.h                 |   76 -
 libs/elua/elua_base/src/ldblib.c                |  397 ----
 libs/elua/elua_base/src/ldebug.c                |  649 -------
 libs/elua/elua_base/src/ldebug.h                |   33 -
 libs/elua/elua_base/src/ldo.c                   |  537 ------
 libs/elua/elua_base/src/ldo.h                   |   57 -
 libs/elua/elua_base/src/ldump.c                 |  321 ----
 libs/elua/elua_base/src/legc.c                  |   12 -
 libs/elua/elua_base/src/legc.h                  |   17 -
 libs/elua/elua_base/src/lfunc.c                 |  176 --
 libs/elua/elua_base/src/lfunc.h                 |   37 -
 libs/elua/elua_base/src/lgc.c                   |  743 --------
 libs/elua/elua_base/src/lgc.h                   |  136 --
 libs/elua/elua_base/src/linit.c                 |  154 --
 libs/elua/elua_base/src/liolib.c.donotcompile   |  619 ------
 libs/elua/elua_base/src/llex.c                  |  458 -----
 libs/elua/elua_base/src/llex.h                  |   81 -
 libs/elua/elua_base/src/llimits.h               |  128 --
 libs/elua/elua_base/src/lmathlib.c              |  395 ----
 libs/elua/elua_base/src/lmem.c                  |   86 -
 libs/elua/elua_base/src/lmem.h                  |   49 -
 libs/elua/elua_base/src/lmynewt.c               |   56 -
 libs/elua/elua_base/src/loadlib.c.donotcompile  |  684 -------
 libs/elua/elua_base/src/lobject.c               |  216 ---
 libs/elua/elua_base/src/lobject.h               |  557 ------
 libs/elua/elua_base/src/lopcodes.c              |  102 -
 libs/elua/elua_base/src/lopcodes.h              |  268 ---
 libs/elua/elua_base/src/loslib.c.donotcompile   |  247 ---
 libs/elua/elua_base/src/lparser.c               | 1345 -------------
 libs/elua/elua_base/src/lparser.h               |   82 -
 libs/elua/elua_base/src/lrodefs.h               |   34 -
 libs/elua/elua_base/src/lrotable.c              |  134 --
 libs/elua/elua_base/src/lrotable.h              |   77 -
 libs/elua/elua_base/src/lstate.c                |  258 ---
 libs/elua/elua_base/src/lstate.h                |  171 --
 libs/elua/elua_base/src/lstring.c               |  147 --
 libs/elua/elua_base/src/lstring.h               |   34 -
 libs/elua/elua_base/src/lstrlib.c               |  893 ---------
 libs/elua/elua_base/src/ltable.c                |  759 --------
 libs/elua/elua_base/src/ltable.h                |   44 -
 libs/elua/elua_base/src/ltablib.c               |  287 ---
 libs/elua/elua_base/src/ltm.c                   |   84 -
 libs/elua/elua_base/src/ltm.h                   |   54 -
 libs/elua/elua_base/src/lua.c                   |  420 -----
 libs/elua/elua_base/src/lua.h                   |  399 ----
 libs/elua/elua_base/src/luac.c.donotcompile     |  242 ---
 libs/elua/elua_base/src/luaconf.h               |  891 ---------
 libs/elua/elua_base/src/lualib.h                |   53 -
 libs/elua/elua_base/src/lundump.c               |  336 ----
 libs/elua/elua_base/src/lundump.h               |   60 -
 libs/elua/elua_base/src/lvm.c                   |  825 --------
 libs/elua/elua_base/src/lvm.h                   |   36 -
 libs/elua/elua_base/src/lzio.c                  |   85 -
 libs/elua/elua_base/src/lzio.h                  |   72 -
 libs/elua/elua_base/src/print.c.donotcompile    |  227 ---
 libs/flash_test/include/flash_test/flash_test.h |   27 -
 libs/flash_test/pkg.yml                         |   30 -
 libs/flash_test/src/flash_test/flash_test.c     |  155 --
 libs/imgmgr/pkg.yml                             |    6 +-
 libs/imgmgr/src/imgmgr.c                        |    2 +-
 libs/imgmgr/src/imgmgr_boot.c                   |    2 +-
 libs/imgmgr/src/imgmgr_cli.c                    |    2 +-
 libs/imgmgr/src/imgmgr_coredump.c               |    2 +-
 libs/imgmgr/src/imgmgr_fs.c                     |    2 +-
 libs/iotivity/pkg.yml                           |    8 +-
 libs/json/MSJSON_COPYING                        |   28 -
 libs/json/include/json/json.h                   |  245 ---
 libs/json/pkg.yml                               |   26 -
 libs/json/src/json_decode.c                     |  670 -------
 libs/json/src/json_encode.c                     |  248 ---
 libs/json/test/pkg.yml                          |   30 -
 libs/json/test/src/test_json.c                  |   43 -
 libs/json/test/src/test_json.h                  |   27 -
 libs/json/test/src/test_json_simple.c           |  360 ----
 libs/newtmgr/nmgr_os/pkg.yml                    |    6 +-
 libs/newtmgr/pkg.yml                            |    6 +-
 libs/newtmgr/transport/ble/pkg.yml              |    2 +-
 libs/newtmgr_oic/pkg.yml                        |    8 +-
 libs/os/include/os/arch/cortex_m0/os/os_arch.h  |   74 -
 libs/os/include/os/arch/cortex_m4/os/os_arch.h  |   75 -
 libs/os/include/os/arch/sim/os/os_arch.h        |   74 -
 libs/os/include/os/endian.h                     |   92 -
 libs/os/include/os/os.h                         |  101 -
 libs/os/include/os/os_callout.h                 |   60 -
 libs/os/include/os/os_cfg.h                     |   25 -
 libs/os/include/os/os_dev.h                     |  114 --
 libs/os/include/os/os_eventq.h                  |   51 -
 libs/os/include/os/os_heap.h                    |   30 -
 libs/os/include/os/os_malloc.h                  |   34 -
 libs/os/include/os/os_mbuf.h                    |  297 ---
 libs/os/include/os/os_mempool.h                 |   94 -
 libs/os/include/os/os_mutex.h                   |   59 -
 libs/os/include/os/os_sanity.h                  |   56 -
 libs/os/include/os/os_sched.h                   |   37 -
 libs/os/include/os/os_sem.h                     |   52 -
 libs/os/include/os/os_task.h                    |  114 --
 libs/os/include/os/os_test.h                    |   25 -
 libs/os/include/os/os_time.h                    |  111 --
 libs/os/include/os/queue.h                      |  514 -----
 libs/os/pkg.yml                                 |   84 -
 libs/os/src/arch/cortex_m0/m0/HAL_CM0.s         |  277 ---
 libs/os/src/arch/cortex_m0/m0/SVC_Table.s       |   56 -
 libs/os/src/arch/cortex_m0/os_arch_arm.c        |  333 ----
 libs/os/src/arch/cortex_m0/os_fault.c           |  158 --
 libs/os/src/arch/cortex_m4/m4/HAL_CM4.s         |  224 ---
 libs/os/src/arch/cortex_m4/m4/SVC_Table.s       |   56 -
 libs/os/src/arch/cortex_m4/os_arch_arm.c        |  328 ----
 libs/os/src/arch/cortex_m4/os_fault.c           |  160 --
 libs/os/src/arch/sim/os_arch_sim.c              |  462 -----
 libs/os/src/arch/sim/os_arch_stack_frame.s      |  101 -
 libs/os/src/arch/sim/os_fault.c                 |   34 -
 libs/os/src/os.c                                |  191 --
 libs/os/src/os_callout.c                        |  200 --
 libs/os/src/os_dev.c                            |  309 ---
 libs/os/src/os_eventq.c                         |  235 ---
 libs/os/src/os_heap.c                           |  106 --
 libs/os/src/os_mbuf.c                           | 1270 -------------
 libs/os/src/os_mempool.c                        |  233 ---
 libs/os/src/os_msys_init.c                      |  147 --
 libs/os/src/os_mutex.c                          |  236 ---
 libs/os/src/os_priv.h                           |   38 -
 libs/os/src/os_sanity.c                         |  238 ---
 libs/os/src/os_sched.c                          |  330 ----
 libs/os/src/os_sem.c                            |  212 ---
 libs/os/src/os_task.c                           |  216 ---
 libs/os/src/os_time.c                           |  248 ---
 libs/os/test/pkg.yml                            |   30 -
 .../test/src/arch/cortex_m4/os_test_arch_arm.c  |   27 -
 libs/os/test/src/arch/sim/os_test_arch_sim.c    |   52 -
 libs/os/test/src/callout_test.c                 |  330 ----
 libs/os/test/src/eventq_test.c                  |  416 ----
 libs/os/test/src/mbuf_test.c                    |  420 -----
 libs/os/test/src/mempool_test.c                 |  227 ---
 libs/os/test/src/mutex_test.c                   |  407 ----
 libs/os/test/src/os_test.c                      |   53 -
 libs/os/test/src/os_test_priv.h                 |   32 -
 libs/os/test/src/sem_test.c                     |  401 ----
 libs/shell/include/shell/shell.h                |   48 -
 libs/shell/include/shell/shell_prompt.h         |   25 -
 libs/shell/pkg.yml                              |   48 -
 libs/shell/src/shell.c                          |  579 ------
 libs/shell/src/shell_os.c                       |  156 --
 libs/shell/src/shell_priv.h                     |   27 -
 libs/shell/src/shell_prompt.c                   |   69 -
 libs/split/README.md                            |   63 -
 libs/split/include/split/split.h                |   57 -
 libs/split/include/split/split_priv.h           |   30 -
 libs/split/pkg.yml                              |   30 -
 libs/split/src/split.c                          |   77 -
 libs/split/src/split_config.c                   |   95 -
 libs/split/src/split_netmgr.c                   |  149 --
 libs/testreport/include/testreport/testreport.h |   34 -
 libs/testreport/pkg.yml                         |   30 -
 libs/testreport/src/arch/cortex_m4/io.c         |   91 -
 libs/testreport/src/arch/sim/io.c               |  140 --
 libs/testreport/src/results.c                   |  190 --
 libs/testreport/src/testreport.c                |  131 --
 libs/testreport/src/testreport_priv.h           |   48 -
 libs/testutil/design.txt                        |  476 -----
 libs/testutil/include/testutil/testutil.h       |  174 --
 libs/testutil/pkg.yml                           |   30 -
 .../src/arch/cortex_m4/testutil_arch_arm.c      |   27 -
 libs/testutil/src/arch/sim/testutil_arch_sim.c  |   30 -
 libs/testutil/src/arch/sim/tu_args.c            |   23 -
 libs/testutil/src/case.c                        |  255 ---
 libs/testutil/src/suite.c                       |   67 -
 libs/testutil/src/testutil.c                    |   50 -
 libs/testutil/src/testutil_priv.h               |   34 -
 libs/tinycbor/include/tinycbor/assert_p.h       |   29 -
 libs/tinycbor/include/tinycbor/cbor.h           |  479 -----
 .../tinycbor/include/tinycbor/cborconstants_p.h |   52 -
 libs/tinycbor/include/tinycbor/cborjson.h       |   62 -
 .../include/tinycbor/compilersupport_p.h        |  218 ---
 .../include/tinycbor/extract_number_p.h         |   78 -
 libs/tinycbor/include/tinycbor/math_support_p.h |   47 -
 libs/tinycbor/pkg.yml                           |   26 -
 libs/tinycbor/src/cborencoder.c                 |  629 -------
 .../src/cborencoder_close_container_checked.c   |   82 -
 libs/tinycbor/src/cborerrorstrings.c            |  165 --
 libs/tinycbor/src/cborparser.c                  | 1293 -------------
 libs/tinycbor/src/cborparser_dup_string.c       |  113 --
 libs/tinycbor/src/cborpretty.c                  |  470 -----
 libs/tinycbor/src/cbortojson.c                  |  686 -------
 libs/tinycbor/src/open_memstream.c              |  117 --
 libs/util/include/util/base64.h                 |   32 -
 libs/util/include/util/crc16.h                  |   36 -
 libs/util/include/util/crc8.h                   |   32 -
 libs/util/include/util/hex.h                    |   25 -
 libs/util/include/util/tpq.h                    |   67 -
 libs/util/pkg.yml                               |    2 +-
 libs/util/src/base64.c                          |  181 --
 libs/util/src/crc16.c                           |   83 -
 libs/util/src/crc8.c                            |   74 -
 libs/util/src/hex.c                             |  101 -
 libs/util/src/tpq.c                             |   88 -
 net/ip/inet_def_service/pkg.yml                 |    4 +-
 .../include/mn_socket/arch/sim/native_sock.h    |   25 +
 net/ip/mn_socket/include/mn_socket/mn_socket.h  |  218 +++
 .../mn_socket/include/mn_socket/mn_socket_ops.h |   85 +
 net/ip/mn_socket/pkg.yml                        |   30 +
 net/ip/mn_socket/src/arch/sim/native_itf.c      |  212 +++
 net/ip/mn_socket/src/arch/sim/native_sock.c     |  753 ++++++++
 .../mn_socket/src/arch/sim/native_sock_priv.h   |   32 +
 net/ip/mn_socket/src/mn_socket.c                |  138 ++
 net/ip/mn_socket/src/mn_socket_aconv.c          |   98 +
 net/ip/mn_socket/test/pkg.yml                   |   30 +
 net/ip/mn_socket/test/src/mn_sock_test.c        |  895 +++++++++
 net/nimble/controller/pkg.yml                   |    2 +-
 net/nimble/host/pkg.yml                         |    2 +-
 .../services/bleuart/include/bleuart/bleuart.h  |   34 +
 net/nimble/host/services/bleuart/pkg.yml        |   42 +
 net/nimble/host/services/bleuart/src/bleuart.c  |  201 ++
 net/nimble/host/src/ble_hs.c                    |    5 +-
 net/nimble/pkg.yml                              |    2 +-
 net/nimble/transport/ram/pkg.yml                |    2 +-
 net/nimble/transport/uart/pkg.yml               |    2 +-
 net/wifi/wifi_mgmt/pkg.yml                      |    2 +-
 sys/config/pkg.yml                              |    6 +-
 sys/config/src/config.c                         |    2 +-
 sys/console/README.md                           |   33 +
 sys/console/full/include/console/console.h      |   38 +
 sys/console/full/include/console/prompt.h       |   33 +
 sys/console/full/pkg.yml                        |   44 +
 sys/console/full/src/cons_fmt.c                 |   77 +
 sys/console/full/src/cons_tty.c                 |  561 ++++++
 sys/console/full/src/prompt.c                   |   49 +
 sys/console/stub/include/console/console.h      |   71 +
 sys/console/stub/include/console/prompt.h       |   35 +
 sys/console/stub/pkg.yml                        |   27 +
 sys/coredump/pkg.yml                            |    2 +-
 sys/fcb/README.md                               |   58 -
 sys/fcb/include/fcb/fcb.h                       |  134 --
 sys/fcb/pkg.yml                                 |   28 -
 sys/fcb/src/fcb.c                               |  258 ---
 sys/fcb/src/fcb_append.c                        |  143 --
 sys/fcb/src/fcb_elem_info.c                     |  101 -
 sys/fcb/src/fcb_getnext.c                       |  132 --
 sys/fcb/src/fcb_priv.h                          |   57 -
 sys/fcb/src/fcb_rotate.c                        |   56 -
 sys/fcb/src/fcb_walk.c                          |   53 -
 sys/fcb/test/pkg.yml                            |   30 -
 sys/fcb/test/src/fcb_test.c                     |  672 -------
 sys/id/pkg.yml                                  |    5 +-
 sys/id/src/id.c                                 |    2 +-
 sys/log/pkg.yml                                 |    6 +-
 .../include/mn_socket/arch/sim/native_sock.h    |   25 -
 sys/mn_socket/include/mn_socket/mn_socket.h     |  218 ---
 sys/mn_socket/include/mn_socket/mn_socket_ops.h |   85 -
 sys/mn_socket/pkg.yml                           |   30 -
 sys/mn_socket/src/arch/sim/native_itf.c         |  212 ---
 sys/mn_socket/src/arch/sim/native_sock.c        |  753 --------
 sys/mn_socket/src/arch/sim/native_sock_priv.h   |   32 -
 sys/mn_socket/src/mn_socket.c                   |  138 --
 sys/mn_socket/src/mn_socket_aconv.c             |   98 -
 sys/mn_socket/test/pkg.yml                      |   30 -
 sys/mn_socket/test/src/mn_sock_test.c           |  895 ---------
 sys/reboot/pkg.yml                              |    4 +-
 sys/shell/include/shell/shell.h                 |   48 +
 sys/shell/include/shell/shell_prompt.h          |   25 +
 sys/shell/pkg.yml                               |   50 +
 sys/shell/src/shell.c                           |  579 ++++++
 sys/shell/src/shell_os.c                        |  156 ++
 sys/shell/src/shell_priv.h                      |   27 +
 sys/shell/src/shell_prompt.c                    |   69 +
 sys/stats/pkg.yml                               |    4 +-
 sys/sysinit/pkg.yml                             |    2 +-
 test/crash_test/include/crash_test/crash_test.h |   27 +
 test/crash_test/pkg.yml                         |   42 +
 test/crash_test/src/crash_cli.c                 |   49 +
 test/crash_test/src/crash_nmgr.c                |   75 +
 test/crash_test/src/crash_test.c                |   72 +
 test/crash_test/src/crash_test_priv.h           |   31 +
 test/flash_test/include/flash_test/flash_test.h |   27 +
 test/flash_test/pkg.yml                         |   30 +
 test/flash_test/src/flash_test/flash_test.c     |  155 ++
 test/testreport/include/testreport/testreport.h |   34 +
 test/testreport/pkg.yml                         |   30 +
 test/testreport/src/arch/cortex_m4/io.c         |   91 +
 test/testreport/src/arch/sim/io.c               |  140 ++
 test/testreport/src/results.c                   |  190 ++
 test/testreport/src/testreport.c                |  131 ++
 test/testreport/src/testreport_priv.h           |   48 +
 test/testutil/design.txt                        |  476 +++++
 test/testutil/include/testutil/testutil.h       |  174 ++
 test/testutil/pkg.yml                           |   30 +
 .../src/arch/cortex_m4/testutil_arch_arm.c      |   27 +
 test/testutil/src/arch/sim/testutil_arch_sim.c  |   30 +
 test/testutil/src/arch/sim/tu_args.c            |   23 +
 test/testutil/src/case.c                        |  255 +++
 test/testutil/src/suite.c                       |   67 +
 test/testutil/src/testutil.c                    |   50 +
 test/testutil/src/testutil_priv.h               |   34 +
 726 files changed, 45582 insertions(+), 65200 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/apps/blecent/pkg.yml
----------------------------------------------------------------------
diff --git a/apps/blecent/pkg.yml b/apps/blecent/pkg.yml
index d0b91cb..f90ca57 100644
--- a/apps/blecent/pkg.yml
+++ b/apps/blecent/pkg.yml
@@ -23,7 +23,7 @@ pkg.homepage: "http://mynewt.apache.org/"
 pkg.keywords:
 
 pkg.deps: 
-    - libs/os 
+    - kernel/os 
     - sys/log
     - net/nimble/controller
     - net/nimble/host
@@ -31,8 +31,8 @@ pkg.deps:
     - net/nimble/host/services/gatt
     - net/nimble/host/store/ram
     - net/nimble/transport/ram
-    - libs/console/full
-    - libs/baselibc
+    - sys/console/full
+    - libc/baselibc
 
 pkg.syscfg_vals:
     # DEBUG logging is a bit noisy; use INFO.

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/apps/blehci/pkg.yml
----------------------------------------------------------------------
diff --git a/apps/blehci/pkg.yml b/apps/blehci/pkg.yml
index 198e395..975d779 100644
--- a/apps/blehci/pkg.yml
+++ b/apps/blehci/pkg.yml
@@ -23,8 +23,8 @@ pkg.homepage: "http://mynewt.apache.org/"
 pkg.keywords:
 
 pkg.deps:
-    - libs/baselibc
-    - libs/console/stub
-    - libs/os
+    - libc/baselibc
+    - sys/console/stub
+    - kernel/os
     - net/nimble/controller
     - net/nimble/transport/uart

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/apps/bleprph/pkg.yml
----------------------------------------------------------------------
diff --git a/apps/bleprph/pkg.yml b/apps/bleprph/pkg.yml
index 4e15338..409f46c 100644
--- a/apps/bleprph/pkg.yml
+++ b/apps/bleprph/pkg.yml
@@ -23,7 +23,7 @@ pkg.homepage: "http://mynewt.apache.org/"
 pkg.keywords:
 
 pkg.deps: 
-    - libs/os 
+    - kernel/os 
     - sys/log
     - net/nimble/controller
     - net/nimble/host
@@ -31,8 +31,8 @@ pkg.deps:
     - net/nimble/host/services/gatt
     - net/nimble/host/store/ram
     - net/nimble/transport/ram
-    - libs/console/full
-    - libs/baselibc
+    - sys/console/full
+    - libc/baselibc
     - libs/newtmgr
     - libs/newtmgr/transport/ble
     - sys/sysinit

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/apps/bletest/pkg.yml
----------------------------------------------------------------------
diff --git a/apps/bletest/pkg.yml b/apps/bletest/pkg.yml
index 9068192..b17321e 100644
--- a/apps/bletest/pkg.yml
+++ b/apps/bletest/pkg.yml
@@ -28,9 +28,9 @@ pkg.deps:
     - net/nimble/controller
     - net/nimble/host
     - net/nimble/transport/ram
-    - libs/os 
-    - libs/console/full
-    - libs/shell
+    - kernel/os 
+    - sys/console/full
+    - sys/shell
     - libs/imgmgr
     - libs/newtmgr
     - sys/config

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/apps/bletiny/pkg.yml
----------------------------------------------------------------------
diff --git a/apps/bletiny/pkg.yml b/apps/bletiny/pkg.yml
index 465edc4..ce68b37 100644
--- a/apps/bletiny/pkg.yml
+++ b/apps/bletiny/pkg.yml
@@ -23,7 +23,7 @@ pkg.homepage: "http://mynewt.apache.org/"
 pkg.keywords:
 
 pkg.deps: 
-    - libs/os 
+    - kernel/os 
     - sys/log
     - net/nimble/controller
     - net/nimble/host
@@ -31,8 +31,8 @@ pkg.deps:
     - net/nimble/host/services/gatt
     - net/nimble/host/store/ram
     - net/nimble/transport/ram
-    - libs/console/full
-    - libs/shell
+    - sys/console/full
+    - sys/shell
 
 ### Disable some features to make bletiny small enough to fit on the nRF51.
 ### These features can be re-enabled in the target definition.

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/apps/bleuart/pkg.yml
----------------------------------------------------------------------
diff --git a/apps/bleuart/pkg.yml b/apps/bleuart/pkg.yml
index 84abb2c..c4b731c 100644
--- a/apps/bleuart/pkg.yml
+++ b/apps/bleuart/pkg.yml
@@ -23,7 +23,7 @@ pkg.homepage: "http://mynewt.apache.org/"
 pkg.keywords:
 
 pkg.deps:
-    - libs/os
+    - kernel/os
     - sys/log
     - net/nimble/controller
     - net/nimble/host
@@ -31,11 +31,11 @@ pkg.deps:
     - net/nimble/host/services/gatt
     - net/nimble/host/store/ram
     - net/nimble/transport/ram
-    - libs/console/full
-    - libs/baselibc
+    - sys/console/full
+    - libc/baselibc
     - libs/newtmgr
     - libs/newtmgr/transport/ble
-    - libs/bleuart
+    - net/nimble/host/services/bleuart
 
 pkg.syscfg_vals:
     # Disable unused roles; bleuart is a peripheral-only app.

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/apps/blinky/pkg.yml
----------------------------------------------------------------------
diff --git a/apps/blinky/pkg.yml b/apps/blinky/pkg.yml
index a63becb..3b536cf 100644
--- a/apps/blinky/pkg.yml
+++ b/apps/blinky/pkg.yml
@@ -25,10 +25,10 @@ pkg.homepage: "http://mynewt.apache.org/"
 pkg.keywords:
 
 pkg.deps:
-    - libs/console/full
+    - sys/console/full
     - libs/newtmgr
-    - libs/os
-    - libs/shell
+    - kernel/os
+    - sys/shell
     - sys/config
     - sys/log
     - sys/stats

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/apps/boot/pkg.yml
----------------------------------------------------------------------
diff --git a/apps/boot/pkg.yml b/apps/boot/pkg.yml
index e2112a9..f97ad59 100644
--- a/apps/boot/pkg.yml
+++ b/apps/boot/pkg.yml
@@ -26,14 +26,14 @@ pkg.keywords:
     - loader
 
 pkg.deps:
-    - libs/bootutil
-    - libs/os
+    - boot/bootutil
+    - kernel/os
     - libs/util
-    - libs/console/stub
+    - sys/console/stub
 
 pkg.deps.BOOT_SERIAL.OVERWRITE:
-    - libs/console/full
-    - libs/boot_serial
+    - sys/console/full
+    - boot/boot_serial
 
 pkg.syscfg_defs:
     BOOT_LOADER:

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/apps/ffs2native/pkg.yml
----------------------------------------------------------------------
diff --git a/apps/ffs2native/pkg.yml b/apps/ffs2native/pkg.yml
index 0644425..0825d3c 100644
--- a/apps/ffs2native/pkg.yml
+++ b/apps/ffs2native/pkg.yml
@@ -27,5 +27,5 @@ pkg.keywords:
 pkg.deps:
     - fs/nffs
     - hw/hal
-    - libs/console/full
-    - libs/os
+    - sys/console/full
+    - kernel/os

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/apps/luatest/pkg.yml
----------------------------------------------------------------------
diff --git a/apps/luatest/pkg.yml b/apps/luatest/pkg.yml
deleted file mode 100644
index b56be6b..0000000
--- a/apps/luatest/pkg.yml
+++ /dev/null
@@ -1,31 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you 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.
-#
-pkg.name: apps/luatest
-pkg.type: app
-pkg.description: Simple project for testing Lua scripting.
-pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
-pkg.homepage: "http://mynewt.apache.org/"
-pkg.keywords:
-
-pkg.deps:
-     - fs/nffs
-     - libs/os
-     - libs/elua/elua_base
-     - libs/console/full
-     - libs/shell
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/apps/luatest/src/main.c
----------------------------------------------------------------------
diff --git a/apps/luatest/src/main.c b/apps/luatest/src/main.c
deleted file mode 100755
index f71cbe3..0000000
--- a/apps/luatest/src/main.c
+++ /dev/null
@@ -1,75 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include <assert.h>
-#include <string.h>
-#include "os/os.h"
-#include "bsp/bsp.h"
-#include "elua_base/elua.h"
-#include "fs/fs.h"
-#ifdef ARCH_sim
-#include "mcu/mcu_sim.h"
-#endif
-
-static void
-create_script_file(void)
-{
-    char filename[] = "/foobar";
-    char script[] = "print \"eat my shorts\"\n";
-    struct fs_file *nf;
-    int rc;
-
-    rc = fs_open(filename, FS_ACCESS_READ, &nf);
-    if (rc) {
-        rc = fs_open(filename, FS_ACCESS_WRITE, &nf);
-        assert(rc == 0);
-        rc = fs_write(nf, script, strlen(script));
-        assert(rc == 0);
-    }
-    fs_close(nf);
-}
-
-/**
- * main
- *
- * The main function for the project. This function initializes and starts the
- * OS.  We should not return from os start.
- *
- * @return int NOTE: this function should never return!
- */
-int
-main(int argc, char **argv)
-{
-#ifdef ARCH_sim
-    mcu_sim_parse_args(argc, argv);
-#endif
-
-    /* Initialize OS */
-    os_init();
-
-    create_script_file();
-
-    /* Start the OS */
-    os_start();
-
-    /* os start should never return. If it does, this should be an error */
-    assert(0);
-
-    return 0;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/apps/ocf_sample/pkg.yml
----------------------------------------------------------------------
diff --git a/apps/ocf_sample/pkg.yml b/apps/ocf_sample/pkg.yml
index 3abca7e..cb69117 100644
--- a/apps/ocf_sample/pkg.yml
+++ b/apps/ocf_sample/pkg.yml
@@ -25,14 +25,14 @@ pkg.homepage: "http://mynewt.apache.org/"
 pkg.keywords:
 
 pkg.deps:
-    - libs/os
+    - kernel/os
     - libs/util
     - sys/log
     - libs/iotivity
 
 pkg.deps.OC_TRANSPORT_SERIAL:
-    - libs/shell
-    - libs/console/full
+    - sys/shell
+    - sys/console/full
 
 pkg.deps.OC_TRANSPORT_GATT:
     - net/nimble/controller

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/apps/sblinky/pkg.yml
----------------------------------------------------------------------
diff --git a/apps/sblinky/pkg.yml b/apps/sblinky/pkg.yml
deleted file mode 100644
index 54f7508..0000000
--- a/apps/sblinky/pkg.yml
+++ /dev/null
@@ -1,36 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you 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.
-#
-
-pkg.name: apps/sblinky
-pkg.type: app
-pkg.description: Basic example application which blinks an LED.
-pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
-pkg.homepage: "http://mynewt.apache.org/"
-pkg.keywords:
-
-pkg.deps:
-    - libs/newtmgr
-    - hw/drivers/adc
-    - fs/nffs
-    - libs/console/full
-    - libs/os
-    - libs/shell
-    - sys/config
-    - sys/log
-    - sys/stats

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/apps/sblinky/src/main.c
----------------------------------------------------------------------
diff --git a/apps/sblinky/src/main.c b/apps/sblinky/src/main.c
deleted file mode 100755
index 2358c0d..0000000
--- a/apps/sblinky/src/main.c
+++ /dev/null
@@ -1,599 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-#include "os/os.h"
-#include "bsp/bsp.h"
-#include "hal/hal_gpio.h"
-#include "hal/hal_spi.h"
-#include "console/console.h"
-#include "shell/shell.h"
-#include "stats/stats.h"
-#include "config/config.h"
-#include <os/os_dev.h>
-#include <adc/adc.h>
-#include <assert.h>
-#include <string.h>
-#ifdef ARCH_sim
-#include <mcu/mcu_sim.h>
-#endif
-
-#ifdef NRF51
-#include "nrf.h"
-#include <adc_nrf51/adc_nrf51.h>
-#include "nrf_drv_adc.h"
-#include "app_util_platform.h"
-#include "app_error.h"
-nrf_drv_adc_config_t adc_config = NRF_DRV_ADC_DEFAULT_CONFIG;
-nrf_drv_adc_channel_t g_nrf_adc_chan =
-    NRF_DRV_ADC_DEFAULT_CHANNEL(NRF_ADC_CONFIG_INPUT_2);
-#endif
-
-#ifdef NRF52
-#include "nrf.h"
-#include <adc_nrf52/adc_nrf52.h>
-#include "nrf_drv_saadc.h"
-#include "app_util_platform.h"
-#include "app_error.h"
-nrf_drv_saadc_config_t adc_config = NRF_DRV_SAADC_DEFAULT_CONFIG;
-#endif
-
-#ifdef STM32F4
-#include "stm32f4xx_hal_dma.h"
-#include "stm32f4xx_hal_adc.h"
-#include <adc_stm32f4/adc_stm32f4.h>
-#endif
-
-#if defined(NRF52) || defined(NRF51)
-/* The spi txrx callback */
-struct sblinky_spi_cb_arg
-{
-    int transfers;
-    int txlen;
-    uint32_t tx_rx_bytes;
-};
-struct sblinky_spi_cb_arg spi_cb_obj;
-void *spi_cb_arg;
-#endif
-
-int g_result_mv;
-int g_result;
-
-/* Init all tasks */
-volatile int tasks_initialized;
-int init_tasks(void);
-
-/* Task 1 */
-#define TASK1_PRIO (1)
-#define TASK1_STACK_SIZE    OS_STACK_ALIGN(1024)
-struct os_task task1;
-os_stack_t stack1[TASK1_STACK_SIZE];
-static volatile int g_task1_loops;
-
-/* Task 2 */
-#define TASK2_PRIO (2)
-#define TASK2_STACK_SIZE    OS_STACK_ALIGN(1024)
-struct os_task task2;
-os_stack_t stack2[TASK2_STACK_SIZE];
-
-static volatile int g_task2_loops;
-
-/* Global test semaphore */
-struct os_sem g_test_sem;
-
-/* For LED toggling */
-int g_led_pin;
-
-#if MYNEWT_VAL(SPI_MASTER)
-uint8_t g_spi_tx_buf[32];
-uint8_t g_spi_rx_buf[32];
-
-void
-sblinky_spi_irqm_handler(void *arg, int len)
-{
-    struct sblinky_spi_cb_arg *cb;
-
-    hal_gpio_set(SPI0_CONFIG_CSN_PIN);
-
-    assert(arg == spi_cb_arg);
-    if (spi_cb_arg) {
-        cb = (struct sblinky_spi_cb_arg *)arg;
-        assert(len == cb->txlen);
-        ++cb->transfers;
-    }
-}
-
-#if 1
-static void
-sblinky_spi_tx_vals(int spi_num, uint8_t *buf, int len)
-{
-    int i;
-    int rc;
-    uint8_t *txptr;
-
-    /* Send all bytes in a loop */
-    txptr = buf;
-    for (i = 0; i < len; ++i) {
-        rc = hal_spi_tx_val(0, *txptr);
-        assert(rc != 0xFFFF);
-        ++txptr;
-    }
-}
-#endif
-#endif
-
-#if MYNEWT_VAL(SPI_SLAVE)
-uint8_t g_spi_tx_buf[32];
-uint8_t g_spi_rx_buf[32];
-
-/* XXX: This is an ugly hack for now. */
-#ifdef NRF51
-#define SPI_SLAVE_ID    (1)
-#else
-#define SPI_SLAVE_ID    (0)
-#endif
-
-void
-sblinky_spi_irqs_handler(void *arg, int len)
-{
-    struct sblinky_spi_cb_arg *cb;
-
-    assert(arg == spi_cb_arg);
-    if (spi_cb_arg) {
-        cb = (struct sblinky_spi_cb_arg *)arg;
-        ++cb->transfers;
-        cb->tx_rx_bytes += len;
-    }
-
-    /* Post semaphore to task waiting for SPI slave */
-    os_sem_release(&g_test_sem);
-}
-#endif
-
-void
-sblinky_spi_cfg(int spi_num)
-{
-    int spi_id = 0;
-    struct hal_spi_settings my_spi;
-
-#if MYNEWT_VAL(SPI_MASTER)
-    my_spi.spi_type = HAL_SPI_TYPE_MASTER;
-    my_spi.data_order = HAL_SPI_MSB_FIRST;
-    my_spi.data_mode = HAL_SPI_MODE0;
-    my_spi.baudrate = 8000;
-    my_spi.word_size = HAL_SPI_WORD_SIZE_8BIT;
-    my_spi.txrx_cb_func = NULL;
-    my_spi.txrx_cb_arg = NULL;
-    spi_id = 0;
-#endif
-
-#if MYNEWT_VAL(SPI_SLAVE)
-    my_spi.spi_type = HAL_SPI_TYPE_SLAVE;
-    my_spi.data_order = HAL_SPI_MSB_FIRST;
-    my_spi.data_mode = HAL_SPI_MODE0;
-    my_spi.baudrate = 0;
-    my_spi.word_size = HAL_SPI_WORD_SIZE_8BIT;
-    my_spi.txrx_cb_func = sblinky_spi_irqs_handler;
-    my_spi.txrx_cb_arg = spi_cb_arg;
-    spi_id = SPI_SLAVE_ID;
-#endif
-    hal_spi_config(spi_id, &my_spi);
-}
-
-#if 0
-#define SAADC_SAMPLES_IN_BUFFER (4)
-static nrf_saadc_value_t       m_buffer_pool[2][SAADC_SAMPLES_IN_BUFFER];
-
-int event_finished;
-int total_events;
-
-static void
-saadc_cb(const nrf_drv_saadc_evt_t *event)
-{
-    if (event->type == NRF_DRV_SAADC_EVT_DONE) {
-        ++event_finished;
-    }
-    ++total_events;
-}
-
-void
-saadc_test(void)
-{
-    ret_code_t rc;
-    nrf_saadc_channel_config_t cc =
-        NRF_DRV_SAADC_DEFAULT_CHANNEL_CONFIG_SE(NRF_SAADC_INPUT_AIN0);
-
-    rc = nrf_drv_saadc_init(NULL, saadc_cb);
-    APP_ERROR_CHECK(rc);
-    rc = nrf_drv_saadc_channel_init(0, &cc);
-    APP_ERROR_CHECK(rc);
-
-    rc = nrf_drv_saadc_buffer_convert(m_buffer_pool[0], SAADC_SAMPLES_IN_BUFFER);
-    APP_ERROR_CHECK(rc);
-
-    rc = nrf_drv_saadc_buffer_convert(m_buffer_pool[1], SAADC_SAMPLES_IN_BUFFER);
-    APP_ERROR_CHECK(rc);
-}
-#endif
-
-
-#define ADC_NUMBER_SAMPLES (16)
-#define ADC_NUMBER_CHANNELS (1)
-
-#if MYNEWT_VAL(ADC_3)
-
-#define STM32F4_ADC3_DEFAULT_CHAN_CFG {\
-    .Channel = ADC_CHANNEL_4,\
-    .Rank = 1,\
-    .SamplingTime = ADC_SAMPLETIME_144CYCLES,\
-    .Offset = 0\
-}
-
-ADC_ChannelConfTypeDef adc3_chan_cfg = STM32F4_ADC3_DEFAULT_CHAN_CFG;
-
-uint8_t *sample_buffer1;
-uint8_t *sample_buffer2;
-
-int adc3_result;
-int my_result_mv3[ADC_NUMBER_SAMPLES];
-
-int
-adc3_read_event(struct adc_dev *dev, void *arg, uint8_t etype,
-        void *buffer, int buffer_len)
-{
-    int i;
-    int rc;
-
-    for (i = 0; i < ADC_NUMBER_SAMPLES; i++) {
-        rc = adc_buf_read(dev, buffer, buffer_len, i, &adc3_result);
-        if (rc != 0) {
-            goto err;
-        }
-        my_result_mv3[i] = adc_result_mv(dev, ADC_CHANNEL_4, adc3_result);
-    }
-
-    adc_buf_release(dev, buffer, buffer_len);
-
-    return (0);
-err:
-    return (rc);
-}
-#endif
-
-#if MYNEWT_VAL(ADC_1)
-
-#define STM32F4_ADC1_DEFAULT_CHAN_CFG {\
-    .Channel = ADC_CHANNEL_10,\
-    .Rank = 1,\
-    .SamplingTime = ADC_SAMPLETIME_144CYCLES,\
-    .Offset = 0\
-}
-
-ADC_ChannelConfTypeDef adc1_chan_cfg = STM32F4_ADC1_DEFAULT_CHAN_CFG;
-
-int adc1_result;
-int my_result_mv1[ADC_NUMBER_SAMPLES];
-uint8_t *sample_buffer3;
-uint8_t *sample_buffer4;
-int
-adc1_read_event(struct adc_dev *dev, void *arg, uint8_t etype,
-        void *buffer, int buffer_len)
-{
-    int i;
-    int rc;
-
-    for (i = 0; i < ADC_NUMBER_SAMPLES; i++) {
-        rc = adc_buf_read(dev, buffer, buffer_len, i, &adc1_result);
-        if (rc != 0) {
-            goto err;
-        }
-        my_result_mv1[i] = adc_result_mv(dev, ADC_CHANNEL_10, adc1_result);
-    }
-
-    adc_buf_release(dev, buffer, buffer_len);
-
-    return (0);
-err:
-    return (rc);
-}
-#endif
-
-void
-task1_handler(void *arg)
-{
-    struct os_task *t;
-#if MYNEWT_VAL(ADC_3)
-    struct adc_dev *adc3;
-#endif
-#if MYNEWT_VAL(ADC_1)
-    struct adc_dev *adc1;
-#endif
-
-#if MYNEWT_VAL(SPI_MASTER)
-    int i;
-    uint8_t last_val;
-#endif
-
-#ifdef NRF52
-    nrf_saadc_channel_config_t cc =
-        NRF_DRV_SAADC_DEFAULT_CHANNEL_CONFIG_SE(NRF_SAADC_INPUT_AIN1);
-    cc.gain = NRF_SAADC_GAIN1_4;
-    cc.reference = NRF_SAADC_REFERENCE_VDD4;
-#endif
-
-    /* Set the led pin for the E407 devboard */
-    g_led_pin = LED_BLINK_PIN;
-    hal_gpio_init_out(g_led_pin, 1);
-
-#if MYNEWT_VAL(ADC_3)
-    adc3 = (struct adc_dev *) os_dev_open("adc3", 1, NULL);
-    assert(adc3 != NULL);
-#endif
-
-#if MYNEWT_VAL(ADC_1)
-    adc1 = (struct adc_dev *) os_dev_open("adc1", 1, NULL);
-    assert(adc1 != NULL);
-#endif
-
-#ifdef NRF51
-    adc_chan_config(adc3, 0, &g_nrf_adc_chan);
-#endif
-
-#ifdef NRF52
-    adc_chan_config(adc3, 0, &cc);
-#endif
-
-#ifdef STM32F4
-#if MYNEWT_VAL(ADC_3)
-    adc_chan_config(adc3, ADC_CHANNEL_4, &adc3_chan_cfg);
-#endif
-#if MYNEWT_VAL(ADC_1)
-    adc_chan_config(adc1, ADC_CHANNEL_10, &adc1_chan_cfg);
-#endif
-#endif
-
-#if MYNEWT_VAL(SPI_MASTER)
-    /* Use SS pin for testing */
-    hal_gpio_init_out(SPI0_CONFIG_CSN_PIN, 1);
-    sblinky_spi_cfg(0);
-    hal_spi_enable(0);
-
-#if 1
-    int rc;
-    /* Send some bytes in a non-blocking manner to SPI using tx val */
-    g_spi_tx_buf[0] = 0xde;
-    g_spi_tx_buf[1] = 0xad;
-    g_spi_tx_buf[2] = 0xbe;
-    g_spi_tx_buf[3] = 0xef;
-    sblinky_spi_tx_vals(0, g_spi_tx_buf, 4);
-
-    /* Send blocking with txrx interface */
-    for (i = 0; i < 32; ++i) {
-        g_spi_tx_buf[i] = i + 1;
-    }
-    memset(g_spi_rx_buf, 0x55, 32);
-    rc = hal_spi_txrx(0, g_spi_tx_buf, g_spi_rx_buf, 32);
-    assert(!rc);
-
-    /* Now send with no rx buf and make sure it dont change! */
-    for (i = 0; i < 32; ++i) {
-        g_spi_tx_buf[i] = (uint8_t)(i + 32);
-    }
-    memset(g_spi_rx_buf, 0xAA, 32);
-    rc = hal_spi_txrx(0, g_spi_tx_buf, NULL, 32);
-    assert(!rc);
-    for (i = 0; i < 32; ++i) {
-        if (g_spi_rx_buf[i] != 0xAA) {
-            assert(0);
-        }
-    }
-#endif
-
-    /* Set up for non-blocking */
-    hal_spi_disable(0);
-    spi_cb_arg = &spi_cb_obj;
-    spi_cb_obj.txlen = 32;
-    hal_spi_set_txrx_cb(0, sblinky_spi_irqm_handler, spi_cb_arg);
-    hal_spi_enable(0);
-#endif
-
-#if MYNEWT_VAL(SPI_SLAVE)
-    sblinky_spi_cfg(SPI_SLAVE_ID);
-    hal_spi_enable(SPI_SLAVE_ID);
-
-    /* Make the default character 0xAA */
-    hal_spi_slave_set_def_tx_val(SPI_SLAVE_ID, 0xAA);
-
-    /* Setup a buffer to receive into */
-    memset(g_spi_tx_buf, 0xEE, 32);
-    rc = hal_spi_txrx(SPI_SLAVE_ID, g_spi_tx_buf, g_spi_rx_buf, 32);
-    assert(rc == 0);
-#endif
-#if MYNEWT_VAL(ADC_3)
-    sample_buffer1 = malloc(adc_buf_size(adc3, ADC_NUMBER_CHANNELS, ADC_NUMBER_SAMPLES));
-    sample_buffer2 = malloc(adc_buf_size(adc3, ADC_NUMBER_CHANNELS, ADC_NUMBER_SAMPLES));
-    memset(sample_buffer1, 0, adc_buf_size(adc3, ADC_NUMBER_CHANNELS, ADC_NUMBER_SAMPLES));
-    memset(sample_buffer2, 0, adc_buf_size(adc3, ADC_NUMBER_CHANNELS, ADC_NUMBER_SAMPLES));
-#endif
-
-#if MYNEWT_VAL(ADC_1)
-    sample_buffer3 = malloc(adc_buf_size(adc1, ADC_NUMBER_CHANNELS, ADC_NUMBER_SAMPLES));
-    sample_buffer4 = malloc(adc_buf_size(adc1, ADC_NUMBER_CHANNELS, ADC_NUMBER_SAMPLES));
-    memset(sample_buffer3, 0, adc_buf_size(adc1, ADC_NUMBER_CHANNELS, ADC_NUMBER_SAMPLES));
-    memset(sample_buffer4, 0, adc_buf_size(adc1, ADC_NUMBER_CHANNELS, ADC_NUMBER_SAMPLES));
-#endif
-
-#if 1
-#if MYNEWT_VAL(ADC_3)
-    adc_buf_set(adc3, sample_buffer1, sample_buffer2,
-            adc_buf_size(adc3, ADC_NUMBER_CHANNELS, ADC_NUMBER_SAMPLES));
-    adc_event_handler_set(adc3, adc3_read_event, NULL);
-#endif
-
-#if MYNEWT_VAL(ADC_1)
-    adc_buf_set(adc1, sample_buffer3, sample_buffer4,
-            adc_buf_size(adc1, ADC_NUMBER_CHANNELS, ADC_NUMBER_SAMPLES));
-    adc_event_handler_set(adc1, adc1_read_event, NULL);
-#endif
-#endif
-
-    while (1) {
-        t = os_sched_get_current_task();
-        assert(t->t_func == task1_handler);
-
-#if 0
-        int rc;
-        rc = adc_chan_read(adc, 4, &g_result);
-        assert(rc == 0);
-        g_result_mv = adc_result_mv(adc, 4, g_result);
-#endif
-        int rc;
-        rc = OS_OK;
-
-
-#if MYNEWT_VAL(ADC_1)
-        rc = adc_sample(adc1);
-        assert(rc == OS_OK);
-#endif
-
-#if MYNEWT_VAL(ADC_3)
-        rc = adc_sample(adc3);
-        assert(rc == OS_OK);
-#endif
-        ++g_task1_loops;
-
-#if MYNEWT_VAL(SPI_MASTER)
-        /*
-         * Send a spi buffer using non-blocking callbacks.
-         * Every other transfer should use a NULL rxbuf
-         */
-        last_val = g_spi_tx_buf[31];
-        for (i = 0; i < 32; ++i) {
-            g_spi_tx_buf[i] = (uint8_t)(last_val + i);
-        }
-        hal_gpio_clear(SPI0_CONFIG_CSN_PIN);
-        rc = hal_spi_txrx(0, g_spi_tx_buf, g_spi_rx_buf, 32);
-        assert(!rc);
-#endif
-
-        /* Wait one second */
-        os_time_delay(OS_TICKS_PER_SEC);
-
-        /* Toggle the LED */
-        hal_gpio_toggle(g_led_pin);
-
-#if 0
-        nrf_drv_saadc_sample();
-#endif
-        /* Release semaphore to task 2 */
-        os_sem_release(&g_test_sem);
-    }
-
-#if MYNEWT_VAL(ADC_1)
-    os_dev_close((struct os_dev *) adc1);
-#endif
-
-#if MYNEWT_VAL(ADC_3)
-    os_dev_close((struct os_dev *) adc3);
-#endif
-
-}
-
-void
-task2_handler(void *arg)
-{
-#if MYNEWT_VAL(SPI_SLAVE)
-    int rc;
-#endif
-    struct os_task *t;
-
-    while (1) {
-        /* just for debug; task 2 should be the running task */
-        t = os_sched_get_current_task();
-        assert(t->t_func == task2_handler);
-
-        /* Increment # of times we went through task loop */
-        ++g_task2_loops;
-
-        /* Wait for semaphore from ISR */
-        os_sem_pend(&g_test_sem, OS_TIMEOUT_NEVER);
-
-#if MYNEWT_VAL(SPI_SLAVE)
-        /* transmit back what we just received */
-        memcpy(g_spi_tx_buf, g_spi_rx_buf, 32);
-        rc = hal_spi_txrx(SPI_SLAVE_ID, g_spi_tx_buf, g_spi_rx_buf, 32);
-        assert(rc == 0);
-#endif
-    }
-}
-
-/**
- * init_tasks
- *
- * Called by main.c after os_init(). This function performs initializations
- * that are required before tasks are running.
- *
- * @return int 0 success; error otherwise.
- */
-int
-init_tasks(void)
-{
-    /* Initialize global test semaphore */
-    os_sem_init(&g_test_sem, 0);
-
-    os_task_init(&task1, "task1", task1_handler, NULL,
-            TASK1_PRIO, OS_WAIT_FOREVER, stack1, TASK1_STACK_SIZE);
-
-    os_task_init(&task2, "task2", task2_handler, NULL,
-            TASK2_PRIO, OS_WAIT_FOREVER, stack2, TASK2_STACK_SIZE);
-
-    tasks_initialized = 1;
-    return 0;
-}
-
-/**
- * main
- *
- * The main function for the project. This function initializes the os, calls
- * init_tasks to initialize tasks (and possibly other objects), then starts the
- * OS. We should not return from os start.
- *
- * @return int NOTE: this function should never return!
- */
-int
-main(int argc, char **argv)
-{
-    int rc;
-
-#ifdef ARCH_sim
-    mcu_sim_parse_args(argc, argv);
-#endif
-
-    os_init();
-
-#if 0
-    saadc_test();
-#endif
-    rc = init_tasks();
-    os_start();
-
-    /* os start should never return. If it does, this should be an error */
-    assert(0);
-
-    return rc;
-}
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/apps/slinky/pkg.yml
----------------------------------------------------------------------
diff --git a/apps/slinky/pkg.yml b/apps/slinky/pkg.yml
index 6bbbcdb..3d4f7a4 100644
--- a/apps/slinky/pkg.yml
+++ b/apps/slinky/pkg.yml
@@ -25,15 +25,15 @@ pkg.homepage: "http://mynewt.apache.org/"
 pkg.keywords:
 
 pkg.deps:
-    - libs/console/full
-    - libs/flash_test
+    - sys/console/full
+    - test/flash_test
     - libs/imgmgr
     - libs/newtmgr
-    - libs/os
-    - libs/bootutil
-    - libs/shell
+    - kernel/os
+    - boot/bootutil
+    - sys/shell
     - libs/util
-    - libs/split
+    - boot/split
     - sys/config
     - sys/id
     - sys/log

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/apps/splitty/pkg.yml
----------------------------------------------------------------------
diff --git a/apps/splitty/pkg.yml b/apps/splitty/pkg.yml
index a984e5f..0a8d80b 100644
--- a/apps/splitty/pkg.yml
+++ b/apps/splitty/pkg.yml
@@ -26,14 +26,14 @@ pkg.keywords:
 
 pkg.deps:
     - fs/nffs
-    - libs/console/full
+    - sys/console/full
     - libs/imgmgr
     - libs/newtmgr
-    - libs/os
-    - libs/bootutil
-    - libs/shell
+    - kernel/os
+    - boot/bootutil
+    - sys/shell
     - libs/util
-    - libs/split
+    - boot/split
     - sys/config
     - sys/id
     - sys/log

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/apps/test/pkg.yml
----------------------------------------------------------------------
diff --git a/apps/test/pkg.yml b/apps/test/pkg.yml
index 22bee48..ff3d3fd 100644
--- a/apps/test/pkg.yml
+++ b/apps/test/pkg.yml
@@ -26,11 +26,11 @@ pkg.keywords:
 
 pkg.deps:
     - fs/nffs
-    - libs/bootutil
-    - libs/console/full
+    - boot/bootutil
+    - sys/console/full
     - crypto/mbedtls
-    - libs/os
-    - libs/testreport
-    - libs/testutil
+    - kernel/os
+    - test/testreport
+    - test/testutil
     - libs/util
     - sys/config

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/boot/boot_serial/include/boot_serial/boot_serial.h
----------------------------------------------------------------------
diff --git a/boot/boot_serial/include/boot_serial/boot_serial.h b/boot/boot_serial/include/boot_serial/boot_serial.h
new file mode 100644
index 0000000..67fa415
--- /dev/null
+++ b/boot/boot_serial/include/boot_serial/boot_serial.h
@@ -0,0 +1,33 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 __BOOT_SERIAL_H__
+#define __BOOT_SERIAL_H__
+
+/*
+ * Create a task for uploading image0 over serial.
+ *
+ * Task opens console serial port and waits for download command.
+ * Return code 0 means new image was uploaded, non-zero means that
+ * there was an error.
+ */
+int boot_serial_task_init(struct os_task *task, uint8_t prio,
+  os_stack_t *stack, uint16_t stack_size, int max_input);
+
+#endif /*  __BOOT_SERIAL_H__ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/boot/boot_serial/pkg.yml
----------------------------------------------------------------------
diff --git a/boot/boot_serial/pkg.yml b/boot/boot_serial/pkg.yml
new file mode 100644
index 0000000..69773a1
--- /dev/null
+++ b/boot/boot_serial/pkg.yml
@@ -0,0 +1,36 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+#
+
+pkg.name: libs/boot_serial
+pkg.description: The boot_serial library is used when downloading image over serial port.
+pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
+pkg.homepage: "http://mynewt.apache.org/"
+pkg.keywords:
+    - boot
+    - bootloader
+
+pkg.deps:
+    - hw/hal
+    - kernel/os
+    - boot/bootutil
+    - encoding/base64
+    - encoding/crc
+
+pkg.req_apis:
+    - console

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/boot/boot_serial/src/boot_serial.c
----------------------------------------------------------------------
diff --git a/boot/boot_serial/src/boot_serial.c b/boot/boot_serial/src/boot_serial.c
new file mode 100644
index 0000000..23c343a
--- /dev/null
+++ b/boot/boot_serial/src/boot_serial.c
@@ -0,0 +1,403 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+#include <assert.h>
+#include <stddef.h>
+#include <inttypes.h>
+#include <ctype.h>
+#include <stdio.h>
+
+#include <bsp/bsp.h>
+
+#include <hal/flash_map.h>
+#include <hal/hal_flash.h>
+#include <hal/hal_system.h>
+
+#include <os/endian.h>
+#include <os/os.h>
+#include <os/os_malloc.h>
+
+#include <console/console.h>
+
+#include <base64/base64.h>
+#include <crc/crc16.h>
+
+#include <bootutil/image.h>
+
+#include "boot_serial/boot_serial.h"
+#include "boot_serial_priv.h"
+
+#define BOOT_SERIAL_OUT_MAX	48
+
+static uint32_t curr_off;
+static uint32_t img_size;
+static struct nmgr_hdr *bs_hdr;
+
+static void boot_serial_output(char *data, int len);
+
+/*
+ * Looks for 'name' from NULL-terminated json data in buf.
+ * Returns pointer to first character of value for that name.
+ * Returns NULL if 'name' is not found.
+ */
+char *
+bs_find_val(char *buf, char *name)
+{
+    char *ptr;
+
+    ptr = strstr(buf, name);
+    if (!ptr) {
+        return NULL;
+    }
+    ptr += strlen(name);
+
+    while (*ptr != '\0') {
+        if (*ptr != ':' && !isspace(*ptr)) {
+            break;
+        }
+        ++ptr;
+    }
+    if (*ptr == '\0') {
+        ptr = NULL;
+    }
+    return ptr;
+}
+
+/*
+ * List images.
+ */
+static void
+bs_list(char *buf, int len)
+{
+    char *ptr;
+    struct image_header hdr;
+    uint8_t tmpbuf[64];
+    const struct flash_area *fap = NULL;
+    int good_img, need_comma = 0;
+    int rc;
+    int i;
+
+    ptr = os_malloc(BOOT_SERIAL_OUT_MAX);
+    if (!ptr) {
+        return;
+    }
+    len = snprintf(ptr, BOOT_SERIAL_OUT_MAX, "{\"images\":[");
+    for (i = FLASH_AREA_IMAGE_0; i <= FLASH_AREA_IMAGE_1; i++) {
+        rc = flash_area_open(i, &fap);
+        if (rc) {
+            continue;
+        }
+
+        flash_area_read(fap, 0, &hdr, sizeof(hdr));
+
+        if (hdr.ih_magic == IMAGE_MAGIC &&
+          bootutil_img_validate(&hdr, fap->fa_flash_id, fap->fa_off,
+            tmpbuf, sizeof(tmpbuf), NULL, 0, NULL) == 0) {
+            good_img = 1;
+        } else {
+            good_img = 0;
+        }
+        if (good_img) {
+            len += snprintf(ptr + len, BOOT_SERIAL_OUT_MAX - len,
+              "%c\"%u.%u.%u.%u\"", need_comma ? ',' : ' ',
+              hdr.ih_ver.iv_major, hdr.ih_ver.iv_minor, hdr.ih_ver.iv_revision,
+              (unsigned int)hdr.ih_ver.iv_build_num);
+        }
+        flash_area_close(fap);
+    }
+    len += snprintf(ptr + len, BOOT_SERIAL_OUT_MAX - len, "]}");
+    boot_serial_output(ptr, len);
+    os_free(ptr);
+}
+
+/*
+ * Image upload request.
+ */
+static void
+bs_upload(char *buf, int len)
+{
+    char *ptr;
+    char *data_ptr;
+    uint32_t off, data_len = 0;
+    const struct flash_area *fap = NULL;
+    int rc;
+
+    /*
+     * should be json inside
+     */
+    ptr = bs_find_val(buf, "\"off\"");
+    if (!ptr) {
+        rc = NMGR_ERR_EINVAL;
+        goto out;
+    }
+    off = strtoul(ptr, NULL, 10);
+
+    if (off == 0) {
+        ptr = bs_find_val(buf, "\"len\"");
+        if (!ptr) {
+            rc = NMGR_ERR_EINVAL;
+            goto out;
+        }
+        data_len = strtoul(ptr, NULL, 10);
+
+    }
+    data_ptr = bs_find_val(buf, "\"data\"");
+    if (!data_ptr) {
+        rc = NMGR_ERR_EINVAL;
+        goto out;
+    }
+    if (*data_ptr != '"') {
+        rc = NMGR_ERR_EINVAL;
+        goto out;
+    }
+    ++data_ptr;
+    data_ptr = strsep(&data_ptr, "\"");
+    if (!data_ptr) {
+        rc = NMGR_ERR_EINVAL;
+        goto out;
+    }
+
+    len = base64_decode(data_ptr, data_ptr);
+    if (len <= 0) {
+        rc = NMGR_ERR_EINVAL;
+        goto out;
+    }
+
+    rc = flash_area_open(FLASH_AREA_IMAGE_0, &fap);
+    if (rc) {
+        rc = NMGR_ERR_EINVAL;
+        goto out;
+    }
+
+    if (off == 0) {
+        curr_off = 0;
+        if (data_len > fap->fa_size) {
+            rc = NMGR_ERR_EINVAL;
+            goto out;
+        }
+        rc = flash_area_erase(fap, 0, fap->fa_size);
+        if (rc) {
+            rc = NMGR_ERR_EINVAL;
+            goto out;
+        }
+        img_size = data_len;
+    }
+    if (off != curr_off) {
+        rc = 0;
+        goto out;
+    }
+    rc = flash_area_write(fap, curr_off, data_ptr, len);
+    if (rc) {
+        rc = NMGR_ERR_EINVAL;
+        goto out;
+    }
+    curr_off += len;
+
+out:
+    ptr = os_malloc(BOOT_SERIAL_OUT_MAX);
+    if (!ptr) {
+        return;
+    }
+    if (rc == 0) {
+        len = snprintf(ptr, BOOT_SERIAL_OUT_MAX, "{\"rc\":%d,\"off\":%u}",
+          rc, (int)curr_off);
+    } else {
+        len = snprintf(ptr, BOOT_SERIAL_OUT_MAX, "{\"rc\":%d}", rc);
+    }
+    boot_serial_output(ptr, len);
+    os_free(ptr);
+    flash_area_close(fap);
+}
+
+/*
+ * Console echo control. Send empty response, don't do anything.
+ */
+static void
+bs_echo_ctl(char *buf, int len)
+{
+    boot_serial_output(NULL, 0);
+}
+
+/*
+ * Reset, and (presumably) boot to newly uploaded image. Flush console
+ * before restarting.
+ */
+static void
+bs_reset(char *buf, int len)
+{
+    char msg[] = "{\"rc\":0}";
+
+    boot_serial_output(msg, strlen(msg));
+    os_time_delay(250);
+    system_reset();
+}
+
+/*
+ * Parse incoming line of input from console.
+ * Expect newtmgr protocol with serial transport.
+ */
+void
+boot_serial_input(char *buf, int len)
+{
+    int rc;
+    uint16_t crc;
+    uint16_t expected_len;
+    struct nmgr_hdr *hdr;
+
+    if (len < BASE64_ENCODE_SIZE(sizeof(uint16_t) * 2)) {
+        return;
+    }
+    rc = base64_decode(buf, buf);
+    if (rc < 0) {
+        return;
+    }
+    len = rc;
+
+    expected_len = ntohs(*(uint16_t *)buf);
+    buf += sizeof(uint16_t);
+    len -= sizeof(uint16_t);
+
+    len = min(len, expected_len);
+
+    crc = crc16_ccitt(CRC16_INITIAL_CRC, buf, len);
+    if (crc || len <= sizeof(crc)) {
+        return;
+    }
+    len -= sizeof(crc);
+    buf[len] = '\0';
+
+    hdr = (struct nmgr_hdr *)buf;
+    if (len < sizeof(*hdr) ||
+      (hdr->nh_op != NMGR_OP_READ && hdr->nh_op != NMGR_OP_WRITE) ||
+      (ntohs(hdr->nh_len) < len - sizeof(*hdr))) {
+        return;
+    }
+    bs_hdr = hdr;
+    hdr->nh_group = ntohs(hdr->nh_group);
+
+    buf += sizeof(*hdr);
+    len -= sizeof(*hdr);
+
+    /*
+     * Limited support for commands.
+     */
+    if (hdr->nh_group == NMGR_GROUP_ID_IMAGE) {
+        switch (hdr->nh_id) {
+        case IMGMGR_NMGR_OP_LIST:
+            bs_list(buf, len);
+            break;
+        case IMGMGR_NMGR_OP_UPLOAD:
+            bs_upload(buf, len);
+            break;
+        default:
+            break;
+        }
+    } else if (hdr->nh_group == NMGR_GROUP_ID_DEFAULT) {
+        switch (hdr->nh_id) {
+        case NMGR_ID_CONS_ECHO_CTRL:
+            bs_echo_ctl(buf, len);
+            break;
+        case NMGR_ID_RESET:
+            bs_reset(buf, len);
+            break;
+        default:
+            break;
+        }
+    }
+}
+
+static void
+boot_serial_output(char *data, int len)
+{
+    uint16_t crc;
+    uint16_t totlen;
+    char pkt_start[2] = { SHELL_NLIP_PKT_START1, SHELL_NLIP_PKT_START2 };
+    char buf[BOOT_SERIAL_OUT_MAX];
+    char encoded_buf[BASE64_ENCODE_SIZE(BOOT_SERIAL_OUT_MAX)];
+
+    bs_hdr->nh_op++;
+    bs_hdr->nh_len = htons(len);
+    bs_hdr->nh_group = htons(bs_hdr->nh_group);
+
+    crc = crc16_ccitt(CRC16_INITIAL_CRC, bs_hdr, sizeof(*bs_hdr));
+    crc = crc16_ccitt(crc, data, len);
+    crc = htons(crc);
+
+    console_write(pkt_start, sizeof(pkt_start));
+
+    totlen = len + sizeof(*bs_hdr) + sizeof(crc);
+    totlen = htons(totlen);
+
+    memcpy(buf, &totlen, sizeof(totlen));
+    totlen = sizeof(totlen);
+    memcpy(&buf[totlen], bs_hdr, sizeof(*bs_hdr));
+    totlen += sizeof(*bs_hdr);
+    memcpy(&buf[totlen], data, len);
+    totlen += len;
+    memcpy(&buf[totlen], &crc, sizeof(crc));
+    totlen += sizeof(crc);
+    totlen = base64_encode(buf, totlen, encoded_buf, 1);
+    console_write(encoded_buf, totlen);
+    console_write("\n", 1);
+}
+
+/*
+ * Task which waits reading console, expecting to get image over
+ * serial port.
+ */
+static void
+boot_serial(void *arg)
+{
+    int rc;
+    int off;
+    char *buf;
+    int full_line;
+    int max_input = (int)arg;
+
+    rc = console_init(NULL);
+    assert(rc == 0);
+    console_echo(0);
+
+    buf = os_malloc(max_input);
+    assert(buf);
+
+    off = 0;
+    while (1) {
+        rc = console_read(buf + off, max_input - off, &full_line);
+        if (rc <= 0 && !full_line) {
+            continue;
+        }
+        off += rc;
+        if (!full_line) {
+            continue;
+        }
+        if (buf[0] == SHELL_NLIP_PKT_START1 &&
+          buf[1] == SHELL_NLIP_PKT_START2) {
+            boot_serial_input(&buf[2], off - 2);
+        }
+        off = 0;
+    }
+}
+
+int
+boot_serial_task_init(struct os_task *task, uint8_t prio, os_stack_t *stack,
+  uint16_t stack_size, int max_input)
+{
+    return os_task_init(task, "boot", boot_serial, (void *)max_input,
+      prio, OS_WAIT_FOREVER, stack, stack_size);
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/boot/boot_serial/src/boot_serial_priv.h
----------------------------------------------------------------------
diff --git a/boot/boot_serial/src/boot_serial_priv.h b/boot/boot_serial/src/boot_serial_priv.h
new file mode 100644
index 0000000..86ba6c6
--- /dev/null
+++ b/boot/boot_serial/src/boot_serial_priv.h
@@ -0,0 +1,61 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 __BOOTUTIL_SERIAL_PRIV_H__
+#define __BOOTUTIL_SERIAL_PRIV_H__
+
+/*
+ * From shell.h
+ */
+#define SHELL_NLIP_PKT_START1   6
+#define SHELL_NLIP_PKT_START2   9
+
+/*
+ * From newtmgr.h
+ */
+#define NMGR_ERR_EINVAL         3
+
+#define NMGR_OP_READ            0
+#define NMGR_OP_WRITE           2
+
+#define NMGR_GROUP_ID_DEFAULT   0
+#define NMGR_GROUP_ID_IMAGE     1
+
+#define NMGR_ID_CONS_ECHO_CTRL  1
+#define NMGR_ID_RESET           5
+
+struct nmgr_hdr {
+    uint8_t  nh_op;             /* NMGR_OP_XXX */
+    uint8_t  nh_flags;
+    uint16_t nh_len;            /* length of the payload */
+    uint16_t nh_group;          /* NMGR_GROUP_XXX */
+    uint8_t  nh_seq;            /* sequence number */
+    uint8_t  nh_id;             /* message ID within group */
+};
+
+/*
+ * From imgmgr.h
+ */
+#define IMGMGR_NMGR_OP_LIST             0
+#define IMGMGR_NMGR_OP_UPLOAD           1
+
+
+void boot_serial_input(char *buf, int len);
+
+#endif /*  __BOOTUTIL_SERIAL_PRIV_H__ */



[27/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/cmsis-core/src/ext/core_cm0plus.h
----------------------------------------------------------------------
diff --git a/libs/cmsis-core/src/ext/core_cm0plus.h b/libs/cmsis-core/src/ext/core_cm0plus.h
deleted file mode 100644
index 5cea74e..0000000
--- a/libs/cmsis-core/src/ext/core_cm0plus.h
+++ /dev/null
@@ -1,793 +0,0 @@
-/**************************************************************************//**
- * @file     core_cm0plus.h
- * @brief    CMSIS Cortex-M0+ Core Peripheral Access Layer Header File
- * @version  V3.20
- * @date     25. February 2013
- *
- * @note
- *
- ******************************************************************************/
-/* Copyright (c) 2009 - 2013 ARM LIMITED
-
-   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 ARM 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 COPYRIGHT HOLDERS AND CONTRIBUTORS BE
-   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-   POSSIBILITY OF SUCH DAMAGE.
-   ---------------------------------------------------------------------------*/
-
-
-#if defined ( __ICCARM__ )
- #pragma system_include  /* treat file as system include file for MISRA check */
-#endif
-
-#ifdef __cplusplus
- extern "C" {
-#endif
-
-#ifndef __CORE_CM0PLUS_H_GENERIC
-#define __CORE_CM0PLUS_H_GENERIC
-
-/** \page CMSIS_MISRA_Exceptions  MISRA-C:2004 Compliance Exceptions
-  CMSIS violates the following MISRA-C:2004 rules:
-
-   \li Required Rule 8.5, object/function definition in header file.<br>
-     Function definitions in header files are used to allow 'inlining'.
-
-   \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.<br>
-     Unions are used for effective representation of core registers.
-
-   \li Advisory Rule 19.7, Function-like macro defined.<br>
-     Function-like macros are used to allow more efficient code.
- */
-
-
-/*******************************************************************************
- *                 CMSIS definitions
- ******************************************************************************/
-/** \ingroup Cortex-M0+
-  @{
- */
-
-/*  CMSIS CM0P definitions */
-#define __CM0PLUS_CMSIS_VERSION_MAIN (0x03)                                /*!< [31:16] CMSIS HAL main version   */
-#define __CM0PLUS_CMSIS_VERSION_SUB  (0x20)                                /*!< [15:0]  CMSIS HAL sub version    */
-#define __CM0PLUS_CMSIS_VERSION      ((__CM0PLUS_CMSIS_VERSION_MAIN << 16) | \
-                                       __CM0PLUS_CMSIS_VERSION_SUB)        /*!< CMSIS HAL version number         */
-
-#define __CORTEX_M                (0x00)                                   /*!< Cortex-M Core                    */
-
-
-#if   defined ( __CC_ARM )
-  #define __ASM            __asm                                      /*!< asm keyword for ARM Compiler          */
-  #define __INLINE         __inline                                   /*!< inline keyword for ARM Compiler       */
-  #define __STATIC_INLINE  static __inline
-
-#elif defined ( __ICCARM__ )
-  #define __ASM            __asm                                      /*!< asm keyword for IAR Compiler          */
-  #define __INLINE         inline                                     /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */
-  #define __STATIC_INLINE  static inline
-
-#elif defined ( __GNUC__ )
-  #define __ASM            __asm                                      /*!< asm keyword for GNU Compiler          */
-  #define __INLINE         inline                                     /*!< inline keyword for GNU Compiler       */
-  #define __STATIC_INLINE  static inline
-
-#elif defined ( __TASKING__ )
-  #define __ASM            __asm                                      /*!< asm keyword for TASKING Compiler      */
-  #define __INLINE         inline                                     /*!< inline keyword for TASKING Compiler   */
-  #define __STATIC_INLINE  static inline
-
-#endif
-
-/** __FPU_USED indicates whether an FPU is used or not. This core does not support an FPU at all
-*/
-#define __FPU_USED       0
-
-#if defined ( __CC_ARM )
-  #if defined __TARGET_FPU_VFP
-    #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
-  #endif
-
-#elif defined ( __ICCARM__ )
-  #if defined __ARMVFP__
-    #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
-  #endif
-
-#elif defined ( __GNUC__ )
-  #if defined (__VFP_FP__) && !defined(__SOFTFP__)
-    #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
-  #endif
-
-#elif defined ( __TASKING__ )
-  #if defined __FPU_VFP__
-    #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
-  #endif
-#endif
-
-#include <stdint.h>                      /* standard types definitions                      */
-#include <core_cmInstr.h>                /* Core Instruction Access                         */
-#include <core_cmFunc.h>                 /* Core Function Access                            */
-
-#endif /* __CORE_CM0PLUS_H_GENERIC */
-
-#ifndef __CMSIS_GENERIC
-
-#ifndef __CORE_CM0PLUS_H_DEPENDANT
-#define __CORE_CM0PLUS_H_DEPENDANT
-
-/* check device defines and use defaults */
-#if defined __CHECK_DEVICE_DEFINES
-  #ifndef __CM0PLUS_REV
-    #define __CM0PLUS_REV             0x0000
-    #warning "__CM0PLUS_REV not defined in device header file; using default!"
-  #endif
-
-  #ifndef __MPU_PRESENT
-    #define __MPU_PRESENT             0
-    #warning "__MPU_PRESENT not defined in device header file; using default!"
-  #endif
-
-  #ifndef __VTOR_PRESENT
-    #define __VTOR_PRESENT            0
-    #warning "__VTOR_PRESENT not defined in device header file; using default!"
-  #endif
-
-  #ifndef __NVIC_PRIO_BITS
-    #define __NVIC_PRIO_BITS          2
-    #warning "__NVIC_PRIO_BITS not defined in device header file; using default!"
-  #endif
-
-  #ifndef __Vendor_SysTickConfig
-    #define __Vendor_SysTickConfig    0
-    #warning "__Vendor_SysTickConfig not defined in device header file; using default!"
-  #endif
-#endif
-
-/* IO definitions (access restrictions to peripheral registers) */
-/**
-    \defgroup CMSIS_glob_defs CMSIS Global Defines
-
-    <strong>IO Type Qualifiers</strong> are used
-    \li to specify the access to peripheral variables.
-    \li for automatic generation of peripheral register debug information.
-*/
-#ifdef __cplusplus
-  #define   __I     volatile             /*!< Defines 'read only' permissions                 */
-#else
-  #define   __I     volatile const       /*!< Defines 'read only' permissions                 */
-#endif
-#define     __O     volatile             /*!< Defines 'write only' permissions                */
-#define     __IO    volatile             /*!< Defines 'read / write' permissions              */
-
-/*@} end of group Cortex-M0+ */
-
-
-
-/*******************************************************************************
- *                 Register Abstraction
-  Core Register contain:
-  - Core Register
-  - Core NVIC Register
-  - Core SCB Register
-  - Core SysTick Register
-  - Core MPU Register
- ******************************************************************************/
-/** \defgroup CMSIS_core_register Defines and Type Definitions
-    \brief Type definitions and defines for Cortex-M processor based devices.
-*/
-
-/** \ingroup    CMSIS_core_register
-    \defgroup   CMSIS_CORE  Status and Control Registers
-    \brief  Core Register type definitions.
-  @{
- */
-
-/** \brief  Union type to access the Application Program Status Register (APSR).
- */
-typedef union
-{
-  struct
-  {
-#if (__CORTEX_M != 0x04)
-    uint32_t _reserved0:27;              /*!< bit:  0..26  Reserved                           */
-#else
-    uint32_t _reserved0:16;              /*!< bit:  0..15  Reserved                           */
-    uint32_t GE:4;                       /*!< bit: 16..19  Greater than or Equal flags        */
-    uint32_t _reserved1:7;               /*!< bit: 20..26  Reserved                           */
-#endif
-    uint32_t Q:1;                        /*!< bit:     27  Saturation condition flag          */
-    uint32_t V:1;                        /*!< bit:     28  Overflow condition code flag       */
-    uint32_t C:1;                        /*!< bit:     29  Carry condition code flag          */
-    uint32_t Z:1;                        /*!< bit:     30  Zero condition code flag           */
-    uint32_t N:1;                        /*!< bit:     31  Negative condition code flag       */
-  } b;                                   /*!< Structure used for bit  access                  */
-  uint32_t w;                            /*!< Type      used for word access                  */
-} APSR_Type;
-
-
-/** \brief  Union type to access the Interrupt Program Status Register (IPSR).
- */
-typedef union
-{
-  struct
-  {
-    uint32_t ISR:9;                      /*!< bit:  0.. 8  Exception number                   */
-    uint32_t _reserved0:23;              /*!< bit:  9..31  Reserved                           */
-  } b;                                   /*!< Structure used for bit  access                  */
-  uint32_t w;                            /*!< Type      used for word access                  */
-} IPSR_Type;
-
-
-/** \brief  Union type to access the Special-Purpose Program Status Registers (xPSR).
- */
-typedef union
-{
-  struct
-  {
-    uint32_t ISR:9;                      /*!< bit:  0.. 8  Exception number                   */
-#if (__CORTEX_M != 0x04)
-    uint32_t _reserved0:15;              /*!< bit:  9..23  Reserved                           */
-#else
-    uint32_t _reserved0:7;               /*!< bit:  9..15  Reserved                           */
-    uint32_t GE:4;                       /*!< bit: 16..19  Greater than or Equal flags        */
-    uint32_t _reserved1:4;               /*!< bit: 20..23  Reserved                           */
-#endif
-    uint32_t T:1;                        /*!< bit:     24  Thumb bit        (read 0)          */
-    uint32_t IT:2;                       /*!< bit: 25..26  saved IT state   (read 0)          */
-    uint32_t Q:1;                        /*!< bit:     27  Saturation condition flag          */
-    uint32_t V:1;                        /*!< bit:     28  Overflow condition code flag       */
-    uint32_t C:1;                        /*!< bit:     29  Carry condition code flag          */
-    uint32_t Z:1;                        /*!< bit:     30  Zero condition code flag           */
-    uint32_t N:1;                        /*!< bit:     31  Negative condition code flag       */
-  } b;                                   /*!< Structure used for bit  access                  */
-  uint32_t w;                            /*!< Type      used for word access                  */
-} xPSR_Type;
-
-
-/** \brief  Union type to access the Control Registers (CONTROL).
- */
-typedef union
-{
-  struct
-  {
-    uint32_t nPRIV:1;                    /*!< bit:      0  Execution privilege in Thread mode */
-    uint32_t SPSEL:1;                    /*!< bit:      1  Stack to be used                   */
-    uint32_t FPCA:1;                     /*!< bit:      2  FP extension active flag           */
-    uint32_t _reserved0:29;              /*!< bit:  3..31  Reserved                           */
-  } b;                                   /*!< Structure used for bit  access                  */
-  uint32_t w;                            /*!< Type      used for word access                  */
-} CONTROL_Type;
-
-/*@} end of group CMSIS_CORE */
-
-
-/** \ingroup    CMSIS_core_register
-    \defgroup   CMSIS_NVIC  Nested Vectored Interrupt Controller (NVIC)
-    \brief      Type definitions for the NVIC Registers
-  @{
- */
-
-/** \brief  Structure type to access the Nested Vectored Interrupt Controller (NVIC).
- */
-typedef struct
-{
-  __IO uint32_t ISER[1];                 /*!< Offset: 0x000 (R/W)  Interrupt Set Enable Register           */
-       uint32_t RESERVED0[31];
-  __IO uint32_t ICER[1];                 /*!< Offset: 0x080 (R/W)  Interrupt Clear Enable Register          */
-       uint32_t RSERVED1[31];
-  __IO uint32_t ISPR[1];                 /*!< Offset: 0x100 (R/W)  Interrupt Set Pending Register           */
-       uint32_t RESERVED2[31];
-  __IO uint32_t ICPR[1];                 /*!< Offset: 0x180 (R/W)  Interrupt Clear Pending Register         */
-       uint32_t RESERVED3[31];
-       uint32_t RESERVED4[64];
-  __IO uint32_t IP[8];                   /*!< Offset: 0x300 (R/W)  Interrupt Priority Register              */
-}  NVIC_Type;
-
-/*@} end of group CMSIS_NVIC */
-
-
-/** \ingroup  CMSIS_core_register
-    \defgroup CMSIS_SCB     System Control Block (SCB)
-    \brief      Type definitions for the System Control Block Registers
-  @{
- */
-
-/** \brief  Structure type to access the System Control Block (SCB).
- */
-typedef struct
-{
-  __I  uint32_t CPUID;                   /*!< Offset: 0x000 (R/ )  CPUID Base Register                                   */
-  __IO uint32_t ICSR;                    /*!< Offset: 0x004 (R/W)  Interrupt Control and State Register                  */
-#if (__VTOR_PRESENT == 1)
-  __IO uint32_t VTOR;                    /*!< Offset: 0x008 (R/W)  Vector Table Offset Register                          */
-#else
-       uint32_t RESERVED0;
-#endif
-  __IO uint32_t AIRCR;                   /*!< Offset: 0x00C (R/W)  Application Interrupt and Reset Control Register      */
-  __IO uint32_t SCR;                     /*!< Offset: 0x010 (R/W)  System Control Register                               */
-  __IO uint32_t CCR;                     /*!< Offset: 0x014 (R/W)  Configuration Control Register                        */
-       uint32_t RESERVED1;
-  __IO uint32_t SHP[2];                  /*!< Offset: 0x01C (R/W)  System Handlers Priority Registers. [0] is RESERVED   */
-  __IO uint32_t SHCSR;                   /*!< Offset: 0x024 (R/W)  System Handler Control and State Register             */
-} SCB_Type;
-
-/* SCB CPUID Register Definitions */
-#define SCB_CPUID_IMPLEMENTER_Pos          24                                             /*!< SCB CPUID: IMPLEMENTER Position */
-#define SCB_CPUID_IMPLEMENTER_Msk          (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos)          /*!< SCB CPUID: IMPLEMENTER Mask */
-
-#define SCB_CPUID_VARIANT_Pos              20                                             /*!< SCB CPUID: VARIANT Position */
-#define SCB_CPUID_VARIANT_Msk              (0xFUL << SCB_CPUID_VARIANT_Pos)               /*!< SCB CPUID: VARIANT Mask */
-
-#define SCB_CPUID_ARCHITECTURE_Pos         16                                             /*!< SCB CPUID: ARCHITECTURE Position */
-#define SCB_CPUID_ARCHITECTURE_Msk         (0xFUL << SCB_CPUID_ARCHITECTURE_Pos)          /*!< SCB CPUID: ARCHITECTURE Mask */
-
-#define SCB_CPUID_PARTNO_Pos                4                                             /*!< SCB CPUID: PARTNO Position */
-#define SCB_CPUID_PARTNO_Msk               (0xFFFUL << SCB_CPUID_PARTNO_Pos)              /*!< SCB CPUID: PARTNO Mask */
-
-#define SCB_CPUID_REVISION_Pos              0                                             /*!< SCB CPUID: REVISION Position */
-#define SCB_CPUID_REVISION_Msk             (0xFUL << SCB_CPUID_REVISION_Pos)              /*!< SCB CPUID: REVISION Mask */
-
-/* SCB Interrupt Control State Register Definitions */
-#define SCB_ICSR_NMIPENDSET_Pos            31                                             /*!< SCB ICSR: NMIPENDSET Position */
-#define SCB_ICSR_NMIPENDSET_Msk            (1UL << SCB_ICSR_NMIPENDSET_Pos)               /*!< SCB ICSR: NMIPENDSET Mask */
-
-#define SCB_ICSR_PENDSVSET_Pos             28                                             /*!< SCB ICSR: PENDSVSET Position */
-#define SCB_ICSR_PENDSVSET_Msk             (1UL << SCB_ICSR_PENDSVSET_Pos)                /*!< SCB ICSR: PENDSVSET Mask */
-
-#define SCB_ICSR_PENDSVCLR_Pos             27                                             /*!< SCB ICSR: PENDSVCLR Position */
-#define SCB_ICSR_PENDSVCLR_Msk             (1UL << SCB_ICSR_PENDSVCLR_Pos)                /*!< SCB ICSR: PENDSVCLR Mask */
-
-#define SCB_ICSR_PENDSTSET_Pos             26                                             /*!< SCB ICSR: PENDSTSET Position */
-#define SCB_ICSR_PENDSTSET_Msk             (1UL << SCB_ICSR_PENDSTSET_Pos)                /*!< SCB ICSR: PENDSTSET Mask */
-
-#define SCB_ICSR_PENDSTCLR_Pos             25                                             /*!< SCB ICSR: PENDSTCLR Position */
-#define SCB_ICSR_PENDSTCLR_Msk             (1UL << SCB_ICSR_PENDSTCLR_Pos)                /*!< SCB ICSR: PENDSTCLR Mask */
-
-#define SCB_ICSR_ISRPREEMPT_Pos            23                                             /*!< SCB ICSR: ISRPREEMPT Position */
-#define SCB_ICSR_ISRPREEMPT_Msk            (1UL << SCB_ICSR_ISRPREEMPT_Pos)               /*!< SCB ICSR: ISRPREEMPT Mask */
-
-#define SCB_ICSR_ISRPENDING_Pos            22                                             /*!< SCB ICSR: ISRPENDING Position */
-#define SCB_ICSR_ISRPENDING_Msk            (1UL << SCB_ICSR_ISRPENDING_Pos)               /*!< SCB ICSR: ISRPENDING Mask */
-
-#define SCB_ICSR_VECTPENDING_Pos           12                                             /*!< SCB ICSR: VECTPENDING Position */
-#define SCB_ICSR_VECTPENDING_Msk           (0x1FFUL << SCB_ICSR_VECTPENDING_Pos)          /*!< SCB ICSR: VECTPENDING Mask */
-
-#define SCB_ICSR_VECTACTIVE_Pos             0                                             /*!< SCB ICSR: VECTACTIVE Position */
-#define SCB_ICSR_VECTACTIVE_Msk            (0x1FFUL << SCB_ICSR_VECTACTIVE_Pos)           /*!< SCB ICSR: VECTACTIVE Mask */
-
-#if (__VTOR_PRESENT == 1)
-/* SCB Interrupt Control State Register Definitions */
-#define SCB_VTOR_TBLOFF_Pos                 8                                             /*!< SCB VTOR: TBLOFF Position */
-#define SCB_VTOR_TBLOFF_Msk                (0xFFFFFFUL << SCB_VTOR_TBLOFF_Pos)            /*!< SCB VTOR: TBLOFF Mask */
-#endif
-
-/* SCB Application Interrupt and Reset Control Register Definitions */
-#define SCB_AIRCR_VECTKEY_Pos              16                                             /*!< SCB AIRCR: VECTKEY Position */
-#define SCB_AIRCR_VECTKEY_Msk              (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos)            /*!< SCB AIRCR: VECTKEY Mask */
-
-#define SCB_AIRCR_VECTKEYSTAT_Pos          16                                             /*!< SCB AIRCR: VECTKEYSTAT Position */
-#define SCB_AIRCR_VECTKEYSTAT_Msk          (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos)        /*!< SCB AIRCR: VECTKEYSTAT Mask */
-
-#define SCB_AIRCR_ENDIANESS_Pos            15                                             /*!< SCB AIRCR: ENDIANESS Position */
-#define SCB_AIRCR_ENDIANESS_Msk            (1UL << SCB_AIRCR_ENDIANESS_Pos)               /*!< SCB AIRCR: ENDIANESS Mask */
-
-#define SCB_AIRCR_SYSRESETREQ_Pos           2                                             /*!< SCB AIRCR: SYSRESETREQ Position */
-#define SCB_AIRCR_SYSRESETREQ_Msk          (1UL << SCB_AIRCR_SYSRESETREQ_Pos)             /*!< SCB AIRCR: SYSRESETREQ Mask */
-
-#define SCB_AIRCR_VECTCLRACTIVE_Pos         1                                             /*!< SCB AIRCR: VECTCLRACTIVE Position */
-#define SCB_AIRCR_VECTCLRACTIVE_Msk        (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos)           /*!< SCB AIRCR: VECTCLRACTIVE Mask */
-
-/* SCB System Control Register Definitions */
-#define SCB_SCR_SEVONPEND_Pos               4                                             /*!< SCB SCR: SEVONPEND Position */
-#define SCB_SCR_SEVONPEND_Msk              (1UL << SCB_SCR_SEVONPEND_Pos)                 /*!< SCB SCR: SEVONPEND Mask */
-
-#define SCB_SCR_SLEEPDEEP_Pos               2                                             /*!< SCB SCR: SLEEPDEEP Position */
-#define SCB_SCR_SLEEPDEEP_Msk              (1UL << SCB_SCR_SLEEPDEEP_Pos)                 /*!< SCB SCR: SLEEPDEEP Mask */
-
-#define SCB_SCR_SLEEPONEXIT_Pos             1                                             /*!< SCB SCR: SLEEPONEXIT Position */
-#define SCB_SCR_SLEEPONEXIT_Msk            (1UL << SCB_SCR_SLEEPONEXIT_Pos)               /*!< SCB SCR: SLEEPONEXIT Mask */
-
-/* SCB Configuration Control Register Definitions */
-#define SCB_CCR_STKALIGN_Pos                9                                             /*!< SCB CCR: STKALIGN Position */
-#define SCB_CCR_STKALIGN_Msk               (1UL << SCB_CCR_STKALIGN_Pos)                  /*!< SCB CCR: STKALIGN Mask */
-
-#define SCB_CCR_UNALIGN_TRP_Pos             3                                             /*!< SCB CCR: UNALIGN_TRP Position */
-#define SCB_CCR_UNALIGN_TRP_Msk            (1UL << SCB_CCR_UNALIGN_TRP_Pos)               /*!< SCB CCR: UNALIGN_TRP Mask */
-
-/* SCB System Handler Control and State Register Definitions */
-#define SCB_SHCSR_SVCALLPENDED_Pos         15                                             /*!< SCB SHCSR: SVCALLPENDED Position */
-#define SCB_SHCSR_SVCALLPENDED_Msk         (1UL << SCB_SHCSR_SVCALLPENDED_Pos)            /*!< SCB SHCSR: SVCALLPENDED Mask */
-
-/*@} end of group CMSIS_SCB */
-
-
-/** \ingroup  CMSIS_core_register
-    \defgroup CMSIS_SysTick     System Tick Timer (SysTick)
-    \brief      Type definitions for the System Timer Registers.
-  @{
- */
-
-/** \brief  Structure type to access the System Timer (SysTick).
- */
-typedef struct
-{
-  __IO uint32_t CTRL;                    /*!< Offset: 0x000 (R/W)  SysTick Control and Status Register */
-  __IO uint32_t LOAD;                    /*!< Offset: 0x004 (R/W)  SysTick Reload Value Register       */
-  __IO uint32_t VAL;                     /*!< Offset: 0x008 (R/W)  SysTick Current Value Register      */
-  __I  uint32_t CALIB;                   /*!< Offset: 0x00C (R/ )  SysTick Calibration Register        */
-} SysTick_Type;
-
-/* SysTick Control / Status Register Definitions */
-#define SysTick_CTRL_COUNTFLAG_Pos         16                                             /*!< SysTick CTRL: COUNTFLAG Position */
-#define SysTick_CTRL_COUNTFLAG_Msk         (1UL << SysTick_CTRL_COUNTFLAG_Pos)            /*!< SysTick CTRL: COUNTFLAG Mask */
-
-#define SysTick_CTRL_CLKSOURCE_Pos          2                                             /*!< SysTick CTRL: CLKSOURCE Position */
-#define SysTick_CTRL_CLKSOURCE_Msk         (1UL << SysTick_CTRL_CLKSOURCE_Pos)            /*!< SysTick CTRL: CLKSOURCE Mask */
-
-#define SysTick_CTRL_TICKINT_Pos            1                                             /*!< SysTick CTRL: TICKINT Position */
-#define SysTick_CTRL_TICKINT_Msk           (1UL << SysTick_CTRL_TICKINT_Pos)              /*!< SysTick CTRL: TICKINT Mask */
-
-#define SysTick_CTRL_ENABLE_Pos             0                                             /*!< SysTick CTRL: ENABLE Position */
-#define SysTick_CTRL_ENABLE_Msk            (1UL << SysTick_CTRL_ENABLE_Pos)               /*!< SysTick CTRL: ENABLE Mask */
-
-/* SysTick Reload Register Definitions */
-#define SysTick_LOAD_RELOAD_Pos             0                                             /*!< SysTick LOAD: RELOAD Position */
-#define SysTick_LOAD_RELOAD_Msk            (0xFFFFFFUL << SysTick_LOAD_RELOAD_Pos)        /*!< SysTick LOAD: RELOAD Mask */
-
-/* SysTick Current Register Definitions */
-#define SysTick_VAL_CURRENT_Pos             0                                             /*!< SysTick VAL: CURRENT Position */
-#define SysTick_VAL_CURRENT_Msk            (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos)        /*!< SysTick VAL: CURRENT Mask */
-
-/* SysTick Calibration Register Definitions */
-#define SysTick_CALIB_NOREF_Pos            31                                             /*!< SysTick CALIB: NOREF Position */
-#define SysTick_CALIB_NOREF_Msk            (1UL << SysTick_CALIB_NOREF_Pos)               /*!< SysTick CALIB: NOREF Mask */
-
-#define SysTick_CALIB_SKEW_Pos             30                                             /*!< SysTick CALIB: SKEW Position */
-#define SysTick_CALIB_SKEW_Msk             (1UL << SysTick_CALIB_SKEW_Pos)                /*!< SysTick CALIB: SKEW Mask */
-
-#define SysTick_CALIB_TENMS_Pos             0                                             /*!< SysTick CALIB: TENMS Position */
-#define SysTick_CALIB_TENMS_Msk            (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos)        /*!< SysTick CALIB: TENMS Mask */
-
-/*@} end of group CMSIS_SysTick */
-
-#if (__MPU_PRESENT == 1)
-/** \ingroup  CMSIS_core_register
-    \defgroup CMSIS_MPU     Memory Protection Unit (MPU)
-    \brief      Type definitions for the Memory Protection Unit (MPU)
-  @{
- */
-
-/** \brief  Structure type to access the Memory Protection Unit (MPU).
- */
-typedef struct
-{
-  __I  uint32_t TYPE;                    /*!< Offset: 0x000 (R/ )  MPU Type Register                              */
-  __IO uint32_t CTRL;                    /*!< Offset: 0x004 (R/W)  MPU Control Register                           */
-  __IO uint32_t RNR;                     /*!< Offset: 0x008 (R/W)  MPU Region RNRber Register                     */
-  __IO uint32_t RBAR;                    /*!< Offset: 0x00C (R/W)  MPU Region Base Address Register               */
-  __IO uint32_t RASR;                    /*!< Offset: 0x010 (R/W)  MPU Region Attribute and Size Register         */
-} MPU_Type;
-
-/* MPU Type Register */
-#define MPU_TYPE_IREGION_Pos               16                                             /*!< MPU TYPE: IREGION Position */
-#define MPU_TYPE_IREGION_Msk               (0xFFUL << MPU_TYPE_IREGION_Pos)               /*!< MPU TYPE: IREGION Mask */
-
-#define MPU_TYPE_DREGION_Pos                8                                             /*!< MPU TYPE: DREGION Position */
-#define MPU_TYPE_DREGION_Msk               (0xFFUL << MPU_TYPE_DREGION_Pos)               /*!< MPU TYPE: DREGION Mask */
-
-#define MPU_TYPE_SEPARATE_Pos               0                                             /*!< MPU TYPE: SEPARATE Position */
-#define MPU_TYPE_SEPARATE_Msk              (1UL << MPU_TYPE_SEPARATE_Pos)                 /*!< MPU TYPE: SEPARATE Mask */
-
-/* MPU Control Register */
-#define MPU_CTRL_PRIVDEFENA_Pos             2                                             /*!< MPU CTRL: PRIVDEFENA Position */
-#define MPU_CTRL_PRIVDEFENA_Msk            (1UL << MPU_CTRL_PRIVDEFENA_Pos)               /*!< MPU CTRL: PRIVDEFENA Mask */
-
-#define MPU_CTRL_HFNMIENA_Pos               1                                             /*!< MPU CTRL: HFNMIENA Position */
-#define MPU_CTRL_HFNMIENA_Msk              (1UL << MPU_CTRL_HFNMIENA_Pos)                 /*!< MPU CTRL: HFNMIENA Mask */
-
-#define MPU_CTRL_ENABLE_Pos                 0                                             /*!< MPU CTRL: ENABLE Position */
-#define MPU_CTRL_ENABLE_Msk                (1UL << MPU_CTRL_ENABLE_Pos)                   /*!< MPU CTRL: ENABLE Mask */
-
-/* MPU Region Number Register */
-#define MPU_RNR_REGION_Pos                  0                                             /*!< MPU RNR: REGION Position */
-#define MPU_RNR_REGION_Msk                 (0xFFUL << MPU_RNR_REGION_Pos)                 /*!< MPU RNR: REGION Mask */
-
-/* MPU Region Base Address Register */
-#define MPU_RBAR_ADDR_Pos                   8                                             /*!< MPU RBAR: ADDR Position */
-#define MPU_RBAR_ADDR_Msk                  (0xFFFFFFUL << MPU_RBAR_ADDR_Pos)              /*!< MPU RBAR: ADDR Mask */
-
-#define MPU_RBAR_VALID_Pos                  4                                             /*!< MPU RBAR: VALID Position */
-#define MPU_RBAR_VALID_Msk                 (1UL << MPU_RBAR_VALID_Pos)                    /*!< MPU RBAR: VALID Mask */
-
-#define MPU_RBAR_REGION_Pos                 0                                             /*!< MPU RBAR: REGION Position */
-#define MPU_RBAR_REGION_Msk                (0xFUL << MPU_RBAR_REGION_Pos)                 /*!< MPU RBAR: REGION Mask */
-
-/* MPU Region Attribute and Size Register */
-#define MPU_RASR_ATTRS_Pos                 16                                             /*!< MPU RASR: MPU Region Attribute field Position */
-#define MPU_RASR_ATTRS_Msk                 (0xFFFFUL << MPU_RASR_ATTRS_Pos)               /*!< MPU RASR: MPU Region Attribute field Mask */
-
-#define MPU_RASR_XN_Pos                    28                                             /*!< MPU RASR: ATTRS.XN Position */
-#define MPU_RASR_XN_Msk                    (1UL << MPU_RASR_XN_Pos)                       /*!< MPU RASR: ATTRS.XN Mask */
-
-#define MPU_RASR_AP_Pos                    24                                             /*!< MPU RASR: ATTRS.AP Position */
-#define MPU_RASR_AP_Msk                    (0x7UL << MPU_RASR_AP_Pos)                     /*!< MPU RASR: ATTRS.AP Mask */
-
-#define MPU_RASR_TEX_Pos                   19                                             /*!< MPU RASR: ATTRS.TEX Position */
-#define MPU_RASR_TEX_Msk                   (0x7UL << MPU_RASR_TEX_Pos)                    /*!< MPU RASR: ATTRS.TEX Mask */
-
-#define MPU_RASR_S_Pos                     18                                             /*!< MPU RASR: ATTRS.S Position */
-#define MPU_RASR_S_Msk                     (1UL << MPU_RASR_S_Pos)                        /*!< MPU RASR: ATTRS.S Mask */
-
-#define MPU_RASR_C_Pos                     17                                             /*!< MPU RASR: ATTRS.C Position */
-#define MPU_RASR_C_Msk                     (1UL << MPU_RASR_C_Pos)                        /*!< MPU RASR: ATTRS.C Mask */
-
-#define MPU_RASR_B_Pos                     16                                             /*!< MPU RASR: ATTRS.B Position */
-#define MPU_RASR_B_Msk                     (1UL << MPU_RASR_B_Pos)                        /*!< MPU RASR: ATTRS.B Mask */
-
-#define MPU_RASR_SRD_Pos                    8                                             /*!< MPU RASR: Sub-Region Disable Position */
-#define MPU_RASR_SRD_Msk                   (0xFFUL << MPU_RASR_SRD_Pos)                   /*!< MPU RASR: Sub-Region Disable Mask */
-
-#define MPU_RASR_SIZE_Pos                   1                                             /*!< MPU RASR: Region Size Field Position */
-#define MPU_RASR_SIZE_Msk                  (0x1FUL << MPU_RASR_SIZE_Pos)                  /*!< MPU RASR: Region Size Field Mask */
-
-#define MPU_RASR_ENABLE_Pos                 0                                             /*!< MPU RASR: Region enable bit Position */
-#define MPU_RASR_ENABLE_Msk                (1UL << MPU_RASR_ENABLE_Pos)                   /*!< MPU RASR: Region enable bit Disable Mask */
-
-/*@} end of group CMSIS_MPU */
-#endif
-
-
-/** \ingroup  CMSIS_core_register
-    \defgroup CMSIS_CoreDebug       Core Debug Registers (CoreDebug)
-    \brief      Cortex-M0+ Core Debug Registers (DCB registers, SHCSR, and DFSR)
-                are only accessible over DAP and not via processor. Therefore
-                they are not covered by the Cortex-M0 header file.
-  @{
- */
-/*@} end of group CMSIS_CoreDebug */
-
-
-/** \ingroup    CMSIS_core_register
-    \defgroup   CMSIS_core_base     Core Definitions
-    \brief      Definitions for base addresses, unions, and structures.
-  @{
- */
-
-/* Memory mapping of Cortex-M0+ Hardware */
-#define SCS_BASE            (0xE000E000UL)                            /*!< System Control Space Base Address */
-#define SysTick_BASE        (SCS_BASE +  0x0010UL)                    /*!< SysTick Base Address              */
-#define NVIC_BASE           (SCS_BASE +  0x0100UL)                    /*!< NVIC Base Address                 */
-#define SCB_BASE            (SCS_BASE +  0x0D00UL)                    /*!< System Control Block Base Address */
-
-#define SCB                 ((SCB_Type       *)     SCB_BASE      )   /*!< SCB configuration struct           */
-#define SysTick             ((SysTick_Type   *)     SysTick_BASE  )   /*!< SysTick configuration struct       */
-#define NVIC                ((NVIC_Type      *)     NVIC_BASE     )   /*!< NVIC configuration struct          */
-
-#if (__MPU_PRESENT == 1)
-  #define MPU_BASE          (SCS_BASE +  0x0D90UL)                    /*!< Memory Protection Unit             */
-  #define MPU               ((MPU_Type       *)     MPU_BASE      )   /*!< Memory Protection Unit             */
-#endif
-
-/*@} */
-
-
-
-/*******************************************************************************
- *                Hardware Abstraction Layer
-  Core Function Interface contains:
-  - Core NVIC Functions
-  - Core SysTick Functions
-  - Core Register Access Functions
- ******************************************************************************/
-/** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference
-*/
-
-
-
-/* ##########################   NVIC functions  #################################### */
-/** \ingroup  CMSIS_Core_FunctionInterface
-    \defgroup CMSIS_Core_NVICFunctions NVIC Functions
-    \brief      Functions that manage interrupts and exceptions via the NVIC.
-    @{
- */
-
-/* Interrupt Priorities are WORD accessible only under ARMv6M                   */
-/* The following MACROS handle generation of the register offset and byte masks */
-#define _BIT_SHIFT(IRQn)         (  (((uint32_t)(IRQn)       )    &  0x03) * 8 )
-#define _SHP_IDX(IRQn)           ( ((((uint32_t)(IRQn) & 0x0F)-8) >>    2)     )
-#define _IP_IDX(IRQn)            (   ((uint32_t)(IRQn)            >>    2)     )
-
-
-/** \brief  Enable External Interrupt
-
-    The function enables a device-specific interrupt in the NVIC interrupt controller.
-
-    \param [in]      IRQn  External interrupt number. Value cannot be negative.
- */
-__STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn)
-{
-  NVIC->ISER[0] = (1 << ((uint32_t)(IRQn) & 0x1F));
-}
-
-
-/** \brief  Disable External Interrupt
-
-    The function disables a device-specific interrupt in the NVIC interrupt controller.
-
-    \param [in]      IRQn  External interrupt number. Value cannot be negative.
- */
-__STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn)
-{
-  NVIC->ICER[0] = (1 << ((uint32_t)(IRQn) & 0x1F));
-}
-
-
-/** \brief  Get Pending Interrupt
-
-    The function reads the pending register in the NVIC and returns the pending bit
-    for the specified interrupt.
-
-    \param [in]      IRQn  Interrupt number.
-
-    \return             0  Interrupt status is not pending.
-    \return             1  Interrupt status is pending.
- */
-__STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn)
-{
-  return((uint32_t) ((NVIC->ISPR[0] & (1 << ((uint32_t)(IRQn) & 0x1F)))?1:0));
-}
-
-
-/** \brief  Set Pending Interrupt
-
-    The function sets the pending bit of an external interrupt.
-
-    \param [in]      IRQn  Interrupt number. Value cannot be negative.
- */
-__STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn)
-{
-  NVIC->ISPR[0] = (1 << ((uint32_t)(IRQn) & 0x1F));
-}
-
-
-/** \brief  Clear Pending Interrupt
-
-    The function clears the pending bit of an external interrupt.
-
-    \param [in]      IRQn  External interrupt number. Value cannot be negative.
- */
-__STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn)
-{
-  NVIC->ICPR[0] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* Clear pending interrupt */
-}
-
-
-/** \brief  Set Interrupt Priority
-
-    The function sets the priority of an interrupt.
-
-    \note The priority cannot be set for every core interrupt.
-
-    \param [in]      IRQn  Interrupt number.
-    \param [in]  priority  Priority to set.
- */
-__STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority)
-{
-  if(IRQn < 0) {
-    SCB->SHP[_SHP_IDX(IRQn)] = (SCB->SHP[_SHP_IDX(IRQn)] & ~(0xFF << _BIT_SHIFT(IRQn))) |
-        (((priority << (8 - __NVIC_PRIO_BITS)) & 0xFF) << _BIT_SHIFT(IRQn)); }
-  else {
-    NVIC->IP[_IP_IDX(IRQn)] = (NVIC->IP[_IP_IDX(IRQn)] & ~(0xFF << _BIT_SHIFT(IRQn))) |
-        (((priority << (8 - __NVIC_PRIO_BITS)) & 0xFF) << _BIT_SHIFT(IRQn)); }
-}
-
-
-/** \brief  Get Interrupt Priority
-
-    The function reads the priority of an interrupt. The interrupt
-    number can be positive to specify an external (device specific)
-    interrupt, or negative to specify an internal (core) interrupt.
-
-
-    \param [in]   IRQn  Interrupt number.
-    \return             Interrupt Priority. Value is aligned automatically to the implemented
-                        priority bits of the microcontroller.
- */
-__STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn)
-{
-
-  if(IRQn < 0) {
-    return((uint32_t)(((SCB->SHP[_SHP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & 0xFF) >> (8 - __NVIC_PRIO_BITS)));  } /* get priority for Cortex-M0 system interrupts */
-  else {
-    return((uint32_t)(((NVIC->IP[ _IP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & 0xFF) >> (8 - __NVIC_PRIO_BITS)));  } /* get priority for device specific interrupts  */
-}
-
-
-/** \brief  System Reset
-
-    The function initiates a system reset request to reset the MCU.
- */
-__STATIC_INLINE void NVIC_SystemReset(void)
-{
-  __DSB();                                                     /* Ensure all outstanding memory accesses included
-                                                                  buffered write are completed before reset */
-  SCB->AIRCR  = ((0x5FA << SCB_AIRCR_VECTKEY_Pos)      |
-                 SCB_AIRCR_SYSRESETREQ_Msk);
-  __DSB();                                                     /* Ensure completion of memory access */
-  while(1);                                                    /* wait until reset */
-}
-
-/*@} end of CMSIS_Core_NVICFunctions */
-
-
-
-/* ##################################    SysTick function  ############################################ */
-/** \ingroup  CMSIS_Core_FunctionInterface
-    \defgroup CMSIS_Core_SysTickFunctions SysTick Functions
-    \brief      Functions that configure the System.
-  @{
- */
-
-#if (__Vendor_SysTickConfig == 0)
-
-/** \brief  System Tick Configuration
-
-    The function initializes the System Timer and its interrupt, and starts the System Tick Timer.
-    Counter is in free running mode to generate periodic interrupts.
-
-    \param [in]  ticks  Number of ticks between two interrupts.
-
-    \return          0  Function succeeded.
-    \return          1  Function failed.
-
-    \note     When the variable <b>__Vendor_SysTickConfig</b> is set to 1, then the
-    function <b>SysTick_Config</b> is not included. In this case, the file <b><i>device</i>.h</b>
-    must contain a vendor-specific implementation of this function.
-
- */
-__STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks)
-{
-  if ((ticks - 1) > SysTick_LOAD_RELOAD_Msk)  return (1);      /* Reload value impossible */
-
-  SysTick->LOAD  = ticks - 1;                                  /* set reload register */
-  NVIC_SetPriority (SysTick_IRQn, (1<<__NVIC_PRIO_BITS) - 1);  /* set Priority for Systick Interrupt */
-  SysTick->VAL   = 0;                                          /* Load the SysTick Counter Value */
-  SysTick->CTRL  = SysTick_CTRL_CLKSOURCE_Msk |
-                   SysTick_CTRL_TICKINT_Msk   |
-                   SysTick_CTRL_ENABLE_Msk;                    /* Enable SysTick IRQ and SysTick Timer */
-  return (0);                                                  /* Function successful */
-}
-
-#endif
-
-/*@} end of CMSIS_Core_SysTickFunctions */
-
-
-
-
-#endif /* __CORE_CM0PLUS_H_DEPENDANT */
-
-#endif /* __CMSIS_GENERIC */
-
-#ifdef __cplusplus
-}
-#endif



[35/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/src/os_dev.c
----------------------------------------------------------------------
diff --git a/kernel/os/src/os_dev.c b/kernel/os/src/os_dev.c
new file mode 100644
index 0000000..fa8709b
--- /dev/null
+++ b/kernel/os/src/os_dev.c
@@ -0,0 +1,309 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include "os/os.h"
+#include "os/queue.h"
+#include "os/os_dev.h"
+
+#include <string.h>
+
+static STAILQ_HEAD(, os_dev) g_os_dev_list;
+
+static int
+os_dev_init(struct os_dev *dev, char *name, uint8_t stage,
+        uint8_t priority, os_dev_init_func_t od_init, void *arg)
+{
+    dev->od_name = name;
+    dev->od_stage = stage;
+    dev->od_priority = priority;
+    /* assume these are set after the fact. */
+    dev->od_flags = 0;
+    dev->od_open_ref = 0;
+    dev->od_init = od_init;
+    dev->od_init_arg = arg;
+    memset(&dev->od_handlers, 0, sizeof(dev->od_handlers));
+
+    return (0);
+}
+
+/**
+ * Add the device to the device tree.  This is a private function.
+ *
+ * @param dev The device to add to the device tree.
+ *
+ * @return 0 on success, non-zero on failure.
+ */
+static int
+os_dev_add(struct os_dev *dev)
+{
+    struct os_dev *cur_dev;
+
+    /* If no devices present, insert into head */
+    if (STAILQ_FIRST(&g_os_dev_list) == NULL) {
+        STAILQ_INSERT_HEAD(&g_os_dev_list, dev, od_next);
+        return (0);
+    }
+
+    /* Add devices to the list, sorted first by stage, then by
+     * priority.  Keep sorted in this order for initialization
+     * stage.
+     */
+    cur_dev = NULL;
+    STAILQ_FOREACH(cur_dev, &g_os_dev_list, od_next) {
+        if (cur_dev->od_stage > dev->od_stage) {
+            continue;
+        }
+
+        if (dev->od_priority >= cur_dev->od_priority) {
+            break;
+        }
+    }
+
+    if (cur_dev) {
+        STAILQ_INSERT_AFTER(&g_os_dev_list, cur_dev, dev, od_next);
+    } else {
+        STAILQ_INSERT_TAIL(&g_os_dev_list, dev, od_next);
+    }
+
+    return (0);
+}
+
+
+/**
+ * Create a new device in the kernel.
+ *
+ * @param dev The device to create.
+ * @param name The name of the device to create.
+ * @param stage The stage to initialize that device to.
+ * @param priority The priority of initializing that device
+ * @param od_init The initialization function to call for this
+ *                device.
+ * @param arg The argument to provide this device initialization
+ *            function.
+ *
+ * @return 0 on success, non-zero on failure.
+ */
+int
+os_dev_create(struct os_dev *dev, char *name, uint8_t stage,
+        uint8_t priority, os_dev_init_func_t od_init, void *arg)
+{
+    int rc;
+
+    rc = os_dev_init(dev, name, stage, priority, od_init, arg);
+    if (rc != 0) {
+        goto err;
+    }
+
+    rc = os_dev_add(dev);
+    if (rc != 0) {
+        goto err;
+    }
+
+    return (0);
+err:
+    return (rc);
+}
+
+/**
+ * Initialize all devices for a given state.
+ *
+ * @param stage The stage to initialize.
+ *
+ * @return 0 on success, non-zero on failure.
+ */
+int
+os_dev_initialize_all(uint8_t stage)
+{
+    struct os_dev *dev;
+    int rc;
+
+    STAILQ_FOREACH(dev, &g_os_dev_list, od_next) {
+        if (dev->od_stage == stage) {
+            rc = dev->od_init(dev, dev->od_init_arg);
+            if (rc != 0) {
+                if (dev->od_flags & OS_DEV_F_INIT_CRITICAL) {
+                    goto err;
+                }
+            } else {
+                dev->od_flags |= OS_DEV_F_STATUS_READY;
+            }
+        }
+    }
+
+    return (0);
+err:
+    return (rc);
+}
+
+/**
+ * Suspend all devices.
+ *
+ * @param dev The device to suspend
+ * @param suspend_t The number of ticks to suspend this device for
+ * @param force Whether or not to force suspending the device
+ *
+ * @return 0 on success, or a non-zero error code if one of the devices
+ *                       returned it.
+ */
+int
+os_dev_suspend_all(os_time_t suspend_t, uint8_t force)
+{
+    struct os_dev *dev;
+    int suspend_failure;
+    int rc;
+
+    suspend_failure = 0;
+    STAILQ_FOREACH(dev, &g_os_dev_list, od_next) {
+        rc = os_dev_suspend(dev, suspend_t, force);
+        if (rc != 0) {
+            suspend_failure = OS_ERROR;
+        }
+    }
+
+    return (suspend_failure);
+}
+
+/**
+ * Resume all the devices that were suspended.
+ *
+ * @return 0 on success, -1 if any of the devices have failed to resume.
+ */
+int
+os_dev_resume_all(void)
+{
+    struct os_dev *dev;
+    int rc;
+
+    STAILQ_FOREACH(dev, &g_os_dev_list, od_next) {
+        rc = os_dev_resume(dev);
+        if (rc != 0) {
+            goto err;
+        }
+    }
+
+    return (0);
+err:
+    return (rc);
+}
+
+/**
+ * Lookup a device by name, internal function only.
+ *
+ * @param name The name of the device to look up.
+ *
+ * @return A pointer to the device corresponding to name, or NULL if not found.
+ */
+static struct os_dev *
+os_dev_lookup(char *name)
+{
+    struct os_dev *dev;
+
+    dev = NULL;
+    STAILQ_FOREACH(dev, &g_os_dev_list, od_next) {
+        if (!strcmp(dev->od_name, name)) {
+            break;
+        }
+    }
+    return (dev);
+}
+
+/**
+ * Open a device.
+ *
+ * @param dev The device to open
+ * @param timo The timeout to open the device, if not specified.
+ * @param arg The argument to the device open() call.
+ *
+ * @return 0 on success, non-zero on failure.
+ */
+struct os_dev *
+os_dev_open(char *devname, uint32_t timo, void *arg)
+{
+    struct os_dev *dev;
+    os_sr_t sr;
+    int rc;
+
+    dev = os_dev_lookup(devname);
+    if (dev == NULL) {
+        return (NULL);
+    }
+
+    /* Device is not ready to be opened. */
+    if ((dev->od_flags & OS_DEV_F_STATUS_READY) == 0) {
+        return (NULL);
+    }
+
+    if (dev->od_handlers.od_open) {
+        rc = dev->od_handlers.od_open(dev, timo, arg);
+        if (rc != 0) {
+            goto err;
+        }
+    }
+
+    OS_ENTER_CRITICAL(sr);
+    ++dev->od_open_ref;
+    dev->od_flags |= OS_DEV_F_STATUS_OPEN;
+    OS_EXIT_CRITICAL(sr);
+
+    return (dev);
+err:
+    return (NULL);
+}
+
+/**
+ * Close a device.
+ *
+ * @param dev The device to close
+ *
+ * @return 0 on success, non-zero on failure.
+ */
+int
+os_dev_close(struct os_dev *dev)
+{
+    int rc;
+    os_sr_t sr;
+
+    if (dev->od_handlers.od_close) {
+        rc = dev->od_handlers.od_close(dev);
+        if (rc != 0) {
+            goto err;
+        }
+    }
+
+    OS_ENTER_CRITICAL(sr);
+    if (--dev->od_open_ref == 0) {
+        dev->od_flags &= ~OS_DEV_F_STATUS_OPEN;
+    }
+    OS_EXIT_CRITICAL(sr);
+
+    return (0);
+err:
+    return (rc);
+}
+
+/**
+ * Clears the device list.  This function does not close any devices or free
+ * any resources; its purpose is to allow a full system reset between unit
+ * tests.
+ */
+void
+os_dev_reset(void)
+{
+    STAILQ_INIT(&g_os_dev_list);
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/src/os_eventq.c
----------------------------------------------------------------------
diff --git a/kernel/os/src/os_eventq.c b/kernel/os/src/os_eventq.c
new file mode 100644
index 0000000..f9cc283
--- /dev/null
+++ b/kernel/os/src/os_eventq.c
@@ -0,0 +1,235 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+
+#include "os/os.h"
+
+#include <string.h>
+
+/**
+ * Initialize the event queue
+ *
+ * @param evq The event queue to initialize
+ */
+void
+os_eventq_init(struct os_eventq *evq)
+{
+    memset(evq, 0, sizeof(*evq));
+    STAILQ_INIT(&evq->evq_list);
+}
+
+/**
+ * Put an event on the event queue.
+ *
+ * @param evq The event queue to put an event on 
+ * @param ev The event to put on the queue
+ */
+void
+os_eventq_put(struct os_eventq *evq, struct os_event *ev)
+{
+    int resched;
+    os_sr_t sr;
+
+    OS_ENTER_CRITICAL(sr);
+
+    /* Do not queue if already queued */
+    if (OS_EVENT_QUEUED(ev)) {
+        OS_EXIT_CRITICAL(sr);
+        return;
+    }
+
+    /* Queue the event */
+    ev->ev_queued = 1;
+    STAILQ_INSERT_TAIL(&evq->evq_list, ev, ev_next);
+
+    resched = 0;
+    if (evq->evq_task) {
+        /* If task waiting on event, wake it up.
+         * Check if task is sleeping, because another event 
+         * queue may have woken this task up beforehand.
+         */
+        if (evq->evq_task->t_state == OS_TASK_SLEEP) {
+            os_sched_wakeup(evq->evq_task);
+            resched = 1;
+        }
+        /* Either way, NULL out the task, because the task will
+         * be awake upon exit of this function.
+         */
+        evq->evq_task = NULL;
+    }
+
+    OS_EXIT_CRITICAL(sr);
+
+    if (resched) {
+        os_sched(NULL);
+    }
+}
+
+/**
+ * Pull a single item from an event queue.  This function blocks until there 
+ * is an item on the event queue to read.
+ *
+ * @param evq The event queue to pull an event from
+ *
+ * @return The event from the queue
+ */
+struct os_event *
+os_eventq_get(struct os_eventq *evq)
+{
+    struct os_event *ev;
+    os_sr_t sr;
+
+    OS_ENTER_CRITICAL(sr);
+pull_one:
+    ev = STAILQ_FIRST(&evq->evq_list);
+    if (ev) {
+        STAILQ_REMOVE(&evq->evq_list, ev, os_event, ev_next);
+        ev->ev_queued = 0;
+    } else {
+        evq->evq_task = os_sched_get_current_task();
+        os_sched_sleep(evq->evq_task, OS_TIMEOUT_NEVER);
+        OS_EXIT_CRITICAL(sr);
+
+        os_sched(NULL);
+
+        OS_ENTER_CRITICAL(sr);
+        evq->evq_task = NULL;
+        goto pull_one;
+    }
+    OS_EXIT_CRITICAL(sr);
+
+    return (ev);
+}
+
+static struct os_event *
+os_eventq_poll_0timo(struct os_eventq **evq, int nevqs)
+{
+    struct os_event *ev;
+    os_sr_t sr;
+    int i;
+
+    ev = NULL;
+
+    OS_ENTER_CRITICAL(sr);
+    for (i = 0; i < nevqs; i++) {
+        ev = STAILQ_FIRST(&evq[i]->evq_list);
+        if (ev) {
+            STAILQ_REMOVE(&evq[i]->evq_list, ev, os_event, ev_next);
+            ev->ev_queued = 0;
+            break;
+        }
+    }
+    OS_EXIT_CRITICAL(sr);
+
+    return ev;
+}
+
+/**
+ * Poll the list of event queues specified by the evq parameter 
+ * (size nevqs), and return the "first" event available on any of 
+ * the queues.  Event queues are searched in the order that they 
+ * are passed in the array.
+ *
+ * @param evq Array of event queues
+ * @param nevqs Number of event queues in evq
+ * @param timo Timeout, forever if OS_WAIT_FOREVER is passed to poll.
+ *
+ * @return An event, or NULL if no events available
+ */
+struct os_event *
+os_eventq_poll(struct os_eventq **evq, int nevqs, os_time_t timo)
+{
+    struct os_event *ev;
+    struct os_task *cur_t;
+    int i, j;
+    os_sr_t sr;
+
+    /* If the timeout is 0, don't involve the scheduler at all.  Grab an event
+     * if one is available, else return immediately.
+     */
+    if (timo == 0) {
+        return os_eventq_poll_0timo(evq, nevqs);
+    }
+
+    ev = NULL;
+
+    OS_ENTER_CRITICAL(sr);
+    cur_t = os_sched_get_current_task();
+
+    for (i = 0; i < nevqs; i++) {
+        ev = STAILQ_FIRST(&evq[i]->evq_list);
+        if (ev) {
+            STAILQ_REMOVE(&evq[i]->evq_list, ev, os_event, ev_next);
+            ev->ev_queued = 0;
+            /* Reset the items that already have an evq task set. */
+            for (j = 0; j < i; j++) {
+                evq[j]->evq_task = NULL;
+            }
+
+            OS_EXIT_CRITICAL(sr);
+            goto has_event;
+        }
+        evq[i]->evq_task = cur_t;
+    }
+
+    os_sched_sleep(cur_t, timo);
+    OS_EXIT_CRITICAL(sr);
+
+    os_sched(NULL);
+
+    OS_ENTER_CRITICAL(sr);
+    for (i = 0; i < nevqs; i++) {
+        /* Go through the entire loop to clear the evq_task variable, 
+         * given this task is no longer sleeping on the event queues.
+         * Return the first event found, so only grab the event if 
+         * we haven't found one.
+         */
+        if (!ev) {
+            ev = STAILQ_FIRST(&evq[i]->evq_list);
+            if (ev) {
+                STAILQ_REMOVE(&evq[i]->evq_list, ev, os_event, ev_next);
+                ev->ev_queued = 0;
+            }
+        }
+        evq[i]->evq_task = NULL;
+    }
+    OS_EXIT_CRITICAL(sr);
+
+has_event:
+    return (ev);
+}
+
+/**
+ * Remove an event from the queue.
+ *
+ * @param evq The event queue to remove the event from
+ * @param ev  The event to remove from the queue
+ */
+void
+os_eventq_remove(struct os_eventq *evq, struct os_event *ev)
+{
+    os_sr_t sr;
+
+    OS_ENTER_CRITICAL(sr);
+    if (OS_EVENT_QUEUED(ev)) {
+        STAILQ_REMOVE(&evq->evq_list, ev, os_event, ev_next);
+    }
+    ev->ev_queued = 0;
+    OS_EXIT_CRITICAL(sr);
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/src/os_heap.c
----------------------------------------------------------------------
diff --git a/kernel/os/src/os_heap.c b/kernel/os/src/os_heap.c
new file mode 100644
index 0000000..5f5af95
--- /dev/null
+++ b/kernel/os/src/os_heap.c
@@ -0,0 +1,106 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+
+#include <assert.h>
+#include "os/os_mutex.h"
+#include "os/os_heap.h"
+
+static struct os_mutex os_malloc_mutex;
+
+static void
+os_malloc_lock(void)
+{
+    int rc;
+
+    if (g_os_started) {
+        rc = os_mutex_pend(&os_malloc_mutex, 0xffffffff);
+        assert(rc == 0);
+    }
+}
+
+static void
+os_malloc_unlock(void)
+{
+    int rc;
+
+    if (g_os_started) {
+        rc = os_mutex_release(&os_malloc_mutex);
+        assert(rc == 0);
+    }
+}
+
+/**
+ * Operating system level malloc().   This ensures that a safe malloc occurs
+ * within the context of the OS.  Depending on platform, the OS may rely on
+ * libc's malloc() implementation, which is not guaranteed to be thread-safe.
+ * This malloc() will always be thread-safe.
+ *
+ * @param size The number of bytes to allocate
+ *
+ * @return A pointer to the memory region allocated.
+ */
+void *
+os_malloc(size_t size)
+{
+    void *ptr;
+
+    os_malloc_lock();
+    ptr = malloc(size);
+    os_malloc_unlock();
+
+    return ptr;
+}
+
+/**
+ * Operating system level free().  See description of os_malloc() for reasoning.
+ *
+ * Free's memory allocated by malloc.
+ *
+ * @param mem The memory to free.
+ */
+void
+os_free(void *mem)
+{
+    os_malloc_lock();
+    free(mem);
+    os_malloc_unlock();
+}
+
+/**
+ * Operating system level realloc(). See description of os_malloc() for reasoning.
+ *
+ * Reallocates the memory at ptr, to be size contiguouos bytes.
+ *
+ * @param ptr A pointer to the memory to allocate
+ * @param size The number of contiguouos bytes to allocate at that location
+ *
+ * @return A pointer to memory of size, or NULL on failure to allocate
+ */
+void *
+os_realloc(void *ptr, size_t size)
+{
+    void *new_ptr;
+
+    os_malloc_lock();
+    new_ptr = realloc(ptr, size);
+    os_malloc_unlock();
+
+    return new_ptr;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/src/os_mbuf.c
----------------------------------------------------------------------
diff --git a/kernel/os/src/os_mbuf.c b/kernel/os/src/os_mbuf.c
new file mode 100644
index 0000000..c7183f9
--- /dev/null
+++ b/kernel/os/src/os_mbuf.c
@@ -0,0 +1,1270 @@
+/*
+ * Software in this file is based heavily on code written in the FreeBSD source
+ * code repostiory.  While the code is written from scratch, it contains
+ * many of the ideas and logic flow in the original source, this is a
+ * derivative work, and the following license applies as well:
+ *
+ * Copyright (c) 1982, 1986, 1988, 1991, 1993
+ *  The Regents of the University of California.  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.
+ * 4. Neither the name of the University 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 REGENTS 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 REGENTS 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 "os/os.h"
+
+#include <assert.h>
+#include <string.h>
+#include <limits.h>
+
+STAILQ_HEAD(, os_mbuf_pool) g_msys_pool_list =
+    STAILQ_HEAD_INITIALIZER(g_msys_pool_list);
+
+/**
+ * Initialize a mbuf queue.  An mbuf queue is a queue of mbufs that tie
+ * to a specific task's event queue.  Mbuf queues are a helper API around
+ * a common paradigm, which is to wait on an event queue, until at least
+ * 1 packet is available, and then process a queue of packets.
+ *
+ * When mbufs are available on the queue, an event OS_EVENT_T_MQUEUE_DATA
+ * will be posted to the task's mbuf queue.
+ *
+ * @param mq The mbuf queue to initialize
+ * @param arg The argument to provide to the event posted on this mbuf queue
+ *
+ * @return 0 on success, non-zero on failure.
+ *
+ */
+int
+os_mqueue_init(struct os_mqueue *mq, void *arg)
+{
+    struct os_event *ev;
+
+    STAILQ_INIT(&mq->mq_head);
+
+    ev = &mq->mq_ev;
+    memset(ev, 0, sizeof(*ev));
+    ev->ev_arg = arg;
+    ev->ev_type = OS_EVENT_T_MQUEUE_DATA;
+
+    return (0);
+}
+
+/**
+ * Remove and return a single mbuf from the mbuf queue.  Does not block.
+ *
+ * @param mq The mbuf queue to pull an element off of.
+ *
+ * @return The next mbuf in the queue, or NULL if queue has no mbufs.
+ */
+struct os_mbuf *
+os_mqueue_get(struct os_mqueue *mq)
+{
+    struct os_mbuf_pkthdr *mp;
+    struct os_mbuf *m;
+    os_sr_t sr;
+
+    OS_ENTER_CRITICAL(sr);
+    mp = STAILQ_FIRST(&mq->mq_head);
+    if (mp) {
+        STAILQ_REMOVE_HEAD(&mq->mq_head, omp_next);
+    }
+    OS_EXIT_CRITICAL(sr);
+
+    if (mp) {
+        m = OS_MBUF_PKTHDR_TO_MBUF(mp);
+    } else {
+        m = NULL;
+    }
+
+    return (m);
+}
+
+/**
+ * Put a new mbuf in the mbuf queue.  Appends an mbuf to the end of the
+ * mbuf queue, and posts an event to the event queue passed in.
+ *
+ * @param mq The mbuf queue to append the mbuf to
+ * @param evq The event queue to post an OS_EVENT_T_MQUEUE_DATA event to
+ * @param m The mbuf to append to the mbuf queue
+ *
+ * @return 0 on success, non-zero on failure.
+ */
+int
+os_mqueue_put(struct os_mqueue *mq, struct os_eventq *evq, struct os_mbuf *m)
+{
+    struct os_mbuf_pkthdr *mp;
+    os_sr_t sr;
+    int rc;
+
+    /* Can only place the head of a chained mbuf on the queue. */
+    if (!OS_MBUF_IS_PKTHDR(m)) {
+        rc = OS_EINVAL;
+        goto err;
+    }
+
+    mp = OS_MBUF_PKTHDR(m);
+
+    OS_ENTER_CRITICAL(sr);
+    STAILQ_INSERT_TAIL(&mq->mq_head, mp, omp_next);
+    OS_EXIT_CRITICAL(sr);
+
+    /* Only post an event to the queue if its specified */
+    if (evq) {
+        os_eventq_put(evq, &mq->mq_ev);
+    }
+
+    return (0);
+err:
+    return (rc);
+}
+
+/**
+ * MSYS is a system level mbuf registry.  Allows the system to share
+ * packet buffers amongst the various networking stacks that can be running
+ * simultaeneously.
+ *
+ * Mbuf pools are created in the system initialization code, and then when
+ * a mbuf is allocated out of msys, it will try and find the best fit based
+ * upon estimated mbuf size.
+ *
+ * os_msys_register() registers a mbuf pool with MSYS, and allows MSYS to
+ * allocate mbufs out of it.
+ *
+ * @param new_pool The pool to register with MSYS
+ *
+ * @return 0 on success, non-zero on failure
+ */
+int
+os_msys_register(struct os_mbuf_pool *new_pool)
+{
+    struct os_mbuf_pool *pool;
+
+    pool = NULL;
+    STAILQ_FOREACH(pool, &g_msys_pool_list, omp_next) {
+        if (new_pool->omp_databuf_len > pool->omp_databuf_len) {
+            break;
+        }
+    }
+
+    if (pool) {
+        STAILQ_INSERT_AFTER(&g_msys_pool_list, pool, new_pool, omp_next);
+    } else {
+        STAILQ_INSERT_TAIL(&g_msys_pool_list, new_pool, omp_next);
+    }
+
+    return (0);
+}
+
+/**
+ * De-registers all mbuf pools from msys.
+ */
+void
+os_msys_reset(void)
+{
+    STAILQ_INIT(&g_msys_pool_list);
+}
+
+static struct os_mbuf_pool *
+_os_msys_find_pool(uint16_t dsize)
+{
+    struct os_mbuf_pool *pool;
+
+    pool = NULL;
+    STAILQ_FOREACH(pool, &g_msys_pool_list, omp_next) {
+        if (dsize <= pool->omp_databuf_len) {
+            break;
+        }
+    }
+
+    if (!pool) {
+        pool = STAILQ_LAST(&g_msys_pool_list, os_mbuf_pool, omp_next);
+    }
+
+    return (pool);
+}
+
+/**
+ * Allocate a mbuf from msys.  Based upon the data size requested,
+ * os_msys_get() will choose the mbuf pool that has the best fit.
+ *
+ * @param dsize The estimated size of the data being stored in the mbuf
+ * @param leadingspace The amount of leadingspace to allocate in the mbuf
+ *
+ * @return A freshly allocated mbuf on success, NULL on failure.
+ *
+ */
+struct os_mbuf *
+os_msys_get(uint16_t dsize, uint16_t leadingspace)
+{
+    struct os_mbuf *m;
+    struct os_mbuf_pool *pool;
+
+    pool = _os_msys_find_pool(dsize);
+    if (!pool) {
+        goto err;
+    }
+
+    m = os_mbuf_get(pool, leadingspace);
+    return (m);
+err:
+    return (NULL);
+}
+
+/**
+ * Allocate a packet header structure from the MSYS pool.  See
+ * os_msys_register() for a description of MSYS.
+ *
+ * @param dsize The estimated size of the data being stored in the mbuf
+ * @param user_hdr_len The length to allocate for the packet header structure
+ *
+ * @return A freshly allocated mbuf on success, NULL on failure.
+ */
+struct os_mbuf *
+os_msys_get_pkthdr(uint16_t dsize, uint16_t user_hdr_len)
+{
+    uint16_t total_pkthdr_len;
+    struct os_mbuf *m;
+    struct os_mbuf_pool *pool;
+
+    total_pkthdr_len =  user_hdr_len + sizeof(struct os_mbuf_pkthdr);
+    pool = _os_msys_find_pool(dsize + total_pkthdr_len);
+    if (!pool) {
+        goto err;
+    }
+
+    m = os_mbuf_get_pkthdr(pool, user_hdr_len);
+    return (m);
+err:
+    return (NULL);
+}
+
+int
+os_msys_count(void)
+{
+    struct os_mbuf_pool *omp;
+    int total;
+
+    total = 0;
+    STAILQ_FOREACH(omp, &g_msys_pool_list, omp_next) {
+        total += omp->omp_pool->mp_num_blocks;
+    }
+
+    return total;
+}
+
+int
+os_msys_num_free(void)
+{
+    struct os_mbuf_pool *omp;
+    int total;
+
+    total = 0;
+    STAILQ_FOREACH(omp, &g_msys_pool_list, omp_next) {
+        total += omp->omp_pool->mp_num_free;
+    }
+
+    return total;
+}
+
+/**
+ * Initialize a pool of mbufs.
+ *
+ * @param omp     The mbuf pool to initialize
+ * @param mp      The memory pool that will hold this mbuf pool
+ * @param buf_len The length of the buffer itself.
+ * @param nbufs   The number of buffers in the pool
+ *
+ * @return 0 on success, error code on failure.
+ */
+int
+os_mbuf_pool_init(struct os_mbuf_pool *omp, struct os_mempool *mp,
+                  uint16_t buf_len, uint16_t nbufs)
+{
+    omp->omp_databuf_len = buf_len - sizeof(struct os_mbuf);
+    omp->omp_mbuf_count = nbufs;
+    omp->omp_pool = mp;
+
+    return (0);
+}
+
+/**
+ * Get an mbuf from the mbuf pool.  The mbuf is allocated, and initialized
+ * prior to being returned.
+ *
+ * @param omp The mbuf pool to return the packet from
+ * @param leadingspace The amount of leadingspace to put before the data
+ *     section by default.
+ *
+ * @return An initialized mbuf on success, and NULL on failure.
+ */
+struct os_mbuf *
+os_mbuf_get(struct os_mbuf_pool *omp, uint16_t leadingspace)
+{
+    struct os_mbuf *om;
+
+    if (leadingspace > omp->omp_databuf_len) {
+        goto err;
+    }
+
+    om = os_memblock_get(omp->omp_pool);
+    if (!om) {
+        goto err;
+    }
+
+    SLIST_NEXT(om, om_next) = NULL;
+    om->om_flags = 0;
+    om->om_pkthdr_len = 0;
+    om->om_len = 0;
+    om->om_data = (&om->om_databuf[0] + leadingspace);
+    om->om_omp = omp;
+
+    return (om);
+err:
+    return (NULL);
+}
+
+/**
+ * Allocate a new packet header mbuf out of the os_mbuf_pool.
+ *
+ * @param omp The mbuf pool to allocate out of
+ * @param user_pkthdr_len The packet header length to reserve for the caller.
+ *
+ * @return A freshly allocated mbuf on success, NULL on failure.
+ */
+struct os_mbuf *
+os_mbuf_get_pkthdr(struct os_mbuf_pool *omp, uint8_t user_pkthdr_len)
+{
+    uint16_t pkthdr_len;
+    struct os_mbuf_pkthdr *pkthdr;
+    struct os_mbuf *om;
+
+    /* User packet header must fit inside mbuf */
+    pkthdr_len = user_pkthdr_len + sizeof(struct os_mbuf_pkthdr);
+    if ((pkthdr_len > omp->omp_databuf_len) || (pkthdr_len > 255)) {
+        return NULL;
+    }
+
+    om = os_mbuf_get(omp, 0);
+    if (om) {
+        om->om_pkthdr_len = pkthdr_len;
+        om->om_data += pkthdr_len;
+
+        pkthdr = OS_MBUF_PKTHDR(om);
+        pkthdr->omp_len = 0;
+        pkthdr->omp_flags = 0;
+        STAILQ_NEXT(pkthdr, omp_next) = NULL;
+    }
+
+    return om;
+}
+
+/**
+ * Release a mbuf back to the pool
+ *
+ * @param omp The Mbuf pool to release back to
+ * @param om  The Mbuf to release back to the pool
+ *
+ * @return 0 on success, -1 on failure
+ */
+int
+os_mbuf_free(struct os_mbuf *om)
+{
+    int rc;
+
+    if (om->om_omp != NULL) {
+        rc = os_memblock_put(om->om_omp->omp_pool, om);
+        if (rc != 0) {
+            goto err;
+        }
+    }
+
+    return (0);
+err:
+    return (rc);
+}
+
+/**
+ * Free a chain of mbufs
+ *
+ * @param omp The mbuf pool to free the chain of mbufs into
+ * @param om  The starting mbuf of the chain to free back into the pool
+ *
+ * @return 0 on success, -1 on failure
+ */
+int
+os_mbuf_free_chain(struct os_mbuf *om)
+{
+    struct os_mbuf *next;
+    int rc;
+
+    while (om != NULL) {
+        next = SLIST_NEXT(om, om_next);
+
+        rc = os_mbuf_free(om);
+        if (rc != 0) {
+            goto err;
+        }
+
+        om = next;
+    }
+
+    return (0);
+err:
+    return (rc);
+}
+
+/**
+ * Copy a packet header from one mbuf to another.
+ *
+ * @param omp The mbuf pool associated with these buffers
+ * @param new_buf The new buffer to copy the packet header into
+ * @param old_buf The old buffer to copy the packet header from
+ */
+static inline void
+_os_mbuf_copypkthdr(struct os_mbuf *new_buf, struct os_mbuf *old_buf)
+{
+    assert(new_buf->om_len == 0);
+
+    memcpy(&new_buf->om_databuf[0], &old_buf->om_databuf[0],
+           old_buf->om_pkthdr_len);
+    new_buf->om_pkthdr_len = old_buf->om_pkthdr_len;
+    new_buf->om_data = new_buf->om_databuf + old_buf->om_pkthdr_len;
+}
+
+/**
+ * Append data onto a mbuf
+ *
+ * @param om   The mbuf to append the data onto
+ * @param data The data to append onto the mbuf
+ * @param len  The length of the data to append
+ *
+ * @return 0 on success, and an error code on failure
+ */
+int
+os_mbuf_append(struct os_mbuf *om, const void *data,  uint16_t len)
+{
+    struct os_mbuf_pool *omp;
+    struct os_mbuf *last;
+    struct os_mbuf *new;
+    int remainder;
+    int space;
+    int rc;
+
+    if (om == NULL) {
+        rc = OS_EINVAL;
+        goto err;
+    }
+
+    omp = om->om_omp;
+
+    /* Scroll to last mbuf in the chain */
+    last = om;
+    while (SLIST_NEXT(last, om_next) != NULL) {
+        last = SLIST_NEXT(last, om_next);
+    }
+
+    remainder = len;
+    space = OS_MBUF_TRAILINGSPACE(last);
+
+    /* If room in current mbuf, copy the first part of the data into the
+     * remaining space in that mbuf.
+     */
+    if (space > 0) {
+        if (space > remainder) {
+            space = remainder;
+        }
+
+        memcpy(OS_MBUF_DATA(last, uint8_t *) + last->om_len , data, space);
+
+        last->om_len += space;
+        data += space;
+        remainder -= space;
+    }
+
+    /* Take the remaining data, and keep allocating new mbufs and copying
+     * data into it, until data is exhausted.
+     */
+    while (remainder > 0) {
+        new = os_mbuf_get(omp, 0);
+        if (!new) {
+            break;
+        }
+
+        new->om_len = min(omp->omp_databuf_len, remainder);
+        memcpy(OS_MBUF_DATA(new, void *), data, new->om_len);
+        data += new->om_len;
+        remainder -= new->om_len;
+        SLIST_NEXT(last, om_next) = new;
+        last = new;
+    }
+
+    /* Adjust the packet header length in the buffer */
+    if (OS_MBUF_IS_PKTHDR(om)) {
+        OS_MBUF_PKTHDR(om)->omp_len += len - remainder;
+    }
+
+    if (remainder != 0) {
+        rc = OS_ENOMEM;
+        goto err;
+    }
+
+
+    return (0);
+err:
+    return (rc);
+}
+
+/**
+ * Reads data from one mbuf and appends it to another.  On error, the specified
+ * data range may be partially appended.  Neither mbuf is required to contain
+ * an mbuf packet header.
+ *
+ * @param dst                   The mbuf to append to.
+ * @param src                   The mbuf to copy data from.
+ * @param src_off               The absolute offset within the source mbuf
+ *                                  chain to read from.
+ * @param len                   The number of bytes to append.
+ *
+ * @return                      0 on success;
+ *                              OS_EINVAL if the specified range extends beyond
+ *                                  the end of the source mbuf chain.
+ */
+int
+os_mbuf_appendfrom(struct os_mbuf *dst, const struct os_mbuf *src,
+                   uint16_t src_off, uint16_t len)
+{
+    const struct os_mbuf *src_cur_om;
+    uint16_t src_cur_off;
+    uint16_t chunk_sz;
+    int rc;
+
+    src_cur_om = os_mbuf_off(src, src_off, &src_cur_off);
+    while (len > 0) {
+        if (src_cur_om == NULL) {
+            return OS_EINVAL;
+        }
+
+        chunk_sz = min(len, src_cur_om->om_len - src_cur_off);
+        rc = os_mbuf_append(dst, src_cur_om->om_data + src_cur_off, chunk_sz);
+        if (rc != 0) {
+            return rc;
+        }
+
+        len -= chunk_sz;
+        src_cur_om = SLIST_NEXT(src_cur_om, om_next);
+        src_cur_off = 0;
+    }
+
+    return 0;
+}
+
+/**
+ * Duplicate a chain of mbufs.  Return the start of the duplicated chain.
+ *
+ * @param omp The mbuf pool to duplicate out of
+ * @param om  The mbuf chain to duplicate
+ *
+ * @return A pointer to the new chain of mbufs
+ */
+struct os_mbuf *
+os_mbuf_dup(struct os_mbuf *om)
+{
+    struct os_mbuf_pool *omp;
+    struct os_mbuf *head;
+    struct os_mbuf *copy;
+
+    omp = om->om_omp;
+
+    head = NULL;
+    copy = NULL;
+
+    for (; om != NULL; om = SLIST_NEXT(om, om_next)) {
+        if (head) {
+            SLIST_NEXT(copy, om_next) = os_mbuf_get(omp,
+                    OS_MBUF_LEADINGSPACE(om));
+            if (!SLIST_NEXT(copy, om_next)) {
+                os_mbuf_free_chain(head);
+                goto err;
+            }
+
+            copy = SLIST_NEXT(copy, om_next);
+        } else {
+            head = os_mbuf_get(omp, OS_MBUF_LEADINGSPACE(om));
+            if (!head) {
+                goto err;
+            }
+
+            if (OS_MBUF_IS_PKTHDR(om)) {
+                _os_mbuf_copypkthdr(head, om);
+            }
+            copy = head;
+        }
+        copy->om_flags = om->om_flags;
+        copy->om_len = om->om_len;
+        memcpy(OS_MBUF_DATA(copy, uint8_t *), OS_MBUF_DATA(om, uint8_t *),
+                om->om_len);
+    }
+
+    return (head);
+err:
+    return (NULL);
+}
+
+/**
+ * Locates the specified absolute offset within an mbuf chain.  The offset
+ * can be one past than the total length of the chain, but no greater.
+ *
+ * @param om                    The start of the mbuf chain to seek within.
+ * @param off                   The absolute address to find.
+ * @param out_off               On success, this points to the relative offset
+ *                                  within the returned mbuf.
+ *
+ * @return                      The mbuf containing the specified offset on
+ *                                  success.
+ *                              NULL if the specified offset is out of bounds.
+ */
+struct os_mbuf *
+os_mbuf_off(const struct os_mbuf *om, int off, uint16_t *out_off)
+{
+    struct os_mbuf *next;
+    struct os_mbuf *cur;
+
+    /* Cast away const. */
+    cur = (struct os_mbuf *)om;
+
+    while (1) {
+        if (cur == NULL) {
+            return NULL;
+        }
+
+        next = SLIST_NEXT(cur, om_next);
+
+        if (cur->om_len > off ||
+            (cur->om_len == off && next == NULL)) {
+
+            *out_off = off;
+            return cur;
+        }
+
+        off -= cur->om_len;
+        cur = next;
+    }
+}
+
+/*
+ * Copy data from an mbuf chain starting "off" bytes from the beginning,
+ * continuing for "len" bytes, into the indicated buffer.
+ *
+ * @param m The mbuf chain to copy from
+ * @param off The offset into the mbuf chain to begin copying from
+ * @param len The length of the data to copy
+ * @param dst The destination buffer to copy into
+ *
+ * @return                      0 on success;
+ *                              -1 if the mbuf does not contain enough data.
+ */
+int
+os_mbuf_copydata(const struct os_mbuf *m, int off, int len, void *dst)
+{
+    unsigned int count;
+    uint8_t *udst;
+
+    if (!len) {
+        return 0;
+    }
+
+    udst = dst;
+
+    while (off > 0) {
+        if (!m) {
+            return (-1);
+        }
+
+        if (off < m->om_len)
+            break;
+        off -= m->om_len;
+        m = SLIST_NEXT(m, om_next);
+    }
+    while (len > 0 && m != NULL) {
+        count = min(m->om_len - off, len);
+        memcpy(udst, m->om_data + off, count);
+        len -= count;
+        udst += count;
+        off = 0;
+        m = SLIST_NEXT(m, om_next);
+    }
+
+    return (len > 0 ? -1 : 0);
+}
+
+/**
+ * Adjust the length of a mbuf, trimming either from the head or the tail
+ * of the mbuf.
+ *
+ * @param mp The mbuf chain to adjust
+ * @param req_len The length to trim from the mbuf.  If positive, trims
+ *                from the head of the mbuf, if negative, trims from the
+ *                tail of the mbuf.
+ */
+void
+os_mbuf_adj(struct os_mbuf *mp, int req_len)
+{
+    int len = req_len;
+    struct os_mbuf *m;
+    int count;
+
+    if ((m = mp) == NULL)
+        return;
+    if (len >= 0) {
+        /*
+         * Trim from head.
+         */
+        while (m != NULL && len > 0) {
+            if (m->om_len <= len) {
+                len -= m->om_len;
+                m->om_len = 0;
+                m = SLIST_NEXT(m, om_next);
+            } else {
+                m->om_len -= len;
+                m->om_data += len;
+                len = 0;
+            }
+        }
+        if (OS_MBUF_IS_PKTHDR(mp))
+            OS_MBUF_PKTHDR(mp)->omp_len -= (req_len - len);
+    } else {
+        /*
+         * Trim from tail.  Scan the mbuf chain,
+         * calculating its length and finding the last mbuf.
+         * If the adjustment only affects this mbuf, then just
+         * adjust and return.  Otherwise, rescan and truncate
+         * after the remaining size.
+         */
+        len = -len;
+        count = 0;
+        for (;;) {
+            count += m->om_len;
+            if (SLIST_NEXT(m, om_next) == (struct os_mbuf *)0)
+                break;
+            m = SLIST_NEXT(m, om_next);
+        }
+        if (m->om_len >= len) {
+            m->om_len -= len;
+            if (OS_MBUF_IS_PKTHDR(mp))
+                OS_MBUF_PKTHDR(mp)->omp_len -= len;
+            return;
+        }
+        count -= len;
+        if (count < 0)
+            count = 0;
+        /*
+         * Correct length for chain is "count".
+         * Find the mbuf with last data, adjust its length,
+         * and toss data from remaining mbufs on chain.
+         */
+        m = mp;
+        if (OS_MBUF_IS_PKTHDR(m))
+            OS_MBUF_PKTHDR(m)->omp_len = count;
+        for (; m; m = SLIST_NEXT(m, om_next)) {
+            if (m->om_len >= count) {
+                m->om_len = count;
+                if (SLIST_NEXT(m, om_next) != NULL) {
+                    os_mbuf_free_chain(SLIST_NEXT(m, om_next));
+                    SLIST_NEXT(m, om_next) = NULL;
+                }
+                break;
+            }
+            count -= m->om_len;
+        }
+    }
+}
+
+/**
+ * Performs a memory compare of the specified region of an mbuf chain against a
+ * flat buffer.
+ *
+ * @param om                    The start of the mbuf chain to compare.
+ * @param off                   The offset within the mbuf chain to start the
+ *                                  comparison.
+ * @param data                  The flat buffer to compare.
+ * @param len                   The length of the flat buffer.
+ *
+ * @return                      0 if both memory regions are identical;
+ *                              A memcmp return code if there is a mismatch;
+ *                              INT_MAX if the mbuf is too short.
+ */
+int
+os_mbuf_cmpf(const struct os_mbuf *om, int off, const void *data, int len)
+{
+    uint16_t chunk_sz;
+    uint16_t data_off;
+    uint16_t om_off;
+    int rc;
+
+    if (len <= 0) {
+        return 0;
+    }
+
+    data_off = 0;
+    om = os_mbuf_off(om, off, &om_off);
+    while (1) {
+        if (om == NULL) {
+            return INT_MAX;
+        }
+
+        chunk_sz = min(om->om_len - om_off, len - data_off);
+        if (chunk_sz > 0) {
+            rc = memcmp(om->om_data + om_off, data + data_off, chunk_sz);
+            if (rc != 0) {
+                return rc;
+            }
+        }
+
+        data_off += chunk_sz;
+        if (data_off == len) {
+            return 0;
+        }
+
+        om = SLIST_NEXT(om, om_next);
+        om_off = 0;
+
+        if (om == NULL) {
+            return INT_MAX;
+        }
+    }
+}
+
+/**
+ * Compares the contents of two mbuf chains.  The ranges of the two chains to
+ * be compared are specified via the two offset parameters and the len
+ * parameter.  Neither mbuf chain is required to contain a packet header.
+ *
+ * @param om1                   The first mbuf chain to compare.
+ * @param offset1               The absolute offset within om1 at which to
+ *                                  start the comparison.
+ * @param om2                   The second mbuf chain to compare.
+ * @param offset2               The absolute offset within om2 at which to
+ *                                  start the comparison.
+ * @param len                   The number of bytes to compare.
+ *
+ * @return                      0 if both mbuf segments are identical;
+ *                              A memcmp() return code if the segment contents
+ *                                  differ;
+ *                              INT_MAX if a specified range extends beyond the
+ *                                  end of its corresponding mbuf chain.
+ */
+int
+os_mbuf_cmpm(const struct os_mbuf *om1, uint16_t offset1,
+             const struct os_mbuf *om2, uint16_t offset2,
+             uint16_t len)
+{
+    const struct os_mbuf *cur1;
+    const struct os_mbuf *cur2;
+    uint16_t bytes_remaining;
+    uint16_t chunk_sz;
+    uint16_t om1_left;
+    uint16_t om2_left;
+    uint16_t om1_off;
+    uint16_t om2_off;
+    int rc;
+
+    cur1 = os_mbuf_off(om1, offset1, &om1_off);
+    cur2 = os_mbuf_off(om2, offset2, &om2_off);
+
+    bytes_remaining = len;
+    while (1) {
+        if (bytes_remaining == 0) {
+            return 0;
+        }
+
+        while (cur1 != NULL && om1_off >= cur1->om_len) {
+            cur1 = SLIST_NEXT(cur1, om_next);
+            om1_off = 0;
+        }
+        while (cur2 != NULL && om2_off >= cur2->om_len) {
+            cur2 = SLIST_NEXT(cur2, om_next);
+            om2_off = 0;
+        }
+
+        if (cur1 == NULL || cur2 == NULL) {
+            return INT_MAX;
+        }
+
+        om1_left = cur1->om_len - om1_off;
+        om2_left = cur2->om_len - om2_off;
+        chunk_sz = min(min(om1_left, om2_left), bytes_remaining);
+
+        rc = memcmp(cur1->om_data + om1_off, cur2->om_data + om2_off,
+                    chunk_sz);
+        if (rc != 0) {
+            return rc;
+        }
+
+        om1_off += chunk_sz;
+        om2_off += chunk_sz;
+        bytes_remaining -= chunk_sz;
+    }
+}
+
+/**
+ * Increases the length of an mbuf chain by adding data to the front.  If there
+ * is insufficient room in the leading mbuf, additional mbufs are allocated and
+ * prepended as necessary.  If this function fails to allocate an mbuf, the
+ * entire chain is freed.
+ *
+ * The specified mbuf chain does not need to contain a packet header.
+ *
+ * @param omp                   The mbuf pool to allocate from.
+ * @param om                    The head of the mbuf chain.
+ * @param len                   The number of bytes to prepend.
+ *
+ * @return                      The new head of the chain on success;
+ *                              NULL on failure.
+ */
+struct os_mbuf *
+os_mbuf_prepend(struct os_mbuf *om, int len)
+{
+    struct os_mbuf *p;
+    int leading;
+
+    while (1) {
+        /* Fill the available space at the front of the head of the chain, as
+         * needed.
+         */
+        leading = min(len, OS_MBUF_LEADINGSPACE(om));
+
+        om->om_data -= leading;
+        om->om_len += leading;
+        if (OS_MBUF_IS_PKTHDR(om)) {
+            OS_MBUF_PKTHDR(om)->omp_len += leading;
+        }
+
+        len -= leading;
+        if (len == 0) {
+            break;
+        }
+
+        /* The current head didn't have enough space; allocate a new head. */
+        if (OS_MBUF_IS_PKTHDR(om)) {
+            p = os_mbuf_get_pkthdr(om->om_omp,
+                om->om_pkthdr_len - sizeof (struct os_mbuf_pkthdr));
+        } else {
+            p = os_mbuf_get(om->om_omp, 0);
+        }
+        if (p == NULL) {
+            os_mbuf_free_chain(om);
+            om = NULL;
+            break;
+        }
+
+        if (OS_MBUF_IS_PKTHDR(om)) {
+            _os_mbuf_copypkthdr(p, om);
+            om->om_pkthdr_len = 0;
+        }
+
+        /* Move the new head's data pointer to the end so that data can be
+         * prepended.
+         */
+        p->om_data += OS_MBUF_TRAILINGSPACE(p);
+
+        SLIST_NEXT(p, om_next) = om;
+        om = p;
+    }
+
+    return om;
+}
+
+/**
+ * Prepends a chunk of empty data to the specified mbuf chain and ensures the
+ * chunk is contiguous.  If either operation fails, the specified mbuf chain is
+ * freed and NULL is returned.
+ *
+ * @param om                    The mbuf chain to prepend to.
+ * @param len                   The number of bytes to prepend and pullup.
+ *
+ * @return                      The modified mbuf on success;
+ *                              NULL on failure (and the mbuf chain is freed).
+ */
+struct os_mbuf *
+os_mbuf_prepend_pullup(struct os_mbuf *om, uint16_t len)
+{
+    om = os_mbuf_prepend(om, len);
+    if (om == NULL) {
+        return NULL;
+    }
+
+    om = os_mbuf_pullup(om, len);
+    if (om == NULL) {
+        return NULL;
+    }
+
+    return om;
+}
+
+/**
+ * Copies the contents of a flat buffer into an mbuf chain, starting at the
+ * specified destination offset.  If the mbuf is too small for the source data,
+ * it is extended as necessary.  If the destination mbuf contains a packet
+ * header, the header length is updated.
+ *
+ * @param omp                   The mbuf pool to allocate from.
+ * @param om                    The mbuf chain to copy into.
+ * @param off                   The offset within the chain to copy to.
+ * @param src                   The source buffer to copy from.
+ * @param len                   The number of bytes to copy.
+ *
+ * @return                      0 on success; nonzero on failure.
+ */
+int
+os_mbuf_copyinto(struct os_mbuf *om, int off, const void *src, int len)
+{
+    struct os_mbuf *next;
+    struct os_mbuf *cur;
+    const uint8_t *sptr;
+    uint16_t cur_off;
+    int copylen;
+    int rc;
+
+    /* Find the mbuf,offset pair for the start of the destination. */
+    cur = os_mbuf_off(om, off, &cur_off);
+    if (cur == NULL) {
+        return -1;
+    }
+
+    /* Overwrite existing data until we reach the end of the chain. */
+    sptr = src;
+    while (1) {
+        copylen = min(cur->om_len - cur_off, len);
+        if (copylen > 0) {
+            memcpy(cur->om_data + cur_off, sptr, copylen);
+            sptr += copylen;
+            len -= copylen;
+
+            copylen = 0;
+        }
+
+        if (len == 0) {
+            /* All the source data fit in the existing mbuf chain. */
+            return 0;
+        }
+
+        next = SLIST_NEXT(cur, om_next);
+        if (next == NULL) {
+            break;
+        }
+
+        cur = next;
+    }
+
+    /* Append the remaining data to the end of the chain. */
+    rc = os_mbuf_append(cur, sptr, len);
+    if (rc != 0) {
+        return rc;
+    }
+
+    /* Fix up the packet header, if one is present. */
+    if (OS_MBUF_IS_PKTHDR(om)) {
+        OS_MBUF_PKTHDR(om)->omp_len =
+            max(OS_MBUF_PKTHDR(om)->omp_len, off + len);
+    }
+
+    return 0;
+}
+
+/**
+ * Attaches a second mbuf chain onto the end of the first.  If the first chain
+ * contains a packet header, the header's length is updated.  If the second
+ * chain has a packet header, its header is cleared.
+ *
+ * @param first                 The mbuf chain being attached to.
+ * @param second                The mbuf chain that gets attached.
+ */
+void
+os_mbuf_concat(struct os_mbuf *first, struct os_mbuf *second)
+{
+    struct os_mbuf *next;
+    struct os_mbuf *cur;
+
+    /* Point 'cur' to the last buffer in the first chain. */
+    cur = first;
+    while (1) {
+        next = SLIST_NEXT(cur, om_next);
+        if (next == NULL) {
+            break;
+        }
+
+        cur = next;
+    }
+
+    /* Attach the second chain to the end of the first. */
+    SLIST_NEXT(cur, om_next) = second;
+
+    /* If the first chain has a packet header, calculate the length of the
+     * second chain and add it to the header length.
+     */
+    if (OS_MBUF_IS_PKTHDR(first)) {
+        if (OS_MBUF_IS_PKTHDR(second)) {
+            OS_MBUF_PKTHDR(first)->omp_len += OS_MBUF_PKTHDR(second)->omp_len;
+        } else {
+            for (cur = second; cur != NULL; cur = SLIST_NEXT(cur, om_next)) {
+                OS_MBUF_PKTHDR(first)->omp_len += cur->om_len;
+            }
+        }
+    }
+
+    second->om_pkthdr_len = 0;
+}
+
+/**
+ * Increases the length of an mbuf chain by the specified amount.  If there is
+ * not sufficient room in the last buffer, a new buffer is allocated and
+ * appended to the chain.  It is an error to request more data than can fit in
+ * a single buffer.
+ *
+ * @param omp
+ * @param om                    The head of the chain to extend.
+ * @param len                   The number of bytes to extend by.
+ *
+ * @return                      A pointer to the new data on success;
+ *                              NULL on failure.
+ */
+void *
+os_mbuf_extend(struct os_mbuf *om, uint16_t len)
+{
+    struct os_mbuf *newm;
+    struct os_mbuf *last;
+    void *data;
+
+    if (len > om->om_omp->omp_databuf_len) {
+        return NULL;
+    }
+
+    /* Scroll to last mbuf in the chain */
+    last = om;
+    while (SLIST_NEXT(last, om_next) != NULL) {
+        last = SLIST_NEXT(last, om_next);
+    }
+
+    if (OS_MBUF_TRAILINGSPACE(last) < len) {
+        newm = os_mbuf_get(om->om_omp, 0);
+        if (newm == NULL) {
+            return NULL;
+        }
+
+        SLIST_NEXT(last, om_next) = newm;
+        last = newm;
+    }
+
+    data = last->om_data + last->om_len;
+    last->om_len += len;
+
+    if (OS_MBUF_IS_PKTHDR(om)) {
+        OS_MBUF_PKTHDR(om)->omp_len += len;
+    }
+
+    return data;
+}
+
+/**
+ * Rearrange a mbuf chain so that len bytes are contiguous,
+ * and in the data area of an mbuf (so that OS_MBUF_DATA() will
+ * work on a structure of size len.)  Returns the resulting
+ * mbuf chain on success, free's it and returns NULL on failure.
+ *
+ * If there is room, it will add up to "max_protohdr - len"
+ * extra bytes to the contiguous region, in an attempt to avoid being
+ * called next time.
+ *
+ * @param omp The mbuf pool to take the mbufs out of
+ * @param om The mbuf chain to make contiguous
+ * @param len The number of bytes in the chain to make contiguous
+ *
+ * @return The contiguous mbuf chain on success, NULL on failure.
+ */
+struct os_mbuf *
+os_mbuf_pullup(struct os_mbuf *om, uint16_t len)
+{
+    struct os_mbuf_pool *omp;
+    struct os_mbuf *next;
+    struct os_mbuf *om2;
+    int count;
+    int space;
+
+    omp = om->om_omp;
+
+    /*
+     * If first mbuf has no cluster, and has room for len bytes
+     * without shifting current data, pullup into it,
+     * otherwise allocate a new mbuf to prepend to the chain.
+     */
+    if (om->om_len >= len) {
+        return (om);
+    }
+    if (om->om_len + OS_MBUF_TRAILINGSPACE(om) >= len &&
+        SLIST_NEXT(om, om_next)) {
+        om2 = om;
+        om = SLIST_NEXT(om, om_next);
+        len -= om2->om_len;
+    } else {
+        if (len > omp->omp_databuf_len - om->om_pkthdr_len) {
+            goto bad;
+        }
+
+        om2 = os_mbuf_get(omp, 0);
+        if (om2 == NULL) {
+            goto bad;
+        }
+
+        if (OS_MBUF_IS_PKTHDR(om)) {
+            _os_mbuf_copypkthdr(om2, om);
+        }
+    }
+    space = OS_MBUF_TRAILINGSPACE(om2);
+    do {
+        count = min(min(len, space), om->om_len);
+        memcpy(om2->om_data + om2->om_len, om->om_data, count);
+        len -= count;
+        om2->om_len += count;
+        om->om_len -= count;
+        space -= count;
+        if (om->om_len) {
+            om->om_data += count;
+        } else {
+            next = SLIST_NEXT(om, om_next);
+            os_mbuf_free(om);
+            om = next;
+        }
+    } while (len > 0 && om);
+    if (len > 0) {
+        os_mbuf_free(om2);
+        goto bad;
+    }
+    SLIST_NEXT(om2, om_next) = om;
+    return (om2);
+bad:
+    os_mbuf_free_chain(om);
+    return (NULL);
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/src/os_mempool.c
----------------------------------------------------------------------
diff --git a/kernel/os/src/os_mempool.c b/kernel/os/src/os_mempool.c
new file mode 100644
index 0000000..e940ba4
--- /dev/null
+++ b/kernel/os/src/os_mempool.c
@@ -0,0 +1,233 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include "os/os.h"
+
+#include <string.h>
+#include <assert.h>
+
+#define OS_MEMPOOL_TRUE_BLOCK_SIZE(bsize)   OS_ALIGN(bsize, OS_ALIGNMENT)
+
+STAILQ_HEAD(, os_mempool) g_os_mempool_list = 
+    STAILQ_HEAD_INITIALIZER(g_os_mempool_list);
+
+/**
+ * os mempool init
+ *  
+ * Initialize a memory pool. 
+ * 
+ * @param mp            Pointer to a pointer to a mempool
+ * @param blocks        The number of blocks in the pool
+ * @param blocks_size   The size of the block, in bytes. 
+ * @param membuf        Pointer to memory to contain blocks. 
+ * @param name          Name of the pool.
+ * 
+ * @return os_error_t 
+ */
+os_error_t
+os_mempool_init(struct os_mempool *mp, int blocks, int block_size,
+                void *membuf, char *name)
+{
+    int true_block_size;
+    uint8_t *block_addr;
+    struct os_memblock *block_ptr;
+
+    /* Check for valid parameters */
+    if ((!mp) || (blocks < 0) || (block_size <= 0)) {
+        return OS_INVALID_PARM;
+    }
+
+    if ((!membuf) && (blocks != 0)) {
+        return OS_INVALID_PARM;
+    }
+
+    if (membuf != NULL) {
+        /* Blocks need to be sized properly and memory buffer should be
+         * aligned
+         */
+        if (((uint32_t)membuf & (OS_ALIGNMENT - 1)) != 0) {
+            return OS_MEM_NOT_ALIGNED;
+        }
+    }
+    true_block_size = OS_MEMPOOL_TRUE_BLOCK_SIZE(block_size);
+
+    /* Initialize the memory pool structure */
+    mp->mp_block_size = block_size;
+    mp->mp_num_free = blocks;
+    mp->mp_num_blocks = blocks;
+    mp->mp_membuf_addr = (uint32_t)membuf;
+    mp->name = name;
+    SLIST_FIRST(mp) = membuf;
+
+    /* Chain the memory blocks to the free list */
+    block_addr = (uint8_t *)membuf;
+    block_ptr = (struct os_memblock *)block_addr;
+    while (blocks > 1) {
+        block_addr += true_block_size;
+        SLIST_NEXT(block_ptr, mb_next) = (struct os_memblock *)block_addr;
+        block_ptr = (struct os_memblock *)block_addr;
+        --blocks;
+    }
+
+    /* Last one in the list should be NULL */
+    SLIST_NEXT(block_ptr, mb_next) = NULL;
+
+    STAILQ_INSERT_TAIL(&g_os_mempool_list, mp, mp_list);
+
+    return OS_OK;
+}
+
+/**
+ * Checks if a memory block was allocated from the specified mempool.
+ *
+ * @param mp                    The mempool to check as parent.
+ * @param block_addr            The memory block to check as child.
+ *
+ * @return                      0 if the block does not belong to the mempool;
+ *                              1 if the block does belong to the mempool.
+ */
+int
+os_memblock_from(struct os_mempool *mp, void *block_addr)
+{
+    uint32_t true_block_size;
+    uint32_t baddr32;
+    uint32_t end;
+
+    _Static_assert(sizeof block_addr == sizeof baddr32,
+                   "Pointer to void must be 32-bits.");
+
+    baddr32 = (uint32_t)block_addr;
+    true_block_size = OS_MEMPOOL_TRUE_BLOCK_SIZE(mp->mp_block_size);
+    end = mp->mp_membuf_addr + (mp->mp_num_blocks * true_block_size);
+
+    /* Check that the block is in the memory buffer range. */
+    if ((baddr32 < mp->mp_membuf_addr) || (baddr32 >= end)) {
+        return 0;
+    }
+
+    /* All freed blocks should be on true block size boundaries! */
+    if (((baddr32 - mp->mp_membuf_addr) % true_block_size) != 0) {
+        return 0;
+    }
+
+    return 1;
+}
+
+/**
+ * os memblock get 
+ *  
+ * Get a memory block from a memory pool 
+ * 
+ * @param mp Pointer to the memory pool
+ * 
+ * @return void* Pointer to block if available; NULL otherwise
+ */
+void *
+os_memblock_get(struct os_mempool *mp)
+{
+    os_sr_t sr;
+    struct os_memblock *block;
+
+    /* Check to make sure they passed in a memory pool (or something) */
+    block = NULL;
+    if (mp) {
+        OS_ENTER_CRITICAL(sr);
+        /* Check for any free */
+        if (mp->mp_num_free) {
+            /* Get a free block */
+            block = SLIST_FIRST(mp);
+
+            /* Set new free list head */
+            SLIST_FIRST(mp) = SLIST_NEXT(block, mb_next);
+
+            /* Decrement number free by 1 */
+            mp->mp_num_free--;
+        }
+        OS_EXIT_CRITICAL(sr);
+    }
+
+    return (void *)block;
+}
+
+/**
+ * os memblock put 
+ *  
+ * Puts the memory block back into the pool 
+ * 
+ * @param mp Pointer to memory pool
+ * @param block_addr Pointer to memory block
+ * 
+ * @return os_error_t 
+ */
+os_error_t
+os_memblock_put(struct os_mempool *mp, void *block_addr)
+{
+    os_sr_t sr;
+    struct os_memblock *block;
+
+    /* Make sure parameters are valid */
+    if ((mp == NULL) || (block_addr == NULL)) {
+        return OS_INVALID_PARM;
+    }
+
+    /* Check that the block we are freeing is a valid block! */
+    if (!os_memblock_from(mp, block_addr)) {
+        return OS_INVALID_PARM;
+    }
+
+    block = (struct os_memblock *)block_addr;
+    OS_ENTER_CRITICAL(sr);
+    
+    /* Chain current free list pointer to this block; make this block head */
+    SLIST_NEXT(block, mb_next) = SLIST_FIRST(mp);
+    SLIST_FIRST(mp) = block;
+
+    /* XXX: Should we check that the number free <= number blocks? */
+    /* Increment number free */
+    mp->mp_num_free++;
+
+    OS_EXIT_CRITICAL(sr);
+
+    return OS_OK;
+}
+
+
+struct os_mempool *
+os_mempool_info_get_next(struct os_mempool *mp, struct os_mempool_info *omi)
+{
+    struct os_mempool *cur;
+
+    if (mp == NULL) {
+        cur = STAILQ_FIRST(&g_os_mempool_list);
+    } else {
+        cur = STAILQ_NEXT(mp, mp_list);
+    }
+
+    if (cur == NULL) {
+        return (NULL);
+    }
+
+    omi->omi_block_size = cur->mp_block_size;
+    omi->omi_num_blocks = cur->mp_num_blocks;
+    omi->omi_num_free = cur->mp_num_free;
+    strncpy(omi->omi_name, cur->name, sizeof(omi->omi_name));
+
+    return (cur);
+}
+

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/src/os_msys_init.c
----------------------------------------------------------------------
diff --git a/kernel/os/src/os_msys_init.c b/kernel/os/src/os_msys_init.c
new file mode 100644
index 0000000..fe0d569
--- /dev/null
+++ b/kernel/os/src/os_msys_init.c
@@ -0,0 +1,147 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include <assert.h>
+#include "sysinit/sysinit.h"
+#include "syscfg/syscfg.h"
+#include "os/os_mempool.h"
+#include "util/mem.h"
+#include "os_priv.h"
+
+#if MYNEWT_VAL(MSYS_1_BLOCK_COUNT) > 0
+#define SYSINIT_MSYS_1_MEMBLOCK_SIZE                \
+    OS_ALIGN(MYNEWT_VAL(MSYS_1_BLOCK_SIZE), 4)
+#define SYSINIT_MSYS_1_MEMPOOL_SIZE                 \
+    OS_MEMPOOL_SIZE(MYNEWT_VAL(MSYS_1_BLOCK_COUNT),  \
+                    SYSINIT_MSYS_1_MEMBLOCK_SIZE)
+static os_membuf_t os_msys_init_1_data[SYSINIT_MSYS_1_MEMPOOL_SIZE];
+static struct os_mbuf_pool os_msys_init_1_mbuf_pool;
+static struct os_mempool os_msys_init_1_mempool;
+#endif
+
+#if MYNEWT_VAL(MSYS_2_BLOCK_COUNT) > 0
+#define SYSINIT_MSYS_2_MEMBLOCK_SIZE                \
+    OS_ALIGN(MYNEWT_VAL(MSYS_2_BLOCK_SIZE), 4)
+#define SYSINIT_MSYS_2_MEMPOOL_SIZE                 \
+    OS_MEMPOOL_SIZE(MYNEWT_VAL(MSYS_2_BLOCK_COUNT),  \
+                    SYSINIT_MSYS_2_MEMBLOCK_SIZE)
+static os_membuf_t os_msys_init_2_data[SYSINIT_MSYS_2_MEMPOOL_SIZE];
+static struct os_mbuf_pool os_msys_init_2_mbuf_pool;
+static struct os_mempool os_msys_init_2_mempool;
+#endif
+
+#if MYNEWT_VAL(MSYS_3_BLOCK_COUNT) > 0
+#define SYSINIT_MSYS_3_MEMBLOCK_SIZE                \
+    OS_ALIGN(MYNEWT_VAL(MSYS_3_BLOCK_SIZE), 4)
+#define SYSINIT_MSYS_3_MEMPOOL_SIZE                 \
+    OS_MEMPOOL_SIZE(MYNEWT_VAL(MSYS_3_BLOCK_COUNT),  \
+                    SYSINIT_MSYS_3_MEMBLOCK_SIZE)
+static os_membuf_t os_msys_init_3_data[SYSINIT_MSYS_3_MEMPOOL_SIZE];
+static struct os_mbuf_pool os_msys_init_3_mbuf_pool;
+static struct os_mempool os_msys_init_3_mempool;
+#endif
+
+#if MYNEWT_VAL(MSYS_4_BLOCK_COUNT) > 0
+#define SYSINIT_MSYS_4_MEMBLOCK_SIZE                \
+    OS_ALIGN(MYNEWT_VAL(MSYS_4_BLOCK_SIZE), 4)
+#define SYSINIT_MSYS_4_MEMPOOL_SIZE                 \
+    OS_MEMPOOL_SIZE(MYNEWT_VAL(MSYS_4_BLOCK_COUNT),  \
+                    SYSINIT_MSYS_4_MEMBLOCK_SIZE)
+static os_membuf_t os_msys_init_4_data[SYSINIT_MSYS_4_MEMPOOL_SIZE];
+static struct os_mbuf_pool os_msys_init_4_mbuf_pool;
+static struct os_mempool os_msys_init_4_mempool;
+#endif
+
+#if MYNEWT_VAL(MSYS_5_BLOCK_COUNT) > 0
+#define SYSINIT_MSYS_5_MEMBLOCK_SIZE                \
+    OS_ALIGN(MYNEWT_VAL(MSYS_5_BLOCK_SIZE), 4)
+#define SYSINIT_MSYS_5_MEMPOOL_SIZE                 \
+    OS_MEMPOOL_SIZE(MYNEWT_VAL(MSYS_5_BLOCK_COUNT),  \
+                    SYSINIT_MSYS_5_MEMBLOCK_SIZE)
+
+static os_membuf_t os_msys_init_5_data[SYSINIT_MSYS_5_MEMPOOL_SIZE];
+static struct os_mbuf_pool os_msys_init_5_mbuf_pool;
+static struct os_mempool os_msys_init_5_mempool;
+#endif
+
+static void
+os_msys_init_once(void *data, struct os_mempool *mempool,
+                  struct os_mbuf_pool *mbuf_pool,
+                  int block_count, int block_size, char *name)
+{
+    int rc;
+
+    rc = mem_init_mbuf_pool(data, mempool, mbuf_pool, block_count, block_size,
+                            name);
+    SYSINIT_PANIC_ASSERT(rc == 0);
+
+    rc = os_msys_register(mbuf_pool);
+    SYSINIT_PANIC_ASSERT(rc == 0);
+}
+
+void
+os_msys_init(void)
+{
+    os_msys_reset();
+
+#if MYNEWT_VAL(MSYS_1_BLOCK_COUNT) > 0
+    os_msys_init_once(os_msys_init_1_data,
+                      &os_msys_init_1_mempool,
+                      &os_msys_init_1_mbuf_pool,
+                      MYNEWT_VAL(MSYS_1_BLOCK_COUNT),
+                      SYSINIT_MSYS_1_MEMBLOCK_SIZE,
+                      "msys_1");
+#endif
+
+#if MYNEWT_VAL(MSYS_2_BLOCK_COUNT) > 0
+    os_msys_init_once(os_msys_init_2_data,
+                      &os_msys_init_2_mempool,
+                      &os_msys_init_2_mbuf_pool,
+                      MYNEWT_VAL(MSYS_2_BLOCK_COUNT),
+                      SYSINIT_MSYS_2_MEMBLOCK_SIZE,
+                      "msys_2");
+#endif
+
+#if MYNEWT_VAL(MSYS_3_BLOCK_COUNT) > 0
+    os_msys_init_once(os_msys_init_3_data,
+                      &os_msys_init_3_mempool,
+                      &os_msys_init_3_mbuf_pool,
+                      MYNEWT_VAL(MSYS_3_BLOCK_COUNT),
+                      SYSINIT_MSYS_3_MEMBLOCK_SIZE,
+                      "msys_3");
+#endif
+
+#if MYNEWT_VAL(MSYS_4_BLOCK_COUNT) > 0
+    os_msys_init_once(os_msys_init_4_data,
+                      &os_msys_init_4_mempool,
+                      &os_msys_init_4_mbuf_pool,
+                      MYNEWT_VAL(MSYS_4_BLOCK_COUNT),
+                      SYSINIT_MSYS_4_MEMBLOCK_SIZE,
+                      "msys_4");
+#endif
+
+#if MYNEWT_VAL(MSYS_5_BLOCK_COUNT) > 0
+    os_msys_init_once(os_msys_init_5_data,
+                      &os_msys_init_5_mempool,
+                      &os_msys_init_5_mbuf_pool,
+                      MYNEWT_VAL(MSYS_5_BLOCK_COUNT),
+                      SYSINIT_MSYS_5_MEMBLOCK_SIZE,
+                      "msys_5");
+#endif
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/src/os_mutex.c
----------------------------------------------------------------------
diff --git a/kernel/os/src/os_mutex.c b/kernel/os/src/os_mutex.c
new file mode 100644
index 0000000..6519292
--- /dev/null
+++ b/kernel/os/src/os_mutex.c
@@ -0,0 +1,236 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include "os/os.h"
+#include <assert.h>
+
+/**
+ * os mutex create
+ *  
+ * Create a mutex and initialize it. 
+ * 
+ * @param mu Pointer to mutex
+ * 
+ * @return os_error_t 
+ *      OS_INVALID_PARM     Mutex passed in was NULL.
+ *      OS_OK               no error.
+ */
+os_error_t
+os_mutex_init(struct os_mutex *mu)
+{
+    if (!mu) {
+        return OS_INVALID_PARM;
+    }
+
+    /* Initialize to 0 */
+    mu->mu_prio = 0;
+    mu->mu_level = 0;
+    mu->mu_owner = NULL;
+    SLIST_FIRST(&mu->mu_head) = NULL;
+
+    return OS_OK;
+}
+
+/**
+ * os mutex release
+ *  
+ * Release a mutex. 
+ * 
+ * @param mu Pointer to the mutex to be released
+ * 
+ * @return os_error_t 
+ *      OS_INVALID_PARM Mutex passed in was NULL.
+ *      OS_BAD_MUTEX    Mutex was not granted to current task (not owner).
+ *      OS_OK           No error
+ */
+os_error_t
+os_mutex_release(struct os_mutex *mu)
+{
+    int resched;
+    os_sr_t sr;
+    struct os_task *current;
+    struct os_task *rdy;
+
+    /* Check if OS is started */
+    if (!g_os_started) {
+        return (OS_NOT_STARTED);
+    }
+
+    /* Check for valid mutex */
+    if (!mu) {
+        return OS_INVALID_PARM;
+    }
+
+    /* We better own this mutex! */
+    current = os_sched_get_current_task();
+    if ((mu->mu_level == 0) || (mu->mu_owner != current)) {
+        return (OS_BAD_MUTEX);
+    }
+
+    /* Decrement nesting level by 1. If not zero, nested (so dont release!) */
+    --mu->mu_level;
+    if (mu->mu_level != 0) {
+        return (OS_OK);
+    }
+
+    OS_ENTER_CRITICAL(sr);
+
+    /* Restore owner task's priority; resort list if different  */
+    if (current->t_prio != mu->mu_prio) {
+        current->t_prio = mu->mu_prio;
+        os_sched_resort(current);
+    }
+
+    /* Check if tasks are waiting for the mutex */
+    rdy = SLIST_FIRST(&mu->mu_head);
+    if (rdy) {
+        /* There is one waiting. Wake it up */
+        assert(rdy->t_obj);
+        os_sched_wakeup(rdy);
+
+        /* Set mutex internals */
+        mu->mu_level = 1;
+        mu->mu_prio = rdy->t_prio;
+    }
+
+    /* Set new owner of mutex (or NULL if not owned) */
+    mu->mu_owner = rdy;
+
+    /* Do we need to re-schedule? */
+    resched = 0;
+    rdy = os_sched_next_task();
+    if (rdy != current) {
+        resched = 1;
+    }
+    OS_EXIT_CRITICAL(sr);
+
+    /* Re-schedule if needed */
+    if (resched) {
+        os_sched(rdy);
+    }
+
+    return OS_OK;
+}
+
+/**
+ * os mutex pend 
+ *  
+ * Pend (wait) for a mutex. 
+ * 
+ * @param mu Pointer to mutex.
+ * @param timeout Timeout, in os ticks. A timeout of 0 means do 
+ *                not wait if not available. A timeout of
+ *                0xFFFFFFFF means wait forever.
+ *              
+ * 
+ * @return os_error_t 
+ *      OS_INVALID_PARM     Mutex passed in was NULL.
+ *      OS_TIMEOUT          Mutex was owned by another task and timeout=0
+ *      OS_OK               no error.
+ */ 
+os_error_t
+os_mutex_pend(struct os_mutex *mu, uint32_t timeout)
+{
+    os_sr_t sr;
+    os_error_t rc;
+    struct os_task *current;
+    struct os_task *entry;
+    struct os_task *last;
+
+    /* OS must be started when calling this function */
+    if (!g_os_started) {
+        return (OS_NOT_STARTED);
+    }
+
+    /* Check for valid mutex */
+    if (!mu) {
+        return OS_INVALID_PARM;
+    }
+
+    OS_ENTER_CRITICAL(sr);
+
+    /* Is this owned? */
+    current = os_sched_get_current_task();
+    if (mu->mu_level == 0) {
+        mu->mu_owner = current;
+        mu->mu_prio  = current->t_prio;
+        mu->mu_level = 1;
+        OS_EXIT_CRITICAL(sr);
+        return OS_OK;
+    }
+
+    /* Are we owner? */
+    if (mu->mu_owner == current) {
+        ++mu->mu_level;
+        OS_EXIT_CRITICAL(sr);
+        return OS_OK;
+    }
+
+    /* Mutex is not owned by us. If timeout is 0, return immediately */
+    if (timeout == 0) {
+        OS_EXIT_CRITICAL(sr);
+        return OS_TIMEOUT;
+    }
+
+    /* Change priority of owner if needed */
+    if (mu->mu_owner->t_prio > current->t_prio) {
+        mu->mu_owner->t_prio = current->t_prio;
+        os_sched_resort(mu->mu_owner);
+    }
+
+    /* Link current task to tasks waiting for mutex */
+    last = NULL;
+    if (!SLIST_EMPTY(&mu->mu_head)) {
+        /* Insert in priority order */
+        SLIST_FOREACH(entry, &mu->mu_head, t_obj_list) {
+            if (current->t_prio < entry->t_prio) { 
+                break;
+            }
+            last = entry;
+        }
+    }
+
+    if (last) {
+        SLIST_INSERT_AFTER(last, current, t_obj_list);
+    } else {
+        SLIST_INSERT_HEAD(&mu->mu_head, current, t_obj_list);
+    }
+
+    /* Set mutex pointer in task */
+    current->t_obj = mu;
+    current->t_flags |= OS_TASK_FLAG_MUTEX_WAIT;
+    os_sched_sleep(current, timeout);
+    OS_EXIT_CRITICAL(sr);
+
+    os_sched(NULL);
+
+    OS_ENTER_CRITICAL(sr);
+    current->t_flags &= ~OS_TASK_FLAG_MUTEX_WAIT;
+    OS_EXIT_CRITICAL(sr);
+
+    /* If we are owner we did not time out. */
+    if (mu->mu_owner == current) {
+        rc = OS_OK; 
+    } else {
+        rc = OS_TIMEOUT;
+    }
+
+    return rc;
+}
+

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/src/os_priv.h
----------------------------------------------------------------------
diff --git a/kernel/os/src/os_priv.h b/kernel/os/src/os_priv.h
new file mode 100644
index 0000000..7745a0a
--- /dev/null
+++ b/kernel/os/src/os_priv.h
@@ -0,0 +1,38 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 H_OS_PRIV_
+#define H_OS_PRIV_
+
+#include "os/queue.h"
+
+TAILQ_HEAD(os_task_list, os_task);
+TAILQ_HEAD(os_callout_list, os_callout);
+STAILQ_HEAD(os_task_stailq, os_task);
+
+extern struct os_task g_idle_task;
+extern struct os_task_list g_os_run_list;
+extern struct os_task_list g_os_sleep_list;
+extern struct os_task_stailq g_os_task_list;
+extern struct os_task *g_current_task;
+extern struct os_callout_list g_callout_list;
+
+void os_msys_init(void);
+
+#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/src/os_sanity.c
----------------------------------------------------------------------
diff --git a/kernel/os/src/os_sanity.c b/kernel/os/src/os_sanity.c
new file mode 100644
index 0000000..f0aa5d2
--- /dev/null
+++ b/kernel/os/src/os_sanity.c
@@ -0,0 +1,238 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include <assert.h>
+#include <string.h>
+
+#include "os/os.h"
+
+SLIST_HEAD(, os_sanity_check) g_os_sanity_check_list =
+    SLIST_HEAD_INITIALIZER(os_sanity_check_list);
+
+struct os_mutex g_os_sanity_check_mu;
+
+/**
+ * Initialize a sanity check
+ *
+ * @param sc The sanity check to initialize
+ *
+ * @return 0 on success, error code on failure.
+ */
+int
+os_sanity_check_init(struct os_sanity_check *sc)
+{
+    memset(sc, 0, sizeof(*sc));
+
+    return (0);
+}
+
+/**
+ * Lock the sanity check list
+ *
+ * @return 0 on success, error code on failure.
+ */
+static int
+os_sanity_check_list_lock(void)
+{
+    int rc;
+
+    if (!g_os_started) {
+        return (0);
+    }
+
+    rc = os_mutex_pend(&g_os_sanity_check_mu, OS_WAIT_FOREVER);
+    if (rc != OS_OK) {
+        goto err;
+    }
+
+    return (0);
+err:
+    return (rc);
+}
+
+/**
+ * Unlock the sanity check list
+ *
+ * @return 0 on success, error code on failure
+ */
+static int
+os_sanity_check_list_unlock(void)
+{
+    int rc;
+
+    if (!g_os_started) {
+        return (0);
+    }
+
+    rc = os_mutex_release(&g_os_sanity_check_mu);
+    if (rc != 0) {
+        goto err;
+    }
+
+    return (0);
+err:
+    return (rc);
+}
+
+/**
+ * Provide a "task checkin" for the sanity task.
+ *
+ * @param t The task to check in
+ *
+ * @return 0 on success, error code on failure
+ */
+int
+os_sanity_task_checkin(struct os_task *t)
+{
+    int rc;
+
+    if (t == NULL) {
+        t = os_sched_get_current_task();
+    }
+
+    rc = os_sanity_check_reset(&t->t_sanity_check);
+    if (rc != OS_OK) {
+        goto err;
+    }
+
+    return (0);
+err:
+    return (rc);
+}
+
+
+/**
+ * Register a sanity check
+ *
+ * @param sc The sanity check to register
+ *
+ * @return 0 on success, error code on failure
+ */
+int
+os_sanity_check_register(struct os_sanity_check *sc)
+{
+    int rc;
+
+    rc = os_sanity_check_list_lock();
+    if (rc != OS_OK) {
+        goto err;
+    }
+
+    SLIST_INSERT_HEAD(&g_os_sanity_check_list, sc, sc_next);
+
+    rc = os_sanity_check_list_unlock();
+    if (rc != OS_OK) {
+        goto err;
+    }
+
+    return (0);
+err:
+    return (rc);
+}
+
+
+/**
+ * Reset the os sanity check, so that it doesn't trip up the
+ * sanity timer.
+ *
+ * @param sc The sanity check to reset
+ *
+ * @return 0 on success, error code on failure
+ */
+int
+os_sanity_check_reset(struct os_sanity_check *sc)
+{
+    int rc;
+
+    rc = os_sanity_check_list_lock();
+    if (rc != OS_OK) {
+        goto err;
+    }
+
+    sc->sc_checkin_last = os_time_get();
+
+    rc = os_sanity_check_list_unlock();
+    if (rc != OS_OK) {
+        goto err;
+    }
+
+    return (0);
+err:
+    return (rc);
+}
+
+/*
+ * Called from the IDLE task context, every MYNEWT_VAL(SANITY_INTERVAL) msecs.
+ *
+ * Goes through the sanity check list, and performs sanity checks.  If any of
+ * these checks failed, or tasks have not checked in, it resets the processor.
+ */
+void
+os_sanity_run(void)
+{
+    struct os_sanity_check *sc;
+    int rc;
+
+    rc = os_sanity_check_list_lock();
+    if (rc != 0) {
+        assert(0);
+    }
+
+    SLIST_FOREACH(sc, &g_os_sanity_check_list, sc_next) {
+        rc = OS_OK;
+
+        if (sc->sc_func) {
+            rc = sc->sc_func(sc, sc->sc_arg);
+            if (rc == OS_OK) {
+                sc->sc_checkin_last = os_time_get();
+                continue;
+            }
+        }
+
+        if (OS_TIME_TICK_GT(os_time_get(),
+                    sc->sc_checkin_last + sc->sc_checkin_itvl)) {
+            assert(0);
+        }
+    }
+
+    rc = os_sanity_check_list_unlock();
+    if (rc != 0) {
+        assert(0);
+    }
+}
+
+/**
+ * Initialize the sanity task and mutex.
+ *
+ * @return 0 on success, error code on failure
+ */
+int
+os_sanity_init(void)
+{
+    int rc;
+
+    rc = os_mutex_init(&g_os_sanity_check_mu);
+    if (rc != 0) {
+        goto err;
+    }
+
+    return (0);
+err:
+    return (rc);
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/src/os_sched.c
----------------------------------------------------------------------
diff --git a/kernel/os/src/os_sched.c b/kernel/os/src/os_sched.c
new file mode 100644
index 0000000..3d81dba
--- /dev/null
+++ b/kernel/os/src/os_sched.c
@@ -0,0 +1,330 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include "os/os.h"
+#include "os/queue.h"
+
+#include <assert.h>
+
+TAILQ_HEAD(, os_task) g_os_run_list = TAILQ_HEAD_INITIALIZER(g_os_run_list); 
+
+TAILQ_HEAD(, os_task) g_os_sleep_list = TAILQ_HEAD_INITIALIZER(g_os_sleep_list); 
+
+struct os_task *g_current_task; 
+
+extern os_time_t g_os_time;
+os_time_t g_os_last_ctx_sw_time;
+
+/**
+ * os sched insert
+ *  
+ * Insert a task into the scheduler list. This causes the task to be evaluated
+ * for running when os_sched is called. 
+ * 
+ * @param t     Pointer to task to insert in run list
+ * 
+ * @return int  OS_OK: task was inserted into run list 
+ *              OS_EINVAL: Task was not in ready state. 
+ */
+os_error_t
+os_sched_insert(struct os_task *t) 
+{
+    struct os_task *entry; 
+    os_sr_t sr; 
+    os_error_t rc;
+
+    if (t->t_state != OS_TASK_READY) {
+        rc = OS_EINVAL;
+        goto err;
+    }
+
+    entry = NULL;
+    OS_ENTER_CRITICAL(sr); 
+    TAILQ_FOREACH(entry, &g_os_run_list, t_os_list) {
+        if (t->t_prio < entry->t_prio) { 
+            break;
+        }
+    }
+    if (entry) {
+        TAILQ_INSERT_BEFORE(entry, (struct os_task *) t, t_os_list);
+    } else {
+        TAILQ_INSERT_TAIL(&g_os_run_list, (struct os_task *) t, t_os_list);
+    }
+    OS_EXIT_CRITICAL(sr);
+
+    return (0);
+err:
+    return (rc);
+}
+
+void
+os_sched_ctx_sw_hook(struct os_task *next_t)
+{
+    if (g_current_task == next_t) {
+        return;
+    }
+
+    next_t->t_ctx_sw_cnt++;
+    g_current_task->t_run_time += g_os_time - g_os_last_ctx_sw_time;
+    g_os_last_ctx_sw_time = g_os_time;
+}
+
+
+/**
+ * os sched get current task 
+ *  
+ * Returns the currently running task. Note that this task may or may not be 
+ * the highest priority task ready to run. 
+ * 
+ * 
+ * @return struct os_task* 
+ */
+struct os_task * 
+os_sched_get_current_task(void)
+{
+    return (g_current_task);
+}
+
+/**
+ * os sched set current task 
+ *  
+ * Sets the currently running task to 't'. Note that this function simply sets 
+ * the global variable holding the currently running task. It does not perform 
+ * a context switch or change the os run or sleep list. 
+ * 
+ * @param t Pointer to currently running task.
+ */
+void 
+os_sched_set_current_task(struct os_task *t) 
+{
+    g_current_task = t;
+}
+
+/**
+ * os sched 
+ *  
+ * Performs a context switch. When called, it will either find the highest 
+ * priority task ready to run if next_t is NULL (i.e. the head of the os run 
+ * list) or will schedule next_t as the task to run.
+ * 
+ * @param next_t Task to run
+ */
+void
+os_sched(struct os_task *next_t)
+{
+    os_sr_t sr;
+
+    OS_ENTER_CRITICAL(sr);
+
+    if (!next_t) {
+        next_t = os_sched_next_task();
+    }
+
+    if (next_t != g_current_task) {
+        os_arch_ctx_sw(next_t);
+    }
+
+    OS_EXIT_CRITICAL(sr);
+}
+
+/**
+ * os sched sleep 
+ *  
+ * Removes the task from the run list and puts it on the sleep list. 
+ * 
+ * @param t Task to put to sleep
+ * @param nticks Number of ticks to put task to sleep
+ * 
+ * @return int
+ *  
+ * NOTE: must be called with interrupts disabled! This function does not call 
+ * the scheduler 
+ */
+int 
+os_sched_sleep(struct os_task *t, os_time_t nticks) 
+{
+    struct os_task *entry;
+
+    entry = NULL; 
+
+    TAILQ_REMOVE(&g_os_run_list, t, t_os_list);
+    t->t_state = OS_TASK_SLEEP;
+    t->t_next_wakeup = os_time_get() + nticks;
+    if (nticks == OS_TIMEOUT_NEVER) {
+        t->t_flags |= OS_TASK_FLAG_NO_TIMEOUT;
+        TAILQ_INSERT_TAIL(&g_os_sleep_list, t, t_os_list); 
+    } else {
+        TAILQ_FOREACH(entry, &g_os_sleep_list, t_os_list) {
+            if ((entry->t_flags & OS_TASK_FLAG_NO_TIMEOUT) ||
+                    OS_TIME_TICK_GT(entry->t_next_wakeup, t->t_next_wakeup)) {
+                break;
+            }
+        }
+        if (entry) {
+            TAILQ_INSERT_BEFORE(entry, t, t_os_list); 
+        } else {
+            TAILQ_INSERT_TAIL(&g_os_sleep_list, t, t_os_list); 
+        }
+    }
+
+    return (0);
+}
+
+/**
+ * os sched wakeup 
+ *  
+ * Called to wake up a task. Waking up a task consists of setting the task state
+ * to READY and moving it from the sleep list to the run list. 
+ * 
+ * @param t     Pointer to task to wake up. 
+ * 
+ * @return int 
+ *  
+ * NOTE: This function must be called with interrupts disabled. 
+ */
+int 
+os_sched_wakeup(struct os_task *t) 
+{
+    struct os_task_obj *os_obj;
+
+    assert(t->t_state == OS_TASK_SLEEP);
+
+    /* Remove self from object list if waiting on one */
+    if (t->t_obj) {
+        os_obj = (struct os_task_obj *)t->t_obj;
+        assert(!SLIST_EMPTY(&os_obj->obj_head));
+        SLIST_REMOVE(&os_obj->obj_head, t, os_task, t_obj_list);
+        SLIST_NEXT(t, t_obj_list) = NULL;
+        t->t_obj = NULL; 
+    }
+
+    /* Remove task from sleep list */
+    t->t_state = OS_TASK_READY;
+    t->t_next_wakeup = 0;
+    t->t_flags &= ~OS_TASK_FLAG_NO_TIMEOUT;
+    TAILQ_REMOVE(&g_os_sleep_list, t, t_os_list);
+    os_sched_insert(t);
+
+    return (0);
+}
+
+/**
+ * os sched os timer exp 
+ *  
+ * Called when the OS tick timer expires. Search the sleep list for any tasks 
+ * that need waking up. This occurs when the current OS time exceeds the next 
+ * wakeup time stored in the task. Any tasks that need waking up will be 
+ * removed from the sleep list and added to the run list. 
+ * 
+ */
+void
+os_sched_os_timer_exp(void)
+{
+    struct os_task *t;
+    struct os_task *next;
+    os_time_t now; 
+    os_sr_t sr;
+
+    now = os_time_get();
+
+    OS_ENTER_CRITICAL(sr);
+
+    /*
+     * Wakeup any tasks that have their sleep timer expired
+     */
+    t = TAILQ_FIRST(&g_os_sleep_list);
+    while (t) {
+        /* If task waiting forever, do not check next wakeup time */
+        if (t->t_flags & OS_TASK_FLAG_NO_TIMEOUT) {
+            break;
+        }
+        next = TAILQ_NEXT(t, t_os_list);
+        if (OS_TIME_TICK_GEQ(now, t->t_next_wakeup)) {
+            os_sched_wakeup(t);
+        } else {
+            break;
+        }
+        t = next;
+    }
+
+    OS_EXIT_CRITICAL(sr); 
+}
+
+/*
+ * Return the number of ticks until the first sleep timer expires.If there are
+ * no such tasks then return OS_TIMEOUT_NEVER instead.
+ */
+os_time_t
+os_sched_wakeup_ticks(os_time_t now)
+{
+    os_time_t rt;
+    struct os_task *t;
+
+    OS_ASSERT_CRITICAL();
+
+    t = TAILQ_FIRST(&g_os_sleep_list);
+    if (t == NULL || (t->t_flags & OS_TASK_FLAG_NO_TIMEOUT)) {
+        rt = OS_TIMEOUT_NEVER;
+    } else if (OS_TIME_TICK_GEQ(t->t_next_wakeup, now)) {
+        rt = t->t_next_wakeup - now;   
+    } else {
+        rt = 0;     /* wakeup time was in the past */
+    }
+    return (rt);
+}
+
+/**
+ * os sched next task 
+ *  
+ * Returns the task that we should be running. This is the task at the head 
+ * of the run list. 
+ *  
+ * NOTE: if you want to guarantee that the os run list does not change after 
+ * calling this function you have to call it with interrupts disabled. 
+ * 
+ * @return struct os_task* 
+ */
+struct os_task *  
+os_sched_next_task(void) 
+{
+    return (TAILQ_FIRST(&g_os_run_list));
+}
+
+/**
+ * os sched resort 
+ *  
+ * Resort a task that is in the ready list as its priority has 
+ * changed. If the task is not in the ready state, there is 
+ * nothing to do. 
+ * 
+ * @param t Pointer to task to insert back into ready to run 
+ *          list.
+ *  
+ * NOTE: this function expects interrupts to be disabled so they 
+ * are not disabled here. 
+ */
+void 
+os_sched_resort(struct os_task *t) 
+{
+    if (t->t_state == OS_TASK_READY) {
+        TAILQ_REMOVE(&g_os_run_list, t, t_os_list);
+        os_sched_insert(t);
+    }
+}
+



[16/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/flash_test/src/flash_test/flash_test.c
----------------------------------------------------------------------
diff --git a/libs/flash_test/src/flash_test/flash_test.c b/libs/flash_test/src/flash_test/flash_test.c
deleted file mode 100644
index 980cbba..0000000
--- a/libs/flash_test/src/flash_test/flash_test.c
+++ /dev/null
@@ -1,155 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-#include <inttypes.h>
-#include <os/os.h>
-#include <console/console.h>
-#include <flash_test/flash_test.h>
-#include <hal/hal_bsp.h>
-#include <hal/hal_flash.h>
-#include <hal/hal_flash_int.h>
-#include <shell/shell.h>
-#include <stdio.h>
-#include <string.h>
-
-static int flash_cli_cmd(int argc, char **argv);
-static struct shell_cmd flash_cmd_struct = {
-    .sc_cmd = "flash",
-    .sc_cmd_func = flash_cli_cmd
-};
-
-static int
-flash_cli_cmd(int argc, char **argv)
-{
-    const struct hal_flash *hf;
-    uint32_t off = 0;
-    uint32_t sz = 1;
-    int sec_cnt;
-    int i;
-    int soff;
-    char *eptr;
-    char tmp_buf[8];
-    char pr_str[80];
-
-    hf = bsp_flash_dev(0);
-    if (!hf) {
-        console_printf("No flash device present\n");
-        return 0;
-    }
-    if (argc == 1) {
-        /*
-         * print status
-         */
-        console_printf("Flash at 0x%lx size 0x%lx with %d sectors,"
-          "alignment req %d bytes\n", 
-                (long unsigned int) hf->hf_base_addr, 
-                (long unsigned int) hf->hf_size,
-                hf->hf_sector_cnt, 
-                hf->hf_align);
-        sec_cnt = hf->hf_sector_cnt;
-        if (sec_cnt > 32) {
-            sec_cnt = 32;
-        }
-        for (i = 0; i < sec_cnt; i++) {
-            console_printf("  %d: %lx\n", i, 
-                    (long unsigned int) hal_flash_sector_size(hf, i));
-        }
-        if (sec_cnt != hf->hf_sector_cnt) {
-            console_printf("...  %d: %lx\n", hf->hf_sector_cnt - 1,
-              (long unsigned int) hal_flash_sector_size(hf, hf->hf_sector_cnt - 1));
-        }
-        return 0;
-    }
-    if (argc > 2) {
-        off = strtoul(argv[2], &eptr, 0);
-        if (*eptr != '\0') {
-            console_printf("Invalid offset %s\n", argv[2]);
-            goto err;
-        }
-    }
-    if (argc > 3) {
-        sz = strtoul(argv[3], &eptr, 0);
-        if (*eptr != '\0') {
-            console_printf("Invalid size %s\n", argv[3]);
-            goto err;
-        }
-    }
-    if (!strcmp(argv[1], "erase")) {
-        console_printf("Erase 0x%lx + %lx\n", 
-                (long unsigned int) off, (long unsigned int) sz);
-
-        if (hal_flash_erase(0, off, sz)) {
-            console_printf("Flash erase failed\n");
-        }
-        console_printf("Done!\n");
-    } else if (!strcmp(argv[1], "read")) {
-        console_printf("Read 0x%lx + %lx\n", 
-                (long unsigned int) off, (long unsigned int) sz);
-        sz += off;
-        while (off < sz) {
-            sec_cnt = min(sizeof(tmp_buf), sz - off);
-            if (hal_flash_read(0, off, tmp_buf, sec_cnt)) {
-                console_printf("flash read failure at %lx\n", 
-                        (long unsigned int) off);
-                break;
-            }
-            for (i = 0, soff = 0; i < sec_cnt; i++) {
-                soff += snprintf(pr_str + soff, sizeof(pr_str) - soff,
-                  "0x%02x ", tmp_buf[i] & 0xff);
-            }
-            console_printf("  0x%lx: %s\n", 
-                    (long unsigned int) off, pr_str);
-            off += sec_cnt;
-        }
-    } else if (!strcmp(argv[1], "write")) {
-        console_printf("Write 0x%lx + %lx\n", 
-                (long unsigned int) off, (long unsigned int) sz);
-
-        sz += off;
-        for (i = 0; i < sizeof(tmp_buf); i++) {
-            tmp_buf[i] = i + 1;
-        }
-
-        while (off < sz) {
-            sec_cnt = min(sizeof(tmp_buf), sz - off);
-            if (hal_flash_write(0, off, tmp_buf, sec_cnt)) {
-                console_printf("flash write failure at %lx\n", 
-                        (long unsigned int) off);
-            }
-            off += sec_cnt;
-        }
-        console_printf("Done!\n");
-    } else if ( !strcmp(argv[1], "?") || !strcmp(argv[1], "help"))
-    {
-        console_printf("Commands Available\n");
-        console_printf("flash -- dumps sector map \n");
-        console_printf("flash read <offset> <size> -- reads bytes from flash \n");
-        console_printf("flash write <offset>  <size>  -- writes incrementing data pattern 0-8 to flash \n");
-        console_printf("flash erase <offset> <size> -- erases flash \n");
-    }
-    return 0;
-err:
-    return -1;
-}
-
-
-int
-flash_test_init(void) {
-    shell_cmd_register(&flash_cmd_struct);
-    return 0;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/imgmgr/pkg.yml
----------------------------------------------------------------------
diff --git a/libs/imgmgr/pkg.yml b/libs/imgmgr/pkg.yml
index 65d12a5..8ff48b4 100644
--- a/libs/imgmgr/pkg.yml
+++ b/libs/imgmgr/pkg.yml
@@ -24,8 +24,8 @@ pkg.homepage: "http://mynewt.apache.org/"
 pkg.keywords:
 
 pkg.deps:
-    - libs/bootutil
-    - libs/util
+    - boot/bootutil
+    - encoding/base64
 
 pkg.req_apis:
     - newtmgr
@@ -37,7 +37,7 @@ pkg.deps.IMGMGR_COREDUMP:
     - sys/coredump
 
 pkg.deps.IMGMGR_SHELL:
-    - libs/shell
+    - sys/shell
 
 pkg.init_function: imgmgr_module_init
 pkg.init_stage: 5

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/imgmgr/src/imgmgr.c
----------------------------------------------------------------------
diff --git a/libs/imgmgr/src/imgmgr.c b/libs/imgmgr/src/imgmgr.c
index 04ec43c..ed317b8 100644
--- a/libs/imgmgr/src/imgmgr.c
+++ b/libs/imgmgr/src/imgmgr.c
@@ -26,7 +26,7 @@
 #include "hal/hal_bsp.h"
 #include "hal/flash_map.h"
 #include "json/json.h"
-#include "util/base64.h"
+#include "base64/base64.h"
 #include "bootutil/image.h"
 #include "bootutil/bootutil_misc.h"
 #include "newtmgr/newtmgr.h"

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/imgmgr/src/imgmgr_boot.c
----------------------------------------------------------------------
diff --git a/libs/imgmgr/src/imgmgr_boot.c b/libs/imgmgr/src/imgmgr_boot.c
index 0473f25..1168278 100644
--- a/libs/imgmgr/src/imgmgr_boot.c
+++ b/libs/imgmgr/src/imgmgr_boot.c
@@ -28,7 +28,7 @@
 #include <bootutil/image.h>
 #include <bootutil/bootutil_misc.h>
 #include <json/json.h>
-#include <util/base64.h>
+#include <base64/base64.h>
 #include <hal/hal_bsp.h>
 
 #include "imgmgr/imgmgr.h"

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/imgmgr/src/imgmgr_cli.c
----------------------------------------------------------------------
diff --git a/libs/imgmgr/src/imgmgr_cli.c b/libs/imgmgr/src/imgmgr_cli.c
index da1c0bf..ee0e862 100644
--- a/libs/imgmgr/src/imgmgr_cli.c
+++ b/libs/imgmgr/src/imgmgr_cli.c
@@ -32,7 +32,7 @@
 #include <bootutil/image.h>
 #include <bootutil/bootutil_misc.h>
 
-#include <util/hex.h>
+#include <base64/hex.h>
 
 #include "imgmgr/imgmgr.h"
 #include "imgmgr_priv.h"

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/imgmgr/src/imgmgr_coredump.c
----------------------------------------------------------------------
diff --git a/libs/imgmgr/src/imgmgr_coredump.c b/libs/imgmgr/src/imgmgr_coredump.c
index 17c430d..79ff608 100644
--- a/libs/imgmgr/src/imgmgr_coredump.c
+++ b/libs/imgmgr/src/imgmgr_coredump.c
@@ -26,7 +26,7 @@
 #include "hal/flash_map.h"
 #include "newtmgr/newtmgr.h"
 #include "coredump/coredump.h"
-#include "util/base64.h"
+#include "base64/base64.h"
 
 #include "imgmgr/imgmgr.h"
 #include "imgmgr_priv.h"

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/imgmgr/src/imgmgr_fs.c
----------------------------------------------------------------------
diff --git a/libs/imgmgr/src/imgmgr_fs.c b/libs/imgmgr/src/imgmgr_fs.c
index af4579d..d44fd55 100644
--- a/libs/imgmgr/src/imgmgr_fs.c
+++ b/libs/imgmgr/src/imgmgr_fs.c
@@ -32,7 +32,7 @@
 #include "bootutil/image.h"
 #include "fs/fs.h"
 #include "json/json.h"
-#include "util/base64.h"
+#include "base64/base64.h"
 #include "bsp/bsp.h"
 
 #include "imgmgr/imgmgr.h"

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/iotivity/pkg.yml
----------------------------------------------------------------------
diff --git a/libs/iotivity/pkg.yml b/libs/iotivity/pkg.yml
index 6c2480e..bfd0b31 100644
--- a/libs/iotivity/pkg.yml
+++ b/libs/iotivity/pkg.yml
@@ -24,8 +24,8 @@ pkg.homepage: "https://www.iotivity.org/"
 pkg.keywords:
 
 pkg.deps:
-    - "@apache-mynewt-core/libs/tinycbor"
-    - "@apache-mynewt-core/libs/os"
+    - "@apache-mynewt-core/encoding/tinycbor"
+    - "@apache-mynewt-core/kernel/os"
     - "@apache-mynewt-core/sys/log"
 
 pkg.deps.OC_TRANSPORT_GATT:
@@ -34,10 +34,10 @@ pkg.deps.OC_TRANSPORT_GATT:
     - "@apache-mynewt-core/net/nimble/host/services/gatt"
 
 pkg.deps.OC_TRANSPORT_IP:
-    - "@apache-mynewt-core/sys/mn_socket"
+    - "@apache-mynewt-core/net/ip/mn_socket"
 
 pkg.deps.OC_TRANSPORT_SERIAL:
-    - "@apache-mynewt-core/libs/shell"
+    - "@apache-mynewt-core/sys/shell"
 
 # remove debug option to save logging
 pkg.cflags: -std=c99

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/json/MSJSON_COPYING
----------------------------------------------------------------------
diff --git a/libs/json/MSJSON_COPYING b/libs/json/MSJSON_COPYING
deleted file mode 100644
index 2267ff2..0000000
--- a/libs/json/MSJSON_COPYING
+++ /dev/null
@@ -1,28 +0,0 @@
-			BSD LICENSE
-
-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 name of the GPSD project 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 REGENTS 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.

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/json/include/json/json.h
----------------------------------------------------------------------
diff --git a/libs/json/include/json/json.h b/libs/json/include/json/json.h
deleted file mode 100644
index ecf098a..0000000
--- a/libs/json/include/json/json.h
+++ /dev/null
@@ -1,245 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 _JSON_H_
-#define _JSON_H_
-
-#include <stdbool.h>
-#include <stdint.h>
-#include <ctype.h>
-#include <stdio.h>
-#include <sys/types.h>
-
-
-#define JSON_VALUE_TYPE_BOOL   (0)
-#define JSON_VALUE_TYPE_UINT64 (1)
-#define JSON_VALUE_TYPE_INT64  (2)
-#define JSON_VALUE_TYPE_STRING (3)
-#define JSON_VALUE_TYPE_ARRAY  (4)
-#define JSON_VALUE_TYPE_OBJECT (5)
-
-/**
- * For encode.  The contents of a JSON value to encode.
- */
-struct json_value {
-    uint8_t jv_pad1;
-    uint8_t jv_type;
-    uint16_t jv_len;
-
-    union {
-        uint64_t u;
-        float fl;
-        char *str;
-        struct {
-            char **keys;
-            struct json_value **values;
-        } composite;
-    } jv_val;
-};
-
-#define JSON_VALUE_STRING(__jv, __str)        \
-    (__jv)->jv_type = JSON_VALUE_TYPE_STRING; \
-    (__jv)->jv_len = strlen(__str);           \
-    (__jv)->jv_val.str = (__str);
-
-#define JSON_VALUE_STRINGN(__jv, __str, __len) \
-    (__jv)->jv_type = JSON_VALUE_TYPE_STRING;  \
-    (__jv)->jv_len = (uint16_t) (__len);                    \
-    (__jv)->jv_val.str = (__str);
-
-#define JSON_VALUE_BOOL(__jv, __v)            \
-    (__jv)->jv_type = JSON_VALUE_TYPE_BOOL;   \
-    (__jv)->jv_val.u = (__v);
-
-#define JSON_VALUE_INT(__jv, __v)             \
-    (__jv)->jv_type = JSON_VALUE_TYPE_INT64;  \
-    (__jv)->jv_val.u = (uint64_t) __v;
-
-#define JSON_VALUE_UINT(__jv, __v)            \
-    (__jv)->jv_type = JSON_VALUE_TYPE_UINT64; \
-    (__jv)->jv_val.u = (uint64_t) __v;
-
-/* Encoding functions */
-typedef int (*json_write_func_t)(void *buf, char *data,
-        int len);
-
-struct json_encoder {
-    json_write_func_t je_write;
-    void *je_arg;
-    int je_wr_commas:1;
-    char je_encode_buf[64];
-};
-
-
-#define JSON_NITEMS(x) (int)(sizeof(x)/sizeof(x[0]))
-
-int json_encode_object_start(struct json_encoder *);
-int json_encode_object_key(struct json_encoder *encoder, char *key);
-int json_encode_object_entry(struct json_encoder *, char *,
-        struct json_value *);
-int json_encode_object_finish(struct json_encoder *);
-
-int json_encode_array_name(struct json_encoder *encoder, char *name);
-int json_encode_array_start(struct json_encoder *encoder);
-int json_encode_array_value(struct json_encoder *encoder, struct json_value *val);
-int json_encode_array_finish(struct json_encoder *encoder);
-
-/* Json parser definitions */
-typedef enum {
-    t_integer,
-    t_uinteger,
-    t_real,
-    t_string,
-    t_boolean,
-    t_character,
-    t_object,
-    t_structobject,
-    t_array,
-    t_check,
-    t_ignore
-} json_type;
-
-struct json_enum_t {
-    char *name;
-    long long int value;
-};
-
-struct json_array_t {
-    json_type element_type;
-    union {
-        struct {
-            const struct json_attr_t *subtype;
-            char *base;
-            size_t stride;
-        } objects;
-        struct {
-            char **ptrs;
-            char *store;
-            int storelen;
-        } strings;
-        struct {
-            long long int *store;
-        } integers;
-        struct {
-            long long unsigned int *store;
-        } uintegers;
-        struct {
-            double *store;
-        } reals;
-        struct {
-            bool *store;
-        } booleans;
-    } arr;
-    int *count;
-    int maxlen;
-};
-
-struct json_attr_t {
-    char *attribute;
-    json_type type;
-    union {
-        long long int *integer;
-        long long unsigned int *uinteger;
-        double *real;
-        char *string;
-        bool *boolean;
-        char *character;
-        struct json_array_t array;
-        size_t offset;
-    } addr;
-    union {
-        long long int integer;
-        long long unsigned int uinteger;
-        double real;
-        bool boolean;
-        char character;
-        char *check;
-    } dflt;
-    size_t len;
-    const struct json_enum_t *map;
-    bool nodefault;
-};
-
-struct json_buffer;
-
-/* when you implement a json buffer, you must implement these functions */
-
-/* returns the next character in the buffer or '\0'*/
-typedef char (*json_buffer_read_next_byte_t)(struct json_buffer *);
-/* returns the previous character in the buffer or '\0' */
-typedef char (*json_buffer_read_prev_byte_t)(struct json_buffer *);
-/* returns the number of characters read or zero */
-typedef int (*json_buffer_readn_t)(struct json_buffer *, char *buf, int n);
-
-struct json_buffer {
-    json_buffer_readn_t jb_readn;
-    json_buffer_read_next_byte_t jb_read_next;
-    json_buffer_read_prev_byte_t jb_read_prev;
-};
-
-#define JSON_ATTR_MAX        31        /* max chars in JSON attribute name */
-#define JSON_VAL_MAX        512        /* max chars in JSON value part */
-
-int json_read_object(struct json_buffer *, const struct json_attr_t *);
-int json_read_array(struct json_buffer *, const struct json_array_t *);
-
-#define JSON_ERR_OBSTART     1   /* non-WS when expecting object start */
-#define JSON_ERR_ATTRSTART   2   /* non-WS when expecting attrib start */
-#define JSON_ERR_BADATTR     3   /* unknown attribute name */
-#define JSON_ERR_ATTRLEN     4   /* attribute name too long */
-#define JSON_ERR_NOARRAY     5   /* saw [ when not expecting array */
-#define JSON_ERR_NOBRAK      6   /* array element specified, but no [ */
-#define JSON_ERR_STRLONG     7   /* string value too long */
-#define JSON_ERR_TOKLONG     8   /* token value too long */
-#define JSON_ERR_BADTRAIL    9   /* garbage while expecting comma or } or ] */
-#define JSON_ERR_ARRAYSTART  10  /* didn't find expected array start */
-#define JSON_ERR_OBJARR      11  /* error while parsing object array */
-#define JSON_ERR_SUBTOOLONG  12  /* too many array elements */
-#define JSON_ERR_BADSUBTRAIL 13  /* garbage while expecting array comma */
-#define JSON_ERR_SUBTYPE     14  /* unsupported array element type */
-#define JSON_ERR_BADSTRING   15  /* error while string parsing */
-#define JSON_ERR_CHECKFAIL   16  /* check attribute not matched */
-#define JSON_ERR_NOPARSTR    17  /* can't support strings in parallel arrays */
-#define JSON_ERR_BADENUM     18  /* invalid enumerated value */
-#define JSON_ERR_QNONSTRING  19  /* saw quoted value when expecting nonstring */
-#define JSON_ERR_NONQSTRING  19  /* didn't see quoted value when expecting string */
-#define JSON_ERR_MISC        20  /* other data conversion error */
-#define JSON_ERR_BADNUM      21  /* error while parsing a numerical argument */
-#define JSON_ERR_NULLPTR     22  /* unexpected null value or attribute pointer */
-
-/*
- * Use the following macros to declare template initializers for structobject
- * arrays.  Writing the equivalents out by hand is error-prone.
- *
- * JSON_STRUCT_OBJECT takes a structure name s, and a fieldname f in s.
- *
- * JSON_STRUCT_ARRAY takes the name of a structure array, a pointer to a an
- * initializer defining the subobject type, and the address of an integer to
- * store the length in.
- */
-#define JSON_STRUCT_OBJECT(s, f)        .addr.offset = offsetof(s, f)
-#define JSON_STRUCT_ARRAY(a, e, n) \
-        .addr.array.element_type = t_structobject, \
-        .addr.array.arr.objects.subtype = e, \
-        .addr.array.arr.objects.base = (char*)a, \
-        .addr.array.arr.objects.stride = sizeof(a[0]), \
-        .addr.array.count = n, \
-        .addr.array.maxlen = (int)(sizeof(a)/sizeof(a[0]))
-
-#endif /* _JSON_H_ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/json/pkg.yml
----------------------------------------------------------------------
diff --git a/libs/json/pkg.yml b/libs/json/pkg.yml
deleted file mode 100644
index 4944622..0000000
--- a/libs/json/pkg.yml
+++ /dev/null
@@ -1,26 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you 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.
-#
-
-pkg.name: libs/json 
-pkg.description: JSON encoding / decoding library.
-pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
-pkg.homepage: "http://mynewt.apache.org/"
-pkg.keywords:
-
-pkg.cflags.float_user: -DFLOAT_SUPPORT

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/json/src/json_decode.c
----------------------------------------------------------------------
diff --git a/libs/json/src/json_decode.c b/libs/json/src/json_decode.c
deleted file mode 100644
index b78bbfd..0000000
--- a/libs/json/src/json_decode.c
+++ /dev/null
@@ -1,670 +0,0 @@
-#include <stdio.h>
-#include <stdlib.h>
-#include <assert.h>
-
-#include "json/json.h"
-
-/**
- * This file is based upon microjson, from Eric S Raymond.
- *
- * License information for MicroJSON is in the package file MSJSON_COPYING,
- * it is BSD licensed source code.
- */
-
-
-/****************************************************************************
-
-NAME
-   mjson.c - parse JSON into fixed-extent data structures
-
-DESCRIPTION
-   This module parses a large subset of JSON (JavaScript Object
-Notation).  Unlike more general JSON parsers, it doesn't use malloc(3)
-and doesn't support polymorphism; you need to give it a set of
-template structures describing the expected shape of the incoming
-JSON, and it will error out if that shape is not matched.  When the
-parse succeeds, attribute values will be extracted into static
-locations specified in the template structures.
-
-   The "shape" of a JSON object in the type signature of its
-attributes (and attribute values, and so on recursively down through
-all nestings of objects and arrays).  This parser is indifferent to
-the order of attributes at any level, but you have to tell it in
-advance what the type of each attribute value will be and where the
-parsed value will be stored. The template structures may supply
-default values to be used when an expected attribute is omitted.
-
-   The preceding paragraph told one fib.  A single attribute may
-actually have a span of multiple specifications with different
-syntactically distinguishable types (e.g. string vs. real vs. integer
-vs. boolean, but not signed integer vs. unsigned integer).  The parser
-will match the right spec against the actual data.
-
-   The dialect this parses has some limitations.  First, it cannot
-recognize the JSON "null" value. Second, all elements of an array must
-be of the same type. Third, characters may not be array elements (this
-restriction could be lifted)
-
-   There are separate entry points for beginning a parse of either
-JSON object or a JSON array. JSON "float" quantities are actually
-stored as doubles.
-
-   This parser processes object arrays in one of two different ways,
-defending on whether the array subtype is declared as object or
-structobject.
-
-   Object arrays take one base address per object subfield, and are
-mapped into parallel C arrays (one per subfield).  Strings are not
-supported in this kind of array, as they don't have a "natural" size
-to use as an offset multiplier.
-
-   Structobjects arrays are a way to parse a list of objects to a set
-of modifications to a corresponding array of C structs.  The trick is
-that the array object initialization has to specify both the C struct
-array's base address and the stride length (the size of the C struct).
-If you initialize the offset fields with the correct offsetof calls,
-everything will work. Strings are supported but all string storage
-has to be inline in the struct.
-
-PERMISSIONS
-   This file is Copyright (c) 2014 by Eric S. Raymond
-   BSD terms apply: see the file COPYING in the distribution root for details.
-
-***************************************************************************/
-
-#include <string.h>
-#include <stdlib.h>
-#include <stdbool.h>
-#include <stdarg.h>
-#include <ctype.h>
-#include <math.h>        /* for HUGE_VAL */
-
-static void
-json_skip_ws(struct json_buffer *jb)
-{
-    char c;
-
-    do {
-        c = jb->jb_read_next(jb);
-    } while (isspace(c));
-
-    jb->jb_read_prev(jb);
-}
-
-static char
-json_peek(struct json_buffer *jb)
-{
-    char c;
-
-    jb->jb_read_next(jb);
-    c = jb->jb_read_prev(jb);
-
-    return c;
-}
-
-static char *
-json_target_address(const struct json_attr_t *cursor,
-        const struct json_array_t *parent, int offset)
-{
-    char *targetaddr = NULL;
-    if (parent == NULL || parent->element_type != t_structobject) {
-        /* ordinary case - use the address in the cursor structure */
-        switch (cursor->type) {
-        case t_ignore:
-            targetaddr = NULL;
-            break;
-        case t_integer:
-            targetaddr = (char *)&cursor->addr.integer[offset];
-            break;
-        case t_uinteger:
-            targetaddr = (char *)&cursor->addr.uinteger[offset];
-            break;
-        case t_real:
-            targetaddr = (char *)&cursor->addr.real[offset];
-            break;
-        case t_string:
-            targetaddr = cursor->addr.string;
-            break;
-        case t_boolean:
-            targetaddr = (char *)&cursor->addr.boolean[offset];
-            break;
-        case t_character:
-            targetaddr = (char *)&cursor->addr.character[offset];
-            break;
-        default:
-            targetaddr = NULL;
-            break;
-        }
-    } else {
-        /* tricky case - hacking a member in an array of structures */
-        targetaddr =
-            parent->arr.objects.base + (offset * parent->arr.objects.stride) +
-            cursor->addr.offset;
-    }
-    return targetaddr;
-}
-
-static int
-json_internal_read_object(struct json_buffer *jb,
-                          const struct json_attr_t *attrs,
-                          const struct json_array_t *parent,
-                          int offset)
-{
-    char c;
-    enum {
-        init, await_attr, in_attr, await_value, in_val_string,
-        in_escape, in_val_token, post_val, post_array
-    } state = 0;
-    char attrbuf[JSON_ATTR_MAX + 1], *pattr = NULL;
-    char valbuf[JSON_VAL_MAX + 1], *pval = NULL;
-    bool value_quoted = false;
-    char uescape[5];    /* enough space for 4 hex digits and '\0' */
-    const struct json_attr_t *cursor;
-    int substatus, n, maxlen = 0;
-    unsigned int u;
-    const struct json_enum_t *mp;
-    char *lptr;
-
-#ifdef S_SPLINT_S
-    /* prevents gripes about buffers not being completely defined */
-    memset(valbuf, '\0', sizeof(valbuf));
-    memset(attrbuf, '\0', sizeof(attrbuf));
-#endif /* S_SPLINT_S */
-
-    /* stuff fields with defaults in case they're omitted in the JSON input */
-    for (cursor = attrs; cursor->attribute != NULL; cursor++) {
-        if (!cursor->nodefault) {
-            lptr = json_target_address(cursor, parent, offset);
-            if (lptr != NULL) {
-                switch (cursor->type) {
-                case t_integer:
-                    memcpy(lptr, &cursor->dflt.integer, sizeof(long long int));
-                    break;
-                case t_uinteger:
-                    memcpy(lptr, &cursor->dflt.uinteger,
-                           sizeof(long long unsigned int));
-                    break;
-                case t_real:
-                    memcpy(lptr, &cursor->dflt.real, sizeof(double));
-                    break;
-                case t_string:
-                    if (parent != NULL
-                        && parent->element_type != t_structobject
-                        && offset > 0) {
-                        return JSON_ERR_NOPARSTR;
-                    }
-                    lptr[0] = '\0';
-                    break;
-                case t_boolean:
-                    memcpy(lptr, &cursor->dflt.boolean, sizeof(bool));
-                    break;
-                case t_character:
-                    lptr[0] = cursor->dflt.character;
-                    break;
-                case t_object:        /* silences a compiler warning */
-                case t_structobject:
-                case t_array:
-                case t_check:
-                case t_ignore:
-                    break;
-                }
-            }
-        }
-    }
-
-    /* parse input JSON */
-    for (c = jb->jb_read_next(jb); c != '\0'; c = jb->jb_read_next(jb)) {
-        switch (state) {
-        case init:
-            if (isspace((unsigned char) c)) {
-                continue;
-            } else if (c == '{') {
-                state = await_attr;
-            } else {
-                return JSON_ERR_OBSTART;
-            }
-            break;
-        case await_attr:
-            if (isspace((unsigned char) c)) {
-                continue;
-            } else if (c == '"') {
-                state = in_attr;
-                pattr = attrbuf;
-            } else if (c == '}') {
-                break;
-            } else {
-                return JSON_ERR_ATTRSTART;
-            }
-            break;
-        case in_attr:
-            if (pattr == NULL) {
-                /* don't update end here, leave at attribute start */
-                return JSON_ERR_NULLPTR;
-            }
-            if (c == '"') {
-                *pattr++ = '\0';
-                for (cursor = attrs; cursor->attribute != NULL; cursor++) {
-                    if (strcmp(cursor->attribute, attrbuf) == 0) {
-                        break;
-                    }
-                }
-                if (cursor->attribute == NULL) {
-                    /* don't update end here, leave at attribute start */
-                    return JSON_ERR_BADATTR;
-                }
-                state = await_value;
-                if (cursor->type == t_string) {
-                    maxlen = (int)cursor->len - 1;
-                } else if (cursor->type == t_check) {
-                    maxlen = (int)strlen(cursor->dflt.check);
-                } else if (cursor->type == t_ignore) {
-                    maxlen = JSON_VAL_MAX;
-                } else if (cursor->map != NULL) {
-                    maxlen = (int)sizeof(valbuf) - 1;
-                } else if (cursor->type == t_boolean) {
-                    maxlen = 5; /* false */
-                }
-                pval = valbuf;
-            } else if (pattr >= attrbuf + JSON_ATTR_MAX - 1) {
-                /* don't update end here, leave at attribute start */
-                return JSON_ERR_ATTRLEN;
-            } else {
-                *pattr++ = c;
-            }
-            break;
-        case await_value:
-            if (isspace((unsigned char) c) || c == ':') {
-                continue;
-            } else if (c == '[') {
-                if (cursor->type != t_array) {
-                    return JSON_ERR_NOARRAY;
-                }
-                c = jb->jb_read_prev(jb);
-                substatus = json_read_array(jb, &cursor->addr.array);
-                if (substatus != 0) {
-                    return substatus;
-                }
-                state = post_array;
-            } else if (cursor->type == t_array) {
-                return JSON_ERR_NOBRAK;
-            } else if (c == '"') {
-                value_quoted = true;
-                state = in_val_string;
-                pval = valbuf;
-            } else {
-                value_quoted = false;
-                state = in_val_token;
-                pval = valbuf;
-                *pval++ = c;
-            }
-            break;
-        case in_val_string:
-            if (pval == NULL) {
-                /* don't update end here, leave at value start */
-                return JSON_ERR_NULLPTR;
-            }
-            if (c == '\\') {
-                state = in_escape;
-            } else if (c == '"') {
-                *pval++ = '\0';
-                state = post_val;
-            } else if (pval > valbuf + JSON_VAL_MAX - 1
-                       || pval > valbuf + maxlen) {
-                /* don't update end here, leave at value start */
-                return JSON_ERR_STRLONG;        /*  */
-            } else {
-                *pval++ = c;
-            }
-            break;
-        case in_escape:
-            if (pval == NULL) {
-                /* don't update end here, leave at value start */
-                return JSON_ERR_NULLPTR;
-            }
-            switch (c) {
-            case 'b':
-                *pval++ = '\b';
-                break;
-            case 'f':
-                *pval++ = '\f';
-                break;
-            case 'n':
-                *pval++ = '\n';
-                break;
-            case 'r':
-                *pval++ = '\r';
-                break;
-            case 't':
-                *pval++ = '\t';
-                break;
-            case 'u':
-                for (n = 0; n < 4 && c != '\0'; n++) {
-                    uescape[n] = c;
-                    c = jb->jb_read_next(jb);
-                }
-                // Scroll back one
-                c = jb->jb_read_prev(jb);
-                (void)sscanf(uescape, "%04x", &u);
-                *pval++ = (char)u;        /* will truncate values above 0xff */
-                break;
-            default:                /* handles double quote and solidus */
-                *pval++ = c;
-                break;
-            }
-            state = in_val_string;
-            break;
-        case in_val_token:
-            if (pval == NULL) {
-                /* don't update end here, leave at value start */
-                return JSON_ERR_NULLPTR;
-            }
-            if (isspace((unsigned char) c) || c == ',' || c == '}') {
-                *pval = '\0';
-                state = post_val;
-                if (c == '}' || c == ',') {
-                    c = jb->jb_read_prev(jb);
-                }
-            } else if (pval > valbuf + JSON_VAL_MAX - 1) {
-                /* don't update end here, leave at value start */
-                return JSON_ERR_TOKLONG;
-            } else {
-                *pval++ = c;
-            }
-            break;
-        case post_val:
-            /*
-             * We know that cursor points at the first spec matching
-             * the current attribute.  We don't know that it's *the*
-             * correct spec; our dialect allows there to be any number
-             * of adjacent ones with the same attrname but different
-             * types.  Here's where we try to seek forward for a
-             * matching type/attr pair if we're not looking at one.
-             */
-            for (;;) {
-                int seeking = cursor->type;
-                if (value_quoted && (cursor->type == t_string)) {
-                    break;
-                }
-                if ((strcmp(valbuf, "true")==0 || strcmp(valbuf, "false")==0)
-                        && seeking == t_boolean) {
-                    break;
-                }
-                if (isdigit((unsigned char) valbuf[0])) {
-                    bool decimal = strchr(valbuf, '.') != NULL;
-                    if (decimal && seeking == t_real) {
-                        break;
-                    }
-                    if (!decimal && (seeking == t_integer ||
-                                     seeking == t_uinteger)) {
-                        break;
-                    }
-                }
-                if (cursor[1].attribute==NULL) {       /* out of possiblities */
-                    break;
-                }
-                if (strcmp(cursor[1].attribute, attrbuf)!=0) {
-                    break;
-                }
-                ++cursor;
-            }
-            if (value_quoted
-                && (cursor->type != t_string && cursor->type != t_character
-                    && cursor->type != t_check && cursor->type != t_ignore
-                    && cursor->map == 0)) {
-                return JSON_ERR_QNONSTRING;
-            }
-            if (!value_quoted
-                && (cursor->type == t_string || cursor->type == t_check
-                    || cursor->map != 0)) {
-                return JSON_ERR_NONQSTRING;
-            }
-            if (cursor->map != 0) {
-                for (mp = cursor->map; mp->name != NULL; mp++) {
-                    if (strcmp(mp->name, valbuf) == 0) {
-                        goto foundit;
-                    }
-                }
-                return JSON_ERR_BADENUM;
-              foundit:
-                (void)snprintf(valbuf, sizeof(valbuf), "%lld", mp->value);
-            }
-            lptr = json_target_address(cursor, parent, offset);
-            if (lptr != NULL) {
-                switch (cursor->type) {
-                case t_integer: {
-                        long long int tmp =
-                            (long long int)strtoll(valbuf, NULL, 10);
-                        memcpy(lptr, &tmp, sizeof(long long int));
-                    }
-                    break;
-                case t_uinteger: {
-                        long long unsigned int tmp =
-                            (long long unsigned int)strtoull(valbuf, NULL, 10);
-                        memcpy(lptr, &tmp, sizeof(long long unsigned int));
-                    }
-                    break;
-                case t_real: {
-#ifdef FLOAT_SUPPORT
-                        double tmp = atof(valbuf);
-                        memcpy(lptr, &tmp, sizeof(double));
-#else
-                        return JSON_ERR_MISC;
-#endif
-                    }
-                    break;
-                case t_string:
-                    if (parent != NULL
-                        && parent->element_type != t_structobject
-                        && offset > 0) {
-                        return JSON_ERR_NOPARSTR;
-                    }
-                    (void)strncpy(lptr, valbuf, cursor->len);
-                    valbuf[sizeof(valbuf)-1] = '\0';
-                    break;
-                case t_boolean: {
-                        bool tmp = (strcmp(valbuf, "true") == 0);
-                        memcpy(lptr, &tmp, sizeof(bool));
-                    }
-                    break;
-                case t_character:
-                    if (strlen(valbuf) > 1) {
-                        /* don't update end here, leave at value start */
-                        return JSON_ERR_STRLONG;
-                    } else {
-                        lptr[0] = valbuf[0];
-                    }
-                    break;
-                case t_ignore:        /* silences a compiler warning */
-                case t_object:        /* silences a compiler warning */
-                case t_structobject:
-                case t_array:
-                    break;
-                case t_check:
-                    if (strcmp(cursor->dflt.check, valbuf) != 0) {
-                        /* don't update end here, leave at start of attribute */
-                        return JSON_ERR_CHECKFAIL;
-                    }
-                    break;
-                }
-            }
-            /*@fallthrough@*/
-        case post_array:
-            if (isspace((unsigned char) c)) {
-                continue;
-            } else if (c == ',') {
-                state = await_attr;
-            } else if (c == '}') {
-                c = jb->jb_read_next(jb);
-                goto good_parse;
-            } else {
-                return JSON_ERR_BADTRAIL;
-            }
-            break;
-        }
-    }
-
-  good_parse:
-    /* in case there's another object following, consume trailing WS */
-    while (isspace((unsigned char) jb->jb_read_next(jb))) {
-    }
-    return 0;
-}
-
-int
-json_read_array(struct json_buffer *jb, const struct json_array_t *arr)
-{
-    char valbuf[64];
-    char c;
-    int substatus, offset, arrcount;
-    char *tp;
-    int n, count;
-
-    json_skip_ws(jb);
-
-    if (jb->jb_read_next(jb) != '[') {
-        return JSON_ERR_ARRAYSTART;
-    }
-
-    tp = arr->arr.strings.store;
-    arrcount = 0;
-
-    json_skip_ws(jb);
-
-    if (json_peek(jb) == ']') {
-        goto breakout;
-    }
-
-    for (offset = 0; offset < arr->maxlen; offset++) {
-        json_skip_ws(jb);
-
-        char *ep = NULL;
-        switch (arr->element_type) {
-        case t_string:
-            if (jb->jb_read_next(jb) != '"') {
-                return JSON_ERR_BADSTRING;
-            }
-            arr->arr.strings.ptrs[offset] = tp;
-            for (; tp - arr->arr.strings.store < arr->arr.strings.storelen;
-                 tp++) {
-                c = jb->jb_read_next(jb);
-                if (c == '"') {
-                    c = jb->jb_read_next(jb);
-                    *tp++ = '\0';
-                    goto stringend;
-                } else if (c == '\0') {
-                    return JSON_ERR_BADSTRING;
-                } else {
-                    *tp = c;
-                    c = jb->jb_read_next(jb);
-                }
-            }
-            return JSON_ERR_BADSTRING;
-          stringend:
-            break;
-        case t_object:
-        case t_structobject:
-            substatus =
-                json_internal_read_object(jb, arr->arr.objects.subtype, arr,
-                                          offset);
-            if (substatus != 0) {
-                return substatus;
-            }
-            break;
-        case t_integer:
-            n = jb->jb_readn(jb, valbuf, sizeof(valbuf)-1);
-            valbuf[n] = '\0';
-
-            arr->arr.integers.store[offset] = strtoll(valbuf, &ep, 0);
-            if (ep == valbuf) {
-                return JSON_ERR_BADNUM;
-            } else {
-                count = n - (ep - valbuf);
-                while (count-- > 0) {
-                    jb->jb_read_prev(jb);
-                }
-            }
-            break;
-        case t_uinteger:
-            n = jb->jb_readn(jb, valbuf, sizeof(valbuf)-1);
-            valbuf[n] = '\0';
-
-            arr->arr.uintegers.store[offset] = strtoull(valbuf, &ep, 0);
-            if (ep == valbuf) {
-                return JSON_ERR_BADNUM;
-            } else {
-                count = n - (ep - valbuf);
-                while (count-- > 0) {
-                    jb->jb_read_prev(jb);
-                }
-            }
-            break;
-        case t_real:
-#ifdef FLOAT_SUPPORT
-            n = jb->jb_readn(jb, valbuf, sizeof(valbuf)-1);
-            valbuf[n] = '\0';
-
-            arr->arr.reals.store[offset] = strtod(valbuf, &ep);
-            if (ep == valbuf) {
-                return JSON_ERR_BADNUM;
-            } else {
-                count = ep - valbuf;
-                while (count-- > 0) {
-                    c = jb->jb_read_next(jb);
-                }
-            }
-#else
-            return JSON_ERR_MISC;
-#endif
-            break;
-        case t_boolean:
-            n = jb->jb_readn(jb, valbuf, 5);
-            valbuf[n] = '\0';
-
-            if (strncmp(valbuf, "true", 4) == 0) {
-                arr->arr.booleans.store[offset] = true;
-                count = n - 4;
-            } else if (strncmp(valbuf, "false", 5) == 0) {
-                arr->arr.booleans.store[offset] = false;
-                count = n - 5;
-            } else {
-                return JSON_ERR_MISC;
-            }
-
-            assert(count >= 0);
-            while (count-- > 0) {
-                jb->jb_read_prev(jb);
-            }
-            break;
-        case t_character:
-        case t_array:
-        case t_check:
-        case t_ignore:
-            return JSON_ERR_SUBTYPE;
-        }
-        arrcount++;
-        json_skip_ws(jb);
-
-        c = jb->jb_read_next(jb);
-        if (c == ']') {
-            goto breakout;
-        } else if (c != ',') {
-            return JSON_ERR_BADSUBTRAIL;
-        }
-    }
-    return JSON_ERR_SUBTOOLONG;
-  breakout:
-    if (arr->count != NULL) {
-        *(arr->count) = arrcount;
-    }
-    return 0;
-}
-
-int
-json_read_object(struct json_buffer *jb, const struct json_attr_t *attrs)
-{
-    int st;
-
-    st = json_internal_read_object(jb, attrs, NULL, 0);
-    return st;
-}
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/json/src/json_encode.c
----------------------------------------------------------------------
diff --git a/libs/json/src/json_encode.c b/libs/json/src/json_encode.c
deleted file mode 100644
index 8512a66..0000000
--- a/libs/json/src/json_encode.c
+++ /dev/null
@@ -1,248 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include <stdio.h>
-#include <string.h>
-
-#include <json/json.h>
-
-#define JSON_ENCODE_OBJECT_START(__e) \
-    (__e)->je_write((__e)->je_arg, "{", sizeof("{")-1);
-
-#define JSON_ENCODE_OBJECT_END(__e) \
-    (__e)->je_write((__e)->je_arg, "}", sizeof("}")-1);
-
-#define JSON_ENCODE_ARRAY_START(__e) \
-    (__e)->je_write((__e)->je_arg, "[", sizeof("[")-1);
-
-#define JSON_ENCODE_ARRAY_END(__e) \
-    (__e)->je_write((__e)->je_arg, "]", sizeof("]")-1);
-
-
-int
-json_encode_object_start(struct json_encoder *encoder)
-{
-    if (encoder->je_wr_commas) {
-        encoder->je_write(encoder->je_arg, ",", sizeof(",")-1);
-        encoder->je_wr_commas = 0;
-    }
-    JSON_ENCODE_OBJECT_START(encoder);
-    encoder->je_wr_commas = 0;
-
-    return (0);
-}
-
-static int
-json_encode_value(struct json_encoder *encoder, struct json_value *jv)
-{
-    int rc;
-    int i;
-    int len;
-
-    switch (jv->jv_type) {
-        case JSON_VALUE_TYPE_BOOL:
-            len = sprintf(encoder->je_encode_buf, "%s",
-                    jv->jv_val.u > 0 ? "true" : "false");
-            encoder->je_write(encoder->je_arg, encoder->je_encode_buf, len);
-            break;
-        case JSON_VALUE_TYPE_UINT64:
-            len = sprintf(encoder->je_encode_buf, "%llu",
-                    jv->jv_val.u);
-            encoder->je_write(encoder->je_arg, encoder->je_encode_buf, len);
-            break;
-        case JSON_VALUE_TYPE_INT64:
-            len = sprintf(encoder->je_encode_buf, "%lld",
-                    jv->jv_val.u);
-            encoder->je_write(encoder->je_arg, encoder->je_encode_buf, len);
-            break;
-        case JSON_VALUE_TYPE_STRING:
-            encoder->je_write(encoder->je_arg, "\"", sizeof("\"")-1);
-            for (i = 0; i < jv->jv_len; i++) {
-                switch (jv->jv_val.str[i]) {
-                    case '"':
-                    case '/':
-                    case '\\':
-                        encoder->je_write(encoder->je_arg, "\\",
-                                sizeof("\\")-1);
-                        encoder->je_write(encoder->je_arg,
-                                (char *) &jv->jv_val.str[i], 1);
-
-                        break;
-                    case '\t':
-                        encoder->je_write(encoder->je_arg, "\\t",
-                                sizeof("\\t")-1);
-                        break;
-                    case '\r':
-                        encoder->je_write(encoder->je_arg, "\\r",
-                                sizeof("\\r")-1);
-                        break;
-                    case '\n':
-                        encoder->je_write(encoder->je_arg, "\\n",
-                                sizeof("\\n")-1);
-                        break;
-                    case '\f':
-                        encoder->je_write(encoder->je_arg, "\\f",
-                                sizeof("\\f")-1);
-                        break;
-                    case '\b':
-                        encoder->je_write(encoder->je_arg, "\\b",
-                                sizeof("\\b")-1);
-                        break;
-                   default:
-                        encoder->je_write(encoder->je_arg,
-                                (char *) &jv->jv_val.str[i], 1);
-                        break;
-                }
-
-            }
-            encoder->je_write(encoder->je_arg, "\"", sizeof("\"")-1);
-            break;
-        case JSON_VALUE_TYPE_ARRAY:
-            JSON_ENCODE_ARRAY_START(encoder);
-            for (i = 0; i < jv->jv_len; i++) {
-                rc = json_encode_value(encoder, jv->jv_val.composite.values[i]);
-                if (rc != 0) {
-                    goto err;
-                }
-                if (i != jv->jv_len - 1) {
-                    encoder->je_write(encoder->je_arg, ",", sizeof(",")-1);
-                }
-            }
-            JSON_ENCODE_ARRAY_END(encoder);
-            break;
-        case JSON_VALUE_TYPE_OBJECT:
-            JSON_ENCODE_OBJECT_START(encoder);
-            for (i = 0; i < jv->jv_len; i++) {
-                rc = json_encode_object_entry(encoder,
-                        jv->jv_val.composite.keys[i],
-                        jv->jv_val.composite.values[i]);
-                if (rc != 0) {
-                    goto err;
-                }
-            }
-            JSON_ENCODE_OBJECT_END(encoder);
-            break;
-        default:
-            rc = -1;
-            goto err;
-    }
-
-
-    return (0);
-err:
-    return (rc);
-}
-
-int
-json_encode_object_key(struct json_encoder *encoder, char *key)
-{
-    if (encoder->je_wr_commas) {
-        encoder->je_write(encoder->je_arg, ",", sizeof(",")-1);
-        encoder->je_wr_commas = 0;
-    }
-
-    /* Write the key entry */
-    encoder->je_write(encoder->je_arg, "\"", sizeof("\"")-1);
-    encoder->je_write(encoder->je_arg, key, strlen(key));
-    encoder->je_write(encoder->je_arg, "\": ", sizeof("\": ")-1);
-
-    return (0);
-}
-
-int
-json_encode_object_entry(struct json_encoder *encoder, char *key,
-        struct json_value *val)
-{
-    int rc;
-
-    if (encoder->je_wr_commas) {
-        encoder->je_write(encoder->je_arg, ",", sizeof(",")-1);
-        encoder->je_wr_commas = 0;
-    }
-    /* Write the key entry */
-    encoder->je_write(encoder->je_arg, "\"", sizeof("\"")-1);
-    encoder->je_write(encoder->je_arg, key, strlen(key));
-    encoder->je_write(encoder->je_arg, "\": ", sizeof("\": ")-1);
-
-    rc = json_encode_value(encoder, val);
-    if (rc != 0) {
-        goto err;
-    }
-    encoder->je_wr_commas = 1;
-
-    return (0);
-err:
-    return (rc);
-}
-
-int
-json_encode_object_finish(struct json_encoder *encoder)
-{
-    JSON_ENCODE_OBJECT_END(encoder);
-    /* Useful in case of nested objects. */
-    encoder->je_wr_commas = 1;
-
-    return (0);
-}
-
-int
-json_encode_array_name(struct json_encoder *encoder, char *name)
-{
-    return json_encode_object_key(encoder, name);
-}
-
-int
-json_encode_array_start(struct json_encoder *encoder)
-{
-    JSON_ENCODE_ARRAY_START(encoder);
-    encoder->je_wr_commas = 0;
-
-    return (0);
-}
-
-int
-json_encode_array_value(struct json_encoder *encoder, struct json_value *jv)
-{
-    int rc;
-
-    if (encoder->je_wr_commas) {
-        encoder->je_write(encoder->je_arg, ",", sizeof(",")-1);
-        encoder->je_wr_commas = 0;
-    }
-
-    rc = json_encode_value(encoder, jv);
-    if (rc != 0) {
-        goto err;
-    }
-    encoder->je_wr_commas = 1;
-
-    return (0);
-err:
-    return (rc);
-}
-
-
-int
-json_encode_array_finish(struct json_encoder *encoder)
-{
-    encoder->je_wr_commas = 1;
-    JSON_ENCODE_ARRAY_END(encoder);
-
-    return (0);
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/json/test/pkg.yml
----------------------------------------------------------------------
diff --git a/libs/json/test/pkg.yml b/libs/json/test/pkg.yml
deleted file mode 100644
index 65f2de0..0000000
--- a/libs/json/test/pkg.yml
+++ /dev/null
@@ -1,30 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you 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.
-#
-pkg.name: libs/json/test
-pkg.type: unittest
-pkg.description: "JSON unit tests."
-pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
-pkg.homepage: "http://mynewt.apache.org/"
-pkg.keywords:
-
-pkg.deps: 
-    - libs/json
-    - libs/testutil
-
-pkg.deps.SELFTEST:
-    - libs/console/stub

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/json/test/src/test_json.c
----------------------------------------------------------------------
diff --git a/libs/json/test/src/test_json.c b/libs/json/test/src/test_json.c
deleted file mode 100644
index dab3f06..0000000
--- a/libs/json/test/src/test_json.c
+++ /dev/null
@@ -1,43 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include "syscfg/syscfg.h"
-#include "testutil/testutil.h"
-#include "test_json.h"
-
-
-TEST_SUITE(test_json_suite) {
-    test_json_simple_encode();
-    test_json_simple_decode();
-}
-
-#if MYNEWT_VAL(SELFTEST)
-
-int
-main(int argc, char **argv)
-{
-    tu_config.tc_print_results = 1;
-    tu_init();
-
-    test_json_suite();
-
-    return tu_any_failed;
-}
-
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/json/test/src/test_json.h
----------------------------------------------------------------------
diff --git a/libs/json/test/src/test_json.h b/libs/json/test/src/test_json.h
deleted file mode 100644
index ea5efcf..0000000
--- a/libs/json/test/src/test_json.h
+++ /dev/null
@@ -1,27 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 TEST_JSON_H
-#define TEST_JSON_H
-
-TEST_CASE_DECL(test_json_simple_encode);
-TEST_CASE_DECL(test_json_simple_decode);
-
-#endif /* TEST_JSON_H */
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/json/test/src/test_json_simple.c
----------------------------------------------------------------------
diff --git a/libs/json/test/src/test_json_simple.c b/libs/json/test/src/test_json_simple.c
deleted file mode 100644
index 0f9e10e..0000000
--- a/libs/json/test/src/test_json_simple.c
+++ /dev/null
@@ -1,360 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include <assert.h>
-#include <string.h>
-#include "testutil/testutil.h"
-#include "test_json.h"
-#include "json/json.h"
-
-static char *output = "{\"KeyBool\": true,\"KeyInt\": -1234,\"KeyUint\": 1353214,\"KeyString\": \"foobar\",\"KeyStringN\": \"foobarlong\",\"KeyIntArr\": [153,2532,-322]}";
-
-static char *output1 ="{\"KeyBoolArr\": [true, false], \"KeyUintArr\": [0, 65535, 4294967295, 8589934590, 3451257]}";
-static char *outputboolspace = "{\"KeyBoolArr\": [    true    ,    false,true         ]}";
-static char *outputboolempty = "{\"KeyBoolArr\": , \"KeyBoolArr\": [  ]}";
-
-static char bigbuf[512];
-static int buf_index;
-
-static int test_write(void *buf, char* data, int len) {
-    int i;
-    for(i = 0; i < len; i++) {
-        bigbuf[buf_index++] = data[i];
-    }
-    return len;
-}
-
-TEST_CASE(test_json_simple_encode){
-    struct json_encoder encoder;
-    struct json_value value;
-    int rc;
-
-    /* reset the state of the internal test */
-    buf_index = 0;
-    memset(&encoder, 0, sizeof(encoder));
-
-    encoder.je_write = test_write;
-    encoder.je_arg= NULL;
-
-    rc = json_encode_object_start(&encoder);
-    TEST_ASSERT(rc == 0);
-
-    JSON_VALUE_BOOL(&value, 1);
-    rc = json_encode_object_entry(&encoder, "KeyBool", &value);
-    TEST_ASSERT(rc == 0);
-
-    JSON_VALUE_INT(&value, -1234);
-    rc = json_encode_object_entry(&encoder, "KeyInt", &value);
-    TEST_ASSERT(rc == 0);
-
-    JSON_VALUE_UINT(&value, 1353214);
-    rc = json_encode_object_entry(&encoder, "KeyUint", &value);
-    TEST_ASSERT(rc == 0);
-
-    JSON_VALUE_STRING(&value, "foobar");
-    rc = json_encode_object_entry(&encoder, "KeyString", &value);
-    TEST_ASSERT(rc == 0);
-
-    /* we'll decode later differently */
-    JSON_VALUE_STRINGN(&value, "foobarlongstring", 10);
-    rc = json_encode_object_entry(&encoder, "KeyStringN", &value);
-    TEST_ASSERT(rc == 0);
-
-    rc = json_encode_array_name(&encoder, "KeyIntArr");
-    TEST_ASSERT(rc == 0);
-
-    rc = json_encode_array_start(&encoder);
-    TEST_ASSERT(rc == 0);
-
-    JSON_VALUE_INT(&value, 153);
-    rc = json_encode_array_value(&encoder, &value);
-    TEST_ASSERT(rc == 0);
-
-    JSON_VALUE_INT(&value, 2532);
-    rc = json_encode_array_value(&encoder, &value);
-    TEST_ASSERT(rc == 0);
-
-    JSON_VALUE_INT(&value, -322);
-    rc = json_encode_array_value(&encoder, &value);
-    TEST_ASSERT(rc == 0);
-
-    rc = json_encode_array_finish(&encoder);
-    TEST_ASSERT(rc == 0);
-
-    rc = json_encode_object_finish(&encoder);
-    TEST_ASSERT(rc == 0);
-
-    /* does it match what we expect it to */
-    rc = strcmp(bigbuf, output);
-    TEST_ASSERT(rc == 0);
-}
-
-
-/* a test structure to hold the json flat buffer and pass bytes
- * to the decoder */
-struct test_jbuf {
-    /* json_buffer must be first element in the structure */
-    struct json_buffer json_buf;
-    char * start_buf;
-    char * end_buf;
-    int current_position;
-};
-
-
-static char
-test_jbuf_read_next(struct json_buffer *jb) {
-    char c;
-    struct test_jbuf  *ptjb = (struct test_jbuf*) jb;
-
-    if((ptjb->start_buf + ptjb->current_position) <= ptjb->end_buf) {
-        c = *(ptjb->start_buf + ptjb->current_position);
-        ptjb->current_position++;
-        return c;
-    }
-    return '\0';
-}
-
-/* this goes backward in the buffer one character */
-static char
-test_jbuf_read_prev(struct json_buffer *jb) {
-    char c;
-    struct test_jbuf  *ptjb = (struct test_jbuf*) jb;
-    if(ptjb->current_position) {
-       ptjb->current_position--;
-       c = *(ptjb->start_buf + ptjb->current_position);
-       return c;
-    }
-
-    /* can't rewind */
-    return '\0';
-
-}
-
-static int
-test_jbuf_readn(struct json_buffer *jb, char *buf, int size) {
-    struct test_jbuf  *ptjb = (struct test_jbuf*) jb;
-
-    int remlen;
-
-    remlen = ptjb->end_buf - (ptjb->start_buf + ptjb->current_position);
-    if (size > remlen) {
-        size = remlen;
-    }
-
-    memcpy(buf, ptjb->start_buf + ptjb->current_position, size);
-    ptjb->current_position += size;
-    return size;
-}
-
-static void
-test_buf_init(struct test_jbuf *ptjb, char *string) {
-    /* initialize the decode */
-    ptjb->json_buf.jb_read_next = test_jbuf_read_next;
-    ptjb->json_buf.jb_read_prev = test_jbuf_read_prev;
-    ptjb->json_buf.jb_readn = test_jbuf_readn;
-    ptjb->start_buf = string;
-    ptjb->end_buf = string + strlen(string);
-    /* end buf points to the NULL */
-    ptjb->current_position = 0;
-}
-
-/* now test the decode on a string */
-TEST_CASE(test_json_simple_decode){
-    struct test_jbuf tjb;
-    struct test_jbuf tjb1;
-    struct test_jbuf tjbboolspacearr;
-    struct test_jbuf tjbboolemptyarr;
-    long long unsigned int uint_val;
-    long long int int_val;
-    bool bool_val;
-    char string1[16];
-    char string2[16];
-    long long int intarr[8];
-    int rc;
-    int rc1;
-    int rcbsa;
-    int array_count;
-    int array_countemp;
-    bool boolarr[2];
-    unsigned long long uintarr[5];
-    int array_count1;
-    int array_count1u;
-    bool boolspacearr[3];
-    bool boolemptyarr[2];
-    
-    struct json_attr_t test_attr[7] = {
-        [0] = {
-            .attribute = "KeyBool",
-            .type = t_boolean,
-            .addr.boolean = &bool_val,
-            .nodefault = true
-        },
-        [1] = {
-            .attribute = "KeyInt",
-            .type = t_integer,
-            .addr.integer = &int_val,
-            .nodefault = true
-            },
-        [2] = {
-            .attribute = "KeyUint",
-            .type = t_uinteger,
-            .addr.uinteger = &uint_val,
-            .nodefault = true
-            },
-        [3] = {
-            .attribute = "KeyString",
-            .type = t_string,
-            .addr.string = string1,
-            .nodefault = true,
-            .len = sizeof(string1)
-            },
-        [4] = {
-            .attribute = "KeyStringN",
-            .type = t_string,
-            .addr.string = string2,
-            .nodefault = true,
-            .len = sizeof(string2)
-        },
-        [5] = {
-            .attribute = "KeyIntArr",
-            .type = t_array,
-            .addr.array = {
-                .element_type = t_integer,
-                .arr.integers.store = intarr,
-                .maxlen = sizeof intarr / sizeof intarr[0],
-                .count = &array_count,
-            },
-            .nodefault = true,
-            .len = sizeof(intarr)
-        },
-        [6] = {
-            .attribute = NULL
-        }
-    };
-    
-    test_buf_init(&tjb, output);
-
-    rc = json_read_object(&tjb.json_buf, test_attr);
-    TEST_ASSERT(rc==0);
-    TEST_ASSERT(bool_val == 1);
-    TEST_ASSERT(int_val ==  -1234);
-    TEST_ASSERT(uint_val == 1353214);
-
-    rc = memcmp(string1, "foobar", strlen("foobar"));
-    TEST_ASSERT(rc==0);
-
-    rc = memcmp(string2, "foobarlongstring", 10);
-    TEST_ASSERT(rc==0);
-
-    TEST_ASSERT(array_count == 3);
-    TEST_ASSERT(intarr[0] == 153);
-    TEST_ASSERT(intarr[1] == 2532);
-    TEST_ASSERT(intarr[2] == -322);
-
-   /*testing for the boolean*/
-   struct json_attr_t test_attr1[2] = {
-       [0] = {
-           .attribute = "KeyBoolArr",
-           .type = t_array,
-           .addr.array = {
-               .element_type = t_boolean,
-               .arr.booleans.store = boolarr,
-               .maxlen = sizeof boolarr / sizeof boolarr[0],
-               .count =&array_count1,
-           },
-           .nodefault = true,
-           .len = sizeof( boolarr),
-       },
-
-       [1] = {
-           .attribute = "KeyUintArr",
-           .type = t_array,
-           .addr.array = {
-               .element_type = t_uinteger,
-               .arr.uintegers.store = uintarr,
-               .maxlen = sizeof uintarr / sizeof uintarr[0],
-               .count =&array_count1u,
-           },
-           .nodefault = true,
-           .len = sizeof( uintarr),
-       }
-   };
-   
-   test_buf_init(&tjb1, output1);
-
-   rc1 = json_read_object(&tjb1.json_buf, test_attr1);
-   TEST_ASSERT(rc1==0);
-
-   TEST_ASSERT(boolarr[0] == true);
-   TEST_ASSERT(boolarr[1] == false);
-
-   TEST_ASSERT(uintarr[0] == 0);
-   TEST_ASSERT(uintarr[1] == 65535);
-   TEST_ASSERT(uintarr[2] == 4294967295ULL);
-   TEST_ASSERT(uintarr[3] == 8589934590ULL);
-   TEST_ASSERT(uintarr[4] == 3451257ULL);
-
-    /*testing arrays with empty spaces within the elements*/
-    struct json_attr_t test_boolspacearr[2] = {
-       [0] = {    
-           .attribute = "KeyBoolArr",
-           .type = t_array,
-           .addr.array = {
-               .element_type = t_boolean,
-               .arr.booleans.store = boolspacearr,
-               .maxlen = sizeof boolspacearr / sizeof boolspacearr[0],
-               .count =&array_count1,
-           },
-           .nodefault = true,
-           .len = sizeof( boolspacearr),
-       }
-           
-    };
-    
-    test_buf_init(&tjbboolspacearr, outputboolspace);
-
-    rcbsa = json_read_object(&tjbboolspacearr.json_buf, test_boolspacearr);
-    TEST_ASSERT(rcbsa == 0);
-
-    TEST_ASSERT(boolspacearr[0] == true);
-    TEST_ASSERT(boolspacearr[1] == false);
-    TEST_ASSERT(boolspacearr[2] == true);
-
-    /*testing array with empty value*/
-    struct json_attr_t test_boolemptyarr[2] = {
-        [0] = {
-            .attribute = "KeyBoolArr",
-           .type = t_array,
-           .addr.array = {
-               .element_type = t_boolean,
-               .arr.booleans.store = boolemptyarr,
-               .maxlen = sizeof boolemptyarr / sizeof boolemptyarr[0],
-               .count =&array_countemp,
-           },
-           .nodefault = true,
-           .len = sizeof( boolemptyarr),
-        }
-    };
-   
-   test_buf_init(&tjbboolemptyarr, outputboolempty);
-
-    rcbsa = json_read_object(&tjbboolemptyarr.json_buf, test_boolemptyarr);
-    TEST_ASSERT(rcbsa == 6); 
-    
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/newtmgr/nmgr_os/pkg.yml
----------------------------------------------------------------------
diff --git a/libs/newtmgr/nmgr_os/pkg.yml b/libs/newtmgr/nmgr_os/pkg.yml
index 66a3f13..21c7eca 100644
--- a/libs/newtmgr/nmgr_os/pkg.yml
+++ b/libs/newtmgr/nmgr_os/pkg.yml
@@ -25,10 +25,10 @@ pkg.keywords:
 
 pkg.deps:
     - hw/hal
-    - libs/os
-    - libs/json
+    - kernel/os
+    - encoding/json
     - libs/util
-    - libs/testutil
+    - test/testutil
     - sys/reboot
 
 pkg.req_apis:

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/newtmgr/pkg.yml
----------------------------------------------------------------------
diff --git a/libs/newtmgr/pkg.yml b/libs/newtmgr/pkg.yml
index 0afb997..8312355 100644
--- a/libs/newtmgr/pkg.yml
+++ b/libs/newtmgr/pkg.yml
@@ -25,11 +25,11 @@ pkg.keywords:
 
 pkg.deps:
     - hw/hal
-    - libs/os
-    - libs/json
+    - kernel/os
+    - encoding/json
     - libs/newtmgr/nmgr_os
     - libs/util
-    - libs/shell
+    - sys/shell
     - sys/reboot
 
 pkg.deps.BLE_HOST:

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/newtmgr/transport/ble/pkg.yml
----------------------------------------------------------------------
diff --git a/libs/newtmgr/transport/ble/pkg.yml b/libs/newtmgr/transport/ble/pkg.yml
index 8c444fe..e3a9117 100644
--- a/libs/newtmgr/transport/ble/pkg.yml
+++ b/libs/newtmgr/transport/ble/pkg.yml
@@ -26,7 +26,7 @@ pkg.keywords:
     - bluetooth
 
 pkg.deps:
-    - libs/os
+    - kernel/os
     - net/nimble
 
 pkg.init_function: newtmgr_ble_pkg_init

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/newtmgr_oic/pkg.yml
----------------------------------------------------------------------
diff --git a/libs/newtmgr_oic/pkg.yml b/libs/newtmgr_oic/pkg.yml
index 69cc00b..3bd41fb 100644
--- a/libs/newtmgr_oic/pkg.yml
+++ b/libs/newtmgr_oic/pkg.yml
@@ -24,13 +24,13 @@ pkg.homepage: "http://mynewt.apache.org/"
 pkg.keywords:
 
 pkg.deps:
-    - libs/os
+    - kernel/os
     - libs/iotivity
-    - libs/json
+    - encoding/json
     - libs/newtmgr/nmgr_os
     - libs/util
-    - libs/testutil
-    - libs/shell
+    - test/testutil
+    - sys/shell
     - sys/reboot
 
 pkg.cflags:

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/include/os/arch/cortex_m0/os/os_arch.h
----------------------------------------------------------------------
diff --git a/libs/os/include/os/arch/cortex_m0/os/os_arch.h b/libs/os/include/os/arch/cortex_m0/os/os_arch.h
deleted file mode 100755
index 1a83ba9..0000000
--- a/libs/os/include/os/arch/cortex_m0/os/os_arch.h
+++ /dev/null
@@ -1,74 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 _OS_ARCH_ARM_H
-#define _OS_ARCH_ARM_H
-
-#include <stdint.h>
-#include <mcu/cortex_m0.h>
-
-struct os_task;
-
-/* Run in priviliged or unprivileged Thread mode */
-#define OS_RUN_PRIV         (0)
-#define OS_RUN_UNPRIV       (1)
-
-/* CPU status register */
-typedef uint32_t os_sr_t;
-/* Stack type, aligned to a 32-bit word. */
-#define OS_STACK_PATTERN    (0xdeadbeef)
-
-typedef uint32_t os_stack_t;
-#define OS_ALIGNMENT        (4)
-#define OS_STACK_ALIGNMENT  (8)
-
-/*
- * Stack sizes for common OS tasks
- */
-#define OS_SANITY_STACK_SIZE (64)
-#define OS_IDLE_STACK_SIZE (64)
-
-#define OS_STACK_ALIGN(__nmemb) \
-    (OS_ALIGN((__nmemb), OS_STACK_ALIGNMENT))
-
-/* Enter a critical section, save processor state, and block interrupts */
-#define OS_ENTER_CRITICAL(__os_sr) (__os_sr = os_arch_save_sr())
-/* Exit a critical section, restore processor state and unblock interrupts */
-#define OS_EXIT_CRITICAL(__os_sr) (os_arch_restore_sr(__os_sr))
-#define OS_ASSERT_CRITICAL() (assert(os_arch_in_critical()))
-
-os_stack_t *os_arch_task_stack_init(struct os_task *, os_stack_t *, int);
-void timer_handler(void);
-void os_arch_ctx_sw(struct os_task *);
-os_sr_t os_arch_save_sr(void);
-void os_arch_restore_sr(os_sr_t);
-int os_arch_in_critical(void);
-void os_arch_init(void);
-uint32_t os_arch_start(void);
-os_error_t os_arch_os_init(void);
-os_error_t os_arch_os_start(void);
-void os_set_env(os_stack_t *);
-void os_arch_init_task_stack(os_stack_t *sf);
-void os_default_irq_asm(void);
-
-/* External function prototypes supplied by BSP */
-void os_bsp_systick_init(uint32_t os_ticks_per_sec, int prio);
-void os_bsp_ctx_sw(void);
-
-#endif /* _OS_ARCH_ARM_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/include/os/arch/cortex_m4/os/os_arch.h
----------------------------------------------------------------------
diff --git a/libs/os/include/os/arch/cortex_m4/os/os_arch.h b/libs/os/include/os/arch/cortex_m4/os/os_arch.h
deleted file mode 100755
index 9e43a7a..0000000
--- a/libs/os/include/os/arch/cortex_m4/os/os_arch.h
+++ /dev/null
@@ -1,75 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 _OS_ARCH_ARM_H
-#define _OS_ARCH_ARM_H
-
-#include <stdint.h>
-#include "mcu/cortex_m4.h"
-
-struct os_task;
-
-/* Run in priviliged or unprivileged Thread mode */
-#define OS_RUN_PRIV         (0)
-#define OS_RUN_UNPRIV       (1)
-
-/* CPU status register */
-typedef uint32_t os_sr_t;
-/* Stack type, aligned to a 32-bit word. */
-#define OS_STACK_PATTERN    (0xdeadbeef)
-
-typedef uint32_t os_stack_t;
-#define OS_ALIGNMENT        (4)
-#define OS_STACK_ALIGNMENT  (8)
-
-/*
- * Stack sizes for common OS tasks
- */
-#define OS_SANITY_STACK_SIZE (64)
-#define OS_IDLE_STACK_SIZE (64)
-
-#define OS_STACK_ALIGN(__nmemb) \
-    (OS_ALIGN((__nmemb), OS_STACK_ALIGNMENT))
-
-/* Enter a critical section, save processor state, and block interrupts */
-#define OS_ENTER_CRITICAL(__os_sr) (__os_sr = os_arch_save_sr())
-/* Exit a critical section, restore processor state and unblock interrupts */
-#define OS_EXIT_CRITICAL(__os_sr) (os_arch_restore_sr(__os_sr))
-#define OS_ASSERT_CRITICAL() (assert(os_arch_in_critical()))
-
-os_stack_t *os_arch_task_stack_init(struct os_task *, os_stack_t *, int);
-void timer_handler(void);
-void os_arch_ctx_sw(struct os_task *);
-os_sr_t os_arch_save_sr(void);
-void os_arch_restore_sr(os_sr_t);
-int os_arch_in_critical(void);
-void os_arch_init(void);
-uint32_t os_arch_start(void);
-os_error_t os_arch_os_init(void);
-os_error_t os_arch_os_start(void);
-void os_set_env(os_stack_t *);
-void os_arch_init_task_stack(os_stack_t *sf);
-void os_default_irq_asm(void);
-
-/* External function prototypes supplied by BSP */
-void os_bsp_systick_init(uint32_t os_tick_per_sec, int prio);
-void os_bsp_idle(os_time_t ticks);
-void os_bsp_ctx_sw(void);
-
-#endif /* _OS_ARCH_ARM_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/include/os/arch/sim/os/os_arch.h
----------------------------------------------------------------------
diff --git a/libs/os/include/os/arch/sim/os/os_arch.h b/libs/os/include/os/arch/sim/os/os_arch.h
deleted file mode 100644
index d9570c8..0000000
--- a/libs/os/include/os/arch/sim/os/os_arch.h
+++ /dev/null
@@ -1,74 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 _OS_ARCH_SIM_H
-#define _OS_ARCH_SIM_H
-
-#include <mcu/mcu_sim.h>
-
-struct os_task;
-
-/* CPU status register */
-typedef unsigned int os_sr_t;
-/* Stack type, aligned to a 32-bit word. */
-#define OS_STACK_PATTERN (0xdeadbeef)
-
-typedef unsigned int os_stack_t;
-#define OS_ALIGNMENT (4)
-#define OS_STACK_ALIGNMENT (16)
-
-/*
- * Stack sizes for common OS tasks
- */
-#define OS_SANITY_STACK_SIZE (1024)
-#define OS_IDLE_STACK_SIZE (1024)
-
-/*
- * The 'sim' architecture-specific code does not have as much control on
- * stack usage as the real embedded architectures.
- *
- * For e.g. the space occupied by the signal handler frame on the task
- * stack is entirely dependent on the host OS.
- *
- * Deal with this by scaling the stack size by a factor of 16. The scaling
- * factor can be arbitrarily large because the stacks are allocated from
- * BSS and thus don't add to either the executable size or resident
- * memory.
- */
-#define OS_STACK_ALIGN(__nmemb) \
-    (OS_ALIGN(((__nmemb) * 16), OS_STACK_ALIGNMENT))
-
-/* Enter a critical section, save processor state, and block interrupts */
-#define OS_ENTER_CRITICAL(__os_sr) (__os_sr = os_arch_save_sr())
-/* Exit a critical section, restore processor state and unblock interrupts */
-#define OS_EXIT_CRITICAL(__os_sr) (os_arch_restore_sr(__os_sr))
-#define OS_ASSERT_CRITICAL() (assert(os_arch_in_critical()))
-
-void _Die(char *file, int line);
-
-os_stack_t *os_arch_task_stack_init(struct os_task *, os_stack_t *, int);
-void os_arch_ctx_sw(struct os_task *);
-os_sr_t os_arch_save_sr(void);
-void os_arch_restore_sr(os_sr_t sr);
-int os_arch_in_critical(void);
-os_error_t os_arch_os_init(void);
-void os_arch_os_stop(void);
-os_error_t os_arch_os_start(void);
-
-#endif /* _OS_ARCH_SIM_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/include/os/endian.h
----------------------------------------------------------------------
diff --git a/libs/os/include/os/endian.h b/libs/os/include/os/endian.h
deleted file mode 100644
index ffb054d..0000000
--- a/libs/os/include/os/endian.h
+++ /dev/null
@@ -1,92 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 H_ENDIAN_
-#define H_ENDIAN_
-
-#include <inttypes.h>
-
-#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
-
-#ifndef ntohll
-#define ntohll(x)  ((uint64_t)(x))
-#endif
-
-#ifndef htonll
-#define htonll(x)  ((uint64_t)(x))
-#endif
-
-#ifndef ntohl
-#define ntohl(x)   ((uint32_t)(x))
-#endif
-
-#ifndef htonl
-#define htonl(x)   ((uint32_t)(x))
-#endif
-
-#ifndef ntohs
-#define ntohs(x)   ((uint16_t)(x))
-#endif
-
-#ifndef htons
-#define htons(x)   ((uint16_t)(x))
-#endif
-
-#else
-
-#ifndef ntohll
-#define ntohll(x)   ((uint64_t)                     \
-     ((((x) & 0xff00000000000000ull) >> 56) |       \
-      (((x) & 0x00ff000000000000ull) >> 40) |       \
-      (((x) & 0x0000ff0000000000ull) >> 24) |       \
-      (((x) & 0x000000ff00000000ull) >>  8) |       \
-      (((x) & 0x00000000ff000000ull) <<  8) |       \
-      (((x) & 0x0000000000ff0000ull) << 24) |       \
-      (((x) & 0x000000000000ff00ull) << 40) |       \
-      (((x) & 0x00000000000000ffull) << 56)))
-#endif
-
-#ifndef htonll
-#define htonll      ntohll
-#endif
-
-#ifndef ntohl
-#define ntohl(x)    ((uint32_t)                     \
-    ((((x) & 0xff000000) >> 24) |                   \
-     (((x) & 0x00ff0000) >>  8) |                   \
-     (((x) & 0x0000ff00) <<  8) |                   \
-     (((x) & 0x000000ff) << 24)))
-#endif
-
-#ifndef htonl
-#define htonl       ntohl
-#endif
-
-#ifndef htons
-#define htons(x)   ((uint16_t)                      \
-    ((((x) & 0xff00) >> 8) |                        \
-     (((x) & 0x00ff) << 8)))
-#endif
-
-#ifndef ntohs
-#define ntohs       htons
-#endif
-
-#endif
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/include/os/os.h
----------------------------------------------------------------------
diff --git a/libs/os/include/os/os.h b/libs/os/include/os/os.h
deleted file mode 100644
index 0f1879c..0000000
--- a/libs/os/include/os/os.h
+++ /dev/null
@@ -1,101 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 _OS_H
-#define _OS_H
-
-#include <stdlib.h>
-//#include <stdint.h>
-
-#ifndef min
-#define min(a, b) ((a)<(b)?(a):(b))
-#endif
-
-#ifndef max
-#define max(a, b) ((a)>(b)?(a):(b))
-#endif
-
-#define os_get_return_addr() (__builtin_return_address(0))
-
-#define OS_ALIGN(__n, __a) (                             \
-        (((__n) & ((__a) - 1)) == 0)                   ? \
-            (__n)                                      : \
-            ((__n) + ((__a) - ((__n) & ((__a) - 1))))    \
-        )
-
-
-/**
- * Whether or not the operating system has been started.  Set to
- * 1 right before first task is run.
- */
-extern int g_os_started;
-
-int os_info_init(void);
-
-/**
- * Returns 1 if the OS has been started, 0 if it has not yet been
- * been started.
- */
-int os_started(void);
-
-/* OS error enumerations */
-enum os_error {
-    OS_OK = 0,
-    OS_ENOMEM = 1,
-    OS_EINVAL = 2,
-    OS_INVALID_PARM = 3,
-    OS_MEM_NOT_ALIGNED = 4,
-    OS_BAD_MUTEX = 5,
-    OS_TIMEOUT = 6,
-    OS_ERR_IN_ISR = 7,      /* Function cannot be called from ISR */
-    OS_ERR_PRIV = 8,        /* Privileged access error */
-    OS_NOT_STARTED = 9,     /* Operating must be started to call this function, but isn't */
-    OS_ENOENT = 10,         /* No such thing */
-    OS_EBUSY = 11,          /* Resource busy */
-    OS_ERROR = 12,           /* Generic Error */
-};
-
-#define OS_WAIT_FOREVER (-1)
-
-typedef enum os_error os_error_t;
-
-#define OS_IDLE_PRIO (0xff)
-
-void os_init(void);
-void os_start(void);
-
-/* XXX: Not sure if this should go here; I want to differentiate API that
- * should be called by application developers as those that should not. */
-void os_init_idle_task(void);
-
-#include "os/os_sanity.h"
-#include "os/os_arch.h"
-#include "os/os_time.h"
-#include "os/os_task.h"
-#include "os/os_sched.h"
-#include "os/os_eventq.h"
-#include "os/os_callout.h"
-#include "os/os_heap.h"
-#include "os/os_mutex.h"
-#include "os/os_sem.h"
-#include "os/os_mempool.h"
-#include "os/os_mbuf.h"
-#include "os/os_dev.h"
-
-#endif /* _OS_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/include/os/os_callout.h
----------------------------------------------------------------------
diff --git a/libs/os/include/os/os_callout.h b/libs/os/include/os/os_callout.h
deleted file mode 100644
index baa377a..0000000
--- a/libs/os/include/os/os_callout.h
+++ /dev/null
@@ -1,60 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 _OS_CALLOUT_H
-#define _OS_CALLOUT_H
-
-#define OS_CALLOUT_F_QUEUED (0x01)
-
-struct os_callout {
-    struct os_event c_ev;
-    struct os_eventq *c_evq;
-    uint32_t c_ticks;
-    TAILQ_ENTRY(os_callout) c_next;
-};
-
-typedef void (*os_callout_func_t)(void *);
-
-struct os_callout_func {
-    /* Must be the first element in the structure for casting
-     * purposes.
-     */
-    struct os_callout cf_c;
-    os_callout_func_t cf_func;
-};
-#define CF_ARG(__cf) ((__cf)->cf_c.c_ev.ev_arg)
-
-void os_callout_func_init(struct os_callout_func *cf, struct os_eventq *evq,
-  os_callout_func_t timo_func, void *ev_arg);
-void os_callout_stop(struct os_callout *);
-int os_callout_reset(struct os_callout *, int32_t);
-void os_callout_tick(void);
-os_time_t os_callout_wakeup_ticks(os_time_t now);
-
-static inline int
-os_callout_queued(struct os_callout *c)
-{
-    return c->c_next.tqe_prev != NULL;
-}
-
-#endif /* _OS_CALLOUT_H */
-
-
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/include/os/os_cfg.h
----------------------------------------------------------------------
diff --git a/libs/os/include/os/os_cfg.h b/libs/os/include/os/os_cfg.h
deleted file mode 100644
index 40c1e91..0000000
--- a/libs/os/include/os/os_cfg.h
+++ /dev/null
@@ -1,25 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 _OS_CFG_H_
-#define _OS_CFG_H_ 
-
-
-#endif /* _OS_CFG_H_ */



[39/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/hw/cmsis-core/src/ext/core_cm4.h
----------------------------------------------------------------------
diff --git a/hw/cmsis-core/src/ext/core_cm4.h b/hw/cmsis-core/src/ext/core_cm4.h
new file mode 100644
index 0000000..13db4ed
--- /dev/null
+++ b/hw/cmsis-core/src/ext/core_cm4.h
@@ -0,0 +1,1772 @@
+/**************************************************************************//**
+ * @file     core_cm4.h
+ * @brief    CMSIS Cortex-M4 Core Peripheral Access Layer Header File
+ * @version  V3.20
+ * @date     25. February 2013
+ *
+ * @note
+ *
+ ******************************************************************************/
+/* Copyright (c) 2009 - 2013 ARM LIMITED
+
+   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 ARM 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 COPYRIGHT HOLDERS AND CONTRIBUTORS BE
+   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+   POSSIBILITY OF SUCH DAMAGE.
+   ---------------------------------------------------------------------------*/
+
+
+#if defined ( __ICCARM__ )
+ #pragma system_include  /* treat file as system include file for MISRA check */
+#endif
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+#ifndef __CORE_CM4_H_GENERIC
+#define __CORE_CM4_H_GENERIC
+
+/** \page CMSIS_MISRA_Exceptions  MISRA-C:2004 Compliance Exceptions
+  CMSIS violates the following MISRA-C:2004 rules:
+
+   \li Required Rule 8.5, object/function definition in header file.<br>
+     Function definitions in header files are used to allow 'inlining'.
+
+   \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.<br>
+     Unions are used for effective representation of core registers.
+
+   \li Advisory Rule 19.7, Function-like macro defined.<br>
+     Function-like macros are used to allow more efficient code.
+ */
+
+
+/*******************************************************************************
+ *                 CMSIS definitions
+ ******************************************************************************/
+/** \ingroup Cortex_M4
+  @{
+ */
+
+/*  CMSIS CM4 definitions */
+#define __CM4_CMSIS_VERSION_MAIN  (0x03)                                   /*!< [31:16] CMSIS HAL main version   */
+#define __CM4_CMSIS_VERSION_SUB   (0x20)                                   /*!< [15:0]  CMSIS HAL sub version    */
+#define __CM4_CMSIS_VERSION       ((__CM4_CMSIS_VERSION_MAIN << 16) | \
+                                    __CM4_CMSIS_VERSION_SUB          )     /*!< CMSIS HAL version number         */
+
+#define __CORTEX_M                (0x04)                                   /*!< Cortex-M Core                    */
+
+
+#if   defined ( __CC_ARM )
+  #define __ASM            __asm                                      /*!< asm keyword for ARM Compiler          */
+  #define __INLINE         __inline                                   /*!< inline keyword for ARM Compiler       */
+  #define __STATIC_INLINE  static __inline
+
+#elif defined ( __ICCARM__ )
+  #define __ASM            __asm                                      /*!< asm keyword for IAR Compiler          */
+  #define __INLINE         inline                                     /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */
+  #define __STATIC_INLINE  static inline
+
+#elif defined ( __TMS470__ )
+  #define __ASM            __asm                                      /*!< asm keyword for TI CCS Compiler       */
+  #define __STATIC_INLINE  static inline
+
+#elif defined ( __GNUC__ )
+  #define __ASM            __asm                                      /*!< asm keyword for GNU Compiler          */
+  #define __INLINE         inline                                     /*!< inline keyword for GNU Compiler       */
+  #define __STATIC_INLINE  static inline
+
+#elif defined ( __TASKING__ )
+  #define __ASM            __asm                                      /*!< asm keyword for TASKING Compiler      */
+  #define __INLINE         inline                                     /*!< inline keyword for TASKING Compiler   */
+  #define __STATIC_INLINE  static inline
+
+#endif
+
+/** __FPU_USED indicates whether an FPU is used or not. For this, __FPU_PRESENT has to be checked prior to making use of FPU specific registers and functions.
+*/
+#if defined ( __CC_ARM )
+  #if defined __TARGET_FPU_VFP
+    #if (__FPU_PRESENT == 1)
+      #define __FPU_USED       1
+    #else
+      #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
+      #define __FPU_USED       0
+    #endif
+  #else
+    #define __FPU_USED         0
+  #endif
+
+#elif defined ( __ICCARM__ )
+  #if defined __ARMVFP__
+    #if (__FPU_PRESENT == 1)
+      #define __FPU_USED       1
+    #else
+      #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
+      #define __FPU_USED       0
+    #endif
+  #else
+    #define __FPU_USED         0
+  #endif
+
+#elif defined ( __TMS470__ )
+  #if defined __TI_VFP_SUPPORT__
+    #if (__FPU_PRESENT == 1)
+      #define __FPU_USED       1
+    #else
+      #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
+      #define __FPU_USED       0
+    #endif
+  #else
+    #define __FPU_USED         0
+  #endif
+
+#elif defined ( __GNUC__ )
+  #if defined (__VFP_FP__) && !defined(__SOFTFP__)
+    #if (__FPU_PRESENT == 1)
+      #define __FPU_USED       1
+    #else
+      #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
+      #define __FPU_USED       0
+    #endif
+  #else
+    #define __FPU_USED         0
+  #endif
+
+#elif defined ( __TASKING__ )
+  #if defined __FPU_VFP__
+    #if (__FPU_PRESENT == 1)
+      #define __FPU_USED       1
+    #else
+      #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
+      #define __FPU_USED       0
+    #endif
+  #else
+    #define __FPU_USED         0
+  #endif
+#endif
+
+#include <stdint.h>                      /* standard types definitions                      */
+#include <core_cmInstr.h>     /* Core Instruction Access                         */
+#include <core_cmFunc.h>      /* Core Function Access                            */
+#include <core_cm4_simd.h>    /* Compiler specific SIMD Intrinsics               */
+
+#endif /* __CORE_CM4_H_GENERIC */
+
+#ifndef __CMSIS_GENERIC
+
+#ifndef __CORE_CM4_H_DEPENDANT
+#define __CORE_CM4_H_DEPENDANT
+
+/* check device defines and use defaults */
+#if defined __CHECK_DEVICE_DEFINES
+  #ifndef __CM4_REV
+    #define __CM4_REV               0x0000
+    #warning "__CM4_REV not defined in device header file; using default!"
+  #endif
+
+  #ifndef __FPU_PRESENT
+    #define __FPU_PRESENT             0
+    #warning "__FPU_PRESENT not defined in device header file; using default!"
+  #endif
+
+  #ifndef __MPU_PRESENT
+    #define __MPU_PRESENT             0
+    #warning "__MPU_PRESENT not defined in device header file; using default!"
+  #endif
+
+  #ifndef __NVIC_PRIO_BITS
+    #define __NVIC_PRIO_BITS          4
+    #warning "__NVIC_PRIO_BITS not defined in device header file; using default!"
+  #endif
+
+  #ifndef __Vendor_SysTickConfig
+    #define __Vendor_SysTickConfig    0
+    #warning "__Vendor_SysTickConfig not defined in device header file; using default!"
+  #endif
+#endif
+
+/* IO definitions (access restrictions to peripheral registers) */
+/**
+    \defgroup CMSIS_glob_defs CMSIS Global Defines
+
+    <strong>IO Type Qualifiers</strong> are used
+    \li to specify the access to peripheral variables.
+    \li for automatic generation of peripheral register debug information.
+*/
+#ifdef __cplusplus
+  #define   __I     volatile             /*!< Defines 'read only' permissions                 */
+#else
+  #define   __I     volatile const       /*!< Defines 'read only' permissions                 */
+#endif
+#define     __O     volatile             /*!< Defines 'write only' permissions                */
+#define     __IO    volatile             /*!< Defines 'read / write' permissions              */
+
+/*@} end of group Cortex_M4 */
+
+
+
+/*******************************************************************************
+ *                 Register Abstraction
+  Core Register contain:
+  - Core Register
+  - Core NVIC Register
+  - Core SCB Register
+  - Core SysTick Register
+  - Core Debug Register
+  - Core MPU Register
+  - Core FPU Register
+ ******************************************************************************/
+/** \defgroup CMSIS_core_register Defines and Type Definitions
+    \brief Type definitions and defines for Cortex-M processor based devices.
+*/
+
+/** \ingroup    CMSIS_core_register
+    \defgroup   CMSIS_CORE  Status and Control Registers
+    \brief  Core Register type definitions.
+  @{
+ */
+
+/** \brief  Union type to access the Application Program Status Register (APSR).
+ */
+typedef union
+{
+  struct
+  {
+#if (__CORTEX_M != 0x04)
+    uint32_t _reserved0:27;              /*!< bit:  0..26  Reserved                           */
+#else
+    uint32_t _reserved0:16;              /*!< bit:  0..15  Reserved                           */
+    uint32_t GE:4;                       /*!< bit: 16..19  Greater than or Equal flags        */
+    uint32_t _reserved1:7;               /*!< bit: 20..26  Reserved                           */
+#endif
+    uint32_t Q:1;                        /*!< bit:     27  Saturation condition flag          */
+    uint32_t V:1;                        /*!< bit:     28  Overflow condition code flag       */
+    uint32_t C:1;                        /*!< bit:     29  Carry condition code flag          */
+    uint32_t Z:1;                        /*!< bit:     30  Zero condition code flag           */
+    uint32_t N:1;                        /*!< bit:     31  Negative condition code flag       */
+  } b;                                   /*!< Structure used for bit  access                  */
+  uint32_t w;                            /*!< Type      used for word access                  */
+} APSR_Type;
+
+
+/** \brief  Union type to access the Interrupt Program Status Register (IPSR).
+ */
+typedef union
+{
+  struct
+  {
+    uint32_t ISR:9;                      /*!< bit:  0.. 8  Exception number                   */
+    uint32_t _reserved0:23;              /*!< bit:  9..31  Reserved                           */
+  } b;                                   /*!< Structure used for bit  access                  */
+  uint32_t w;                            /*!< Type      used for word access                  */
+} IPSR_Type;
+
+
+/** \brief  Union type to access the Special-Purpose Program Status Registers (xPSR).
+ */
+typedef union
+{
+  struct
+  {
+    uint32_t ISR:9;                      /*!< bit:  0.. 8  Exception number                   */
+#if (__CORTEX_M != 0x04)
+    uint32_t _reserved0:15;              /*!< bit:  9..23  Reserved                           */
+#else
+    uint32_t _reserved0:7;               /*!< bit:  9..15  Reserved                           */
+    uint32_t GE:4;                       /*!< bit: 16..19  Greater than or Equal flags        */
+    uint32_t _reserved1:4;               /*!< bit: 20..23  Reserved                           */
+#endif
+    uint32_t T:1;                        /*!< bit:     24  Thumb bit        (read 0)          */
+    uint32_t IT:2;                       /*!< bit: 25..26  saved IT state   (read 0)          */
+    uint32_t Q:1;                        /*!< bit:     27  Saturation condition flag          */
+    uint32_t V:1;                        /*!< bit:     28  Overflow condition code flag       */
+    uint32_t C:1;                        /*!< bit:     29  Carry condition code flag          */
+    uint32_t Z:1;                        /*!< bit:     30  Zero condition code flag           */
+    uint32_t N:1;                        /*!< bit:     31  Negative condition code flag       */
+  } b;                                   /*!< Structure used for bit  access                  */
+  uint32_t w;                            /*!< Type      used for word access                  */
+} xPSR_Type;
+
+
+/** \brief  Union type to access the Control Registers (CONTROL).
+ */
+typedef union
+{
+  struct
+  {
+    uint32_t nPRIV:1;                    /*!< bit:      0  Execution privilege in Thread mode */
+    uint32_t SPSEL:1;                    /*!< bit:      1  Stack to be used                   */
+    uint32_t FPCA:1;                     /*!< bit:      2  FP extension active flag           */
+    uint32_t _reserved0:29;              /*!< bit:  3..31  Reserved                           */
+  } b;                                   /*!< Structure used for bit  access                  */
+  uint32_t w;                            /*!< Type      used for word access                  */
+} CONTROL_Type;
+
+/*@} end of group CMSIS_CORE */
+
+
+/** \ingroup    CMSIS_core_register
+    \defgroup   CMSIS_NVIC  Nested Vectored Interrupt Controller (NVIC)
+    \brief      Type definitions for the NVIC Registers
+  @{
+ */
+
+/** \brief  Structure type to access the Nested Vectored Interrupt Controller (NVIC).
+ */
+typedef struct
+{
+  __IO uint32_t ISER[8];                 /*!< Offset: 0x000 (R/W)  Interrupt Set Enable Register           */
+       uint32_t RESERVED0[24];
+  __IO uint32_t ICER[8];                 /*!< Offset: 0x080 (R/W)  Interrupt Clear Enable Register         */
+       uint32_t RSERVED1[24];
+  __IO uint32_t ISPR[8];                 /*!< Offset: 0x100 (R/W)  Interrupt Set Pending Register          */
+       uint32_t RESERVED2[24];
+  __IO uint32_t ICPR[8];                 /*!< Offset: 0x180 (R/W)  Interrupt Clear Pending Register        */
+       uint32_t RESERVED3[24];
+  __IO uint32_t IABR[8];                 /*!< Offset: 0x200 (R/W)  Interrupt Active bit Register           */
+       uint32_t RESERVED4[56];
+  __IO uint8_t  IP[240];                 /*!< Offset: 0x300 (R/W)  Interrupt Priority Register (8Bit wide) */
+       uint32_t RESERVED5[644];
+  __O  uint32_t STIR;                    /*!< Offset: 0xE00 ( /W)  Software Trigger Interrupt Register     */
+}  NVIC_Type;
+
+/* Software Triggered Interrupt Register Definitions */
+#define NVIC_STIR_INTID_Pos                 0                                          /*!< STIR: INTLINESNUM Position */
+#define NVIC_STIR_INTID_Msk                (0x1FFUL << NVIC_STIR_INTID_Pos)            /*!< STIR: INTLINESNUM Mask */
+
+/*@} end of group CMSIS_NVIC */
+
+
+/** \ingroup  CMSIS_core_register
+    \defgroup CMSIS_SCB     System Control Block (SCB)
+    \brief      Type definitions for the System Control Block Registers
+  @{
+ */
+
+/** \brief  Structure type to access the System Control Block (SCB).
+ */
+typedef struct
+{
+  __I  uint32_t CPUID;                   /*!< Offset: 0x000 (R/ )  CPUID Base Register                                   */
+  __IO uint32_t ICSR;                    /*!< Offset: 0x004 (R/W)  Interrupt Control and State Register                  */
+  __IO uint32_t VTOR;                    /*!< Offset: 0x008 (R/W)  Vector Table Offset Register                          */
+  __IO uint32_t AIRCR;                   /*!< Offset: 0x00C (R/W)  Application Interrupt and Reset Control Register      */
+  __IO uint32_t SCR;                     /*!< Offset: 0x010 (R/W)  System Control Register                               */
+  __IO uint32_t CCR;                     /*!< Offset: 0x014 (R/W)  Configuration Control Register                        */
+  __IO uint8_t  SHP[12];                 /*!< Offset: 0x018 (R/W)  System Handlers Priority Registers (4-7, 8-11, 12-15) */
+  __IO uint32_t SHCSR;                   /*!< Offset: 0x024 (R/W)  System Handler Control and State Register             */
+  __IO uint32_t CFSR;                    /*!< Offset: 0x028 (R/W)  Configurable Fault Status Register                    */
+  __IO uint32_t HFSR;                    /*!< Offset: 0x02C (R/W)  HardFault Status Register                             */
+  __IO uint32_t DFSR;                    /*!< Offset: 0x030 (R/W)  Debug Fault Status Register                           */
+  __IO uint32_t MMFAR;                   /*!< Offset: 0x034 (R/W)  MemManage Fault Address Register                      */
+  __IO uint32_t BFAR;                    /*!< Offset: 0x038 (R/W)  BusFault Address Register                             */
+  __IO uint32_t AFSR;                    /*!< Offset: 0x03C (R/W)  Auxiliary Fault Status Register                       */
+  __I  uint32_t PFR[2];                  /*!< Offset: 0x040 (R/ )  Processor Feature Register                            */
+  __I  uint32_t DFR;                     /*!< Offset: 0x048 (R/ )  Debug Feature Register                                */
+  __I  uint32_t ADR;                     /*!< Offset: 0x04C (R/ )  Auxiliary Feature Register                            */
+  __I  uint32_t MMFR[4];                 /*!< Offset: 0x050 (R/ )  Memory Model Feature Register                         */
+  __I  uint32_t ISAR[5];                 /*!< Offset: 0x060 (R/ )  Instruction Set Attributes Register                   */
+       uint32_t RESERVED0[5];
+  __IO uint32_t CPACR;                   /*!< Offset: 0x088 (R/W)  Coprocessor Access Control Register                   */
+} SCB_Type;
+
+/* SCB CPUID Register Definitions */
+#define SCB_CPUID_IMPLEMENTER_Pos          24                                             /*!< SCB CPUID: IMPLEMENTER Position */
+#define SCB_CPUID_IMPLEMENTER_Msk          (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos)          /*!< SCB CPUID: IMPLEMENTER Mask */
+
+#define SCB_CPUID_VARIANT_Pos              20                                             /*!< SCB CPUID: VARIANT Position */
+#define SCB_CPUID_VARIANT_Msk              (0xFUL << SCB_CPUID_VARIANT_Pos)               /*!< SCB CPUID: VARIANT Mask */
+
+#define SCB_CPUID_ARCHITECTURE_Pos         16                                             /*!< SCB CPUID: ARCHITECTURE Position */
+#define SCB_CPUID_ARCHITECTURE_Msk         (0xFUL << SCB_CPUID_ARCHITECTURE_Pos)          /*!< SCB CPUID: ARCHITECTURE Mask */
+
+#define SCB_CPUID_PARTNO_Pos                4                                             /*!< SCB CPUID: PARTNO Position */
+#define SCB_CPUID_PARTNO_Msk               (0xFFFUL << SCB_CPUID_PARTNO_Pos)              /*!< SCB CPUID: PARTNO Mask */
+
+#define SCB_CPUID_REVISION_Pos              0                                             /*!< SCB CPUID: REVISION Position */
+#define SCB_CPUID_REVISION_Msk             (0xFUL << SCB_CPUID_REVISION_Pos)              /*!< SCB CPUID: REVISION Mask */
+
+/* SCB Interrupt Control State Register Definitions */
+#define SCB_ICSR_NMIPENDSET_Pos            31                                             /*!< SCB ICSR: NMIPENDSET Position */
+#define SCB_ICSR_NMIPENDSET_Msk            (1UL << SCB_ICSR_NMIPENDSET_Pos)               /*!< SCB ICSR: NMIPENDSET Mask */
+
+#define SCB_ICSR_PENDSVSET_Pos             28                                             /*!< SCB ICSR: PENDSVSET Position */
+#define SCB_ICSR_PENDSVSET_Msk             (1UL << SCB_ICSR_PENDSVSET_Pos)                /*!< SCB ICSR: PENDSVSET Mask */
+
+#define SCB_ICSR_PENDSVCLR_Pos             27                                             /*!< SCB ICSR: PENDSVCLR Position */
+#define SCB_ICSR_PENDSVCLR_Msk             (1UL << SCB_ICSR_PENDSVCLR_Pos)                /*!< SCB ICSR: PENDSVCLR Mask */
+
+#define SCB_ICSR_PENDSTSET_Pos             26                                             /*!< SCB ICSR: PENDSTSET Position */
+#define SCB_ICSR_PENDSTSET_Msk             (1UL << SCB_ICSR_PENDSTSET_Pos)                /*!< SCB ICSR: PENDSTSET Mask */
+
+#define SCB_ICSR_PENDSTCLR_Pos             25                                             /*!< SCB ICSR: PENDSTCLR Position */
+#define SCB_ICSR_PENDSTCLR_Msk             (1UL << SCB_ICSR_PENDSTCLR_Pos)                /*!< SCB ICSR: PENDSTCLR Mask */
+
+#define SCB_ICSR_ISRPREEMPT_Pos            23                                             /*!< SCB ICSR: ISRPREEMPT Position */
+#define SCB_ICSR_ISRPREEMPT_Msk            (1UL << SCB_ICSR_ISRPREEMPT_Pos)               /*!< SCB ICSR: ISRPREEMPT Mask */
+
+#define SCB_ICSR_ISRPENDING_Pos            22                                             /*!< SCB ICSR: ISRPENDING Position */
+#define SCB_ICSR_ISRPENDING_Msk            (1UL << SCB_ICSR_ISRPENDING_Pos)               /*!< SCB ICSR: ISRPENDING Mask */
+
+#define SCB_ICSR_VECTPENDING_Pos           12                                             /*!< SCB ICSR: VECTPENDING Position */
+#define SCB_ICSR_VECTPENDING_Msk           (0x1FFUL << SCB_ICSR_VECTPENDING_Pos)          /*!< SCB ICSR: VECTPENDING Mask */
+
+#define SCB_ICSR_RETTOBASE_Pos             11                                             /*!< SCB ICSR: RETTOBASE Position */
+#define SCB_ICSR_RETTOBASE_Msk             (1UL << SCB_ICSR_RETTOBASE_Pos)                /*!< SCB ICSR: RETTOBASE Mask */
+
+#define SCB_ICSR_VECTACTIVE_Pos             0                                             /*!< SCB ICSR: VECTACTIVE Position */
+#define SCB_ICSR_VECTACTIVE_Msk            (0x1FFUL << SCB_ICSR_VECTACTIVE_Pos)           /*!< SCB ICSR: VECTACTIVE Mask */
+
+/* SCB Vector Table Offset Register Definitions */
+#define SCB_VTOR_TBLOFF_Pos                 7                                             /*!< SCB VTOR: TBLOFF Position */
+#define SCB_VTOR_TBLOFF_Msk                (0x1FFFFFFUL << SCB_VTOR_TBLOFF_Pos)           /*!< SCB VTOR: TBLOFF Mask */
+
+/* SCB Application Interrupt and Reset Control Register Definitions */
+#define SCB_AIRCR_VECTKEY_Pos              16                                             /*!< SCB AIRCR: VECTKEY Position */
+#define SCB_AIRCR_VECTKEY_Msk              (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos)            /*!< SCB AIRCR: VECTKEY Mask */
+
+#define SCB_AIRCR_VECTKEYSTAT_Pos          16                                             /*!< SCB AIRCR: VECTKEYSTAT Position */
+#define SCB_AIRCR_VECTKEYSTAT_Msk          (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos)        /*!< SCB AIRCR: VECTKEYSTAT Mask */
+
+#define SCB_AIRCR_ENDIANESS_Pos            15                                             /*!< SCB AIRCR: ENDIANESS Position */
+#define SCB_AIRCR_ENDIANESS_Msk            (1UL << SCB_AIRCR_ENDIANESS_Pos)               /*!< SCB AIRCR: ENDIANESS Mask */
+
+#define SCB_AIRCR_PRIGROUP_Pos              8                                             /*!< SCB AIRCR: PRIGROUP Position */
+#define SCB_AIRCR_PRIGROUP_Msk             (7UL << SCB_AIRCR_PRIGROUP_Pos)                /*!< SCB AIRCR: PRIGROUP Mask */
+
+#define SCB_AIRCR_SYSRESETREQ_Pos           2                                             /*!< SCB AIRCR: SYSRESETREQ Position */
+#define SCB_AIRCR_SYSRESETREQ_Msk          (1UL << SCB_AIRCR_SYSRESETREQ_Pos)             /*!< SCB AIRCR: SYSRESETREQ Mask */
+
+#define SCB_AIRCR_VECTCLRACTIVE_Pos         1                                             /*!< SCB AIRCR: VECTCLRACTIVE Position */
+#define SCB_AIRCR_VECTCLRACTIVE_Msk        (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos)           /*!< SCB AIRCR: VECTCLRACTIVE Mask */
+
+#define SCB_AIRCR_VECTRESET_Pos             0                                             /*!< SCB AIRCR: VECTRESET Position */
+#define SCB_AIRCR_VECTRESET_Msk            (1UL << SCB_AIRCR_VECTRESET_Pos)               /*!< SCB AIRCR: VECTRESET Mask */
+
+/* SCB System Control Register Definitions */
+#define SCB_SCR_SEVONPEND_Pos               4                                             /*!< SCB SCR: SEVONPEND Position */
+#define SCB_SCR_SEVONPEND_Msk              (1UL << SCB_SCR_SEVONPEND_Pos)                 /*!< SCB SCR: SEVONPEND Mask */
+
+#define SCB_SCR_SLEEPDEEP_Pos               2                                             /*!< SCB SCR: SLEEPDEEP Position */
+#define SCB_SCR_SLEEPDEEP_Msk              (1UL << SCB_SCR_SLEEPDEEP_Pos)                 /*!< SCB SCR: SLEEPDEEP Mask */
+
+#define SCB_SCR_SLEEPONEXIT_Pos             1                                             /*!< SCB SCR: SLEEPONEXIT Position */
+#define SCB_SCR_SLEEPONEXIT_Msk            (1UL << SCB_SCR_SLEEPONEXIT_Pos)               /*!< SCB SCR: SLEEPONEXIT Mask */
+
+/* SCB Configuration Control Register Definitions */
+#define SCB_CCR_STKALIGN_Pos                9                                             /*!< SCB CCR: STKALIGN Position */
+#define SCB_CCR_STKALIGN_Msk               (1UL << SCB_CCR_STKALIGN_Pos)                  /*!< SCB CCR: STKALIGN Mask */
+
+#define SCB_CCR_BFHFNMIGN_Pos               8                                             /*!< SCB CCR: BFHFNMIGN Position */
+#define SCB_CCR_BFHFNMIGN_Msk              (1UL << SCB_CCR_BFHFNMIGN_Pos)                 /*!< SCB CCR: BFHFNMIGN Mask */
+
+#define SCB_CCR_DIV_0_TRP_Pos               4                                             /*!< SCB CCR: DIV_0_TRP Position */
+#define SCB_CCR_DIV_0_TRP_Msk              (1UL << SCB_CCR_DIV_0_TRP_Pos)                 /*!< SCB CCR: DIV_0_TRP Mask */
+
+#define SCB_CCR_UNALIGN_TRP_Pos             3                                             /*!< SCB CCR: UNALIGN_TRP Position */
+#define SCB_CCR_UNALIGN_TRP_Msk            (1UL << SCB_CCR_UNALIGN_TRP_Pos)               /*!< SCB CCR: UNALIGN_TRP Mask */
+
+#define SCB_CCR_USERSETMPEND_Pos            1                                             /*!< SCB CCR: USERSETMPEND Position */
+#define SCB_CCR_USERSETMPEND_Msk           (1UL << SCB_CCR_USERSETMPEND_Pos)              /*!< SCB CCR: USERSETMPEND Mask */
+
+#define SCB_CCR_NONBASETHRDENA_Pos          0                                             /*!< SCB CCR: NONBASETHRDENA Position */
+#define SCB_CCR_NONBASETHRDENA_Msk         (1UL << SCB_CCR_NONBASETHRDENA_Pos)            /*!< SCB CCR: NONBASETHRDENA Mask */
+
+/* SCB System Handler Control and State Register Definitions */
+#define SCB_SHCSR_USGFAULTENA_Pos          18                                             /*!< SCB SHCSR: USGFAULTENA Position */
+#define SCB_SHCSR_USGFAULTENA_Msk          (1UL << SCB_SHCSR_USGFAULTENA_Pos)             /*!< SCB SHCSR: USGFAULTENA Mask */
+
+#define SCB_SHCSR_BUSFAULTENA_Pos          17                                             /*!< SCB SHCSR: BUSFAULTENA Position */
+#define SCB_SHCSR_BUSFAULTENA_Msk          (1UL << SCB_SHCSR_BUSFAULTENA_Pos)             /*!< SCB SHCSR: BUSFAULTENA Mask */
+
+#define SCB_SHCSR_MEMFAULTENA_Pos          16                                             /*!< SCB SHCSR: MEMFAULTENA Position */
+#define SCB_SHCSR_MEMFAULTENA_Msk          (1UL << SCB_SHCSR_MEMFAULTENA_Pos)             /*!< SCB SHCSR: MEMFAULTENA Mask */
+
+#define SCB_SHCSR_SVCALLPENDED_Pos         15                                             /*!< SCB SHCSR: SVCALLPENDED Position */
+#define SCB_SHCSR_SVCALLPENDED_Msk         (1UL << SCB_SHCSR_SVCALLPENDED_Pos)            /*!< SCB SHCSR: SVCALLPENDED Mask */
+
+#define SCB_SHCSR_BUSFAULTPENDED_Pos       14                                             /*!< SCB SHCSR: BUSFAULTPENDED Position */
+#define SCB_SHCSR_BUSFAULTPENDED_Msk       (1UL << SCB_SHCSR_BUSFAULTPENDED_Pos)          /*!< SCB SHCSR: BUSFAULTPENDED Mask */
+
+#define SCB_SHCSR_MEMFAULTPENDED_Pos       13                                             /*!< SCB SHCSR: MEMFAULTPENDED Position */
+#define SCB_SHCSR_MEMFAULTPENDED_Msk       (1UL << SCB_SHCSR_MEMFAULTPENDED_Pos)          /*!< SCB SHCSR: MEMFAULTPENDED Mask */
+
+#define SCB_SHCSR_USGFAULTPENDED_Pos       12                                             /*!< SCB SHCSR: USGFAULTPENDED Position */
+#define SCB_SHCSR_USGFAULTPENDED_Msk       (1UL << SCB_SHCSR_USGFAULTPENDED_Pos)          /*!< SCB SHCSR: USGFAULTPENDED Mask */
+
+#define SCB_SHCSR_SYSTICKACT_Pos           11                                             /*!< SCB SHCSR: SYSTICKACT Position */
+#define SCB_SHCSR_SYSTICKACT_Msk           (1UL << SCB_SHCSR_SYSTICKACT_Pos)              /*!< SCB SHCSR: SYSTICKACT Mask */
+
+#define SCB_SHCSR_PENDSVACT_Pos            10                                             /*!< SCB SHCSR: PENDSVACT Position */
+#define SCB_SHCSR_PENDSVACT_Msk            (1UL << SCB_SHCSR_PENDSVACT_Pos)               /*!< SCB SHCSR: PENDSVACT Mask */
+
+#define SCB_SHCSR_MONITORACT_Pos            8                                             /*!< SCB SHCSR: MONITORACT Position */
+#define SCB_SHCSR_MONITORACT_Msk           (1UL << SCB_SHCSR_MONITORACT_Pos)              /*!< SCB SHCSR: MONITORACT Mask */
+
+#define SCB_SHCSR_SVCALLACT_Pos             7                                             /*!< SCB SHCSR: SVCALLACT Position */
+#define SCB_SHCSR_SVCALLACT_Msk            (1UL << SCB_SHCSR_SVCALLACT_Pos)               /*!< SCB SHCSR: SVCALLACT Mask */
+
+#define SCB_SHCSR_USGFAULTACT_Pos           3                                             /*!< SCB SHCSR: USGFAULTACT Position */
+#define SCB_SHCSR_USGFAULTACT_Msk          (1UL << SCB_SHCSR_USGFAULTACT_Pos)             /*!< SCB SHCSR: USGFAULTACT Mask */
+
+#define SCB_SHCSR_BUSFAULTACT_Pos           1                                             /*!< SCB SHCSR: BUSFAULTACT Position */
+#define SCB_SHCSR_BUSFAULTACT_Msk          (1UL << SCB_SHCSR_BUSFAULTACT_Pos)             /*!< SCB SHCSR: BUSFAULTACT Mask */
+
+#define SCB_SHCSR_MEMFAULTACT_Pos           0                                             /*!< SCB SHCSR: MEMFAULTACT Position */
+#define SCB_SHCSR_MEMFAULTACT_Msk          (1UL << SCB_SHCSR_MEMFAULTACT_Pos)             /*!< SCB SHCSR: MEMFAULTACT Mask */
+
+/* SCB Configurable Fault Status Registers Definitions */
+#define SCB_CFSR_USGFAULTSR_Pos            16                                             /*!< SCB CFSR: Usage Fault Status Register Position */
+#define SCB_CFSR_USGFAULTSR_Msk            (0xFFFFUL << SCB_CFSR_USGFAULTSR_Pos)          /*!< SCB CFSR: Usage Fault Status Register Mask */
+
+#define SCB_CFSR_BUSFAULTSR_Pos             8                                             /*!< SCB CFSR: Bus Fault Status Register Position */
+#define SCB_CFSR_BUSFAULTSR_Msk            (0xFFUL << SCB_CFSR_BUSFAULTSR_Pos)            /*!< SCB CFSR: Bus Fault Status Register Mask */
+
+#define SCB_CFSR_MEMFAULTSR_Pos             0                                             /*!< SCB CFSR: Memory Manage Fault Status Register Position */
+#define SCB_CFSR_MEMFAULTSR_Msk            (0xFFUL << SCB_CFSR_MEMFAULTSR_Pos)            /*!< SCB CFSR: Memory Manage Fault Status Register Mask */
+
+/* SCB Hard Fault Status Registers Definitions */
+#define SCB_HFSR_DEBUGEVT_Pos              31                                             /*!< SCB HFSR: DEBUGEVT Position */
+#define SCB_HFSR_DEBUGEVT_Msk              (1UL << SCB_HFSR_DEBUGEVT_Pos)                 /*!< SCB HFSR: DEBUGEVT Mask */
+
+#define SCB_HFSR_FORCED_Pos                30                                             /*!< SCB HFSR: FORCED Position */
+#define SCB_HFSR_FORCED_Msk                (1UL << SCB_HFSR_FORCED_Pos)                   /*!< SCB HFSR: FORCED Mask */
+
+#define SCB_HFSR_VECTTBL_Pos                1                                             /*!< SCB HFSR: VECTTBL Position */
+#define SCB_HFSR_VECTTBL_Msk               (1UL << SCB_HFSR_VECTTBL_Pos)                  /*!< SCB HFSR: VECTTBL Mask */
+
+/* SCB Debug Fault Status Register Definitions */
+#define SCB_DFSR_EXTERNAL_Pos               4                                             /*!< SCB DFSR: EXTERNAL Position */
+#define SCB_DFSR_EXTERNAL_Msk              (1UL << SCB_DFSR_EXTERNAL_Pos)                 /*!< SCB DFSR: EXTERNAL Mask */
+
+#define SCB_DFSR_VCATCH_Pos                 3                                             /*!< SCB DFSR: VCATCH Position */
+#define SCB_DFSR_VCATCH_Msk                (1UL << SCB_DFSR_VCATCH_Pos)                   /*!< SCB DFSR: VCATCH Mask */
+
+#define SCB_DFSR_DWTTRAP_Pos                2                                             /*!< SCB DFSR: DWTTRAP Position */
+#define SCB_DFSR_DWTTRAP_Msk               (1UL << SCB_DFSR_DWTTRAP_Pos)                  /*!< SCB DFSR: DWTTRAP Mask */
+
+#define SCB_DFSR_BKPT_Pos                   1                                             /*!< SCB DFSR: BKPT Position */
+#define SCB_DFSR_BKPT_Msk                  (1UL << SCB_DFSR_BKPT_Pos)                     /*!< SCB DFSR: BKPT Mask */
+
+#define SCB_DFSR_HALTED_Pos                 0                                             /*!< SCB DFSR: HALTED Position */
+#define SCB_DFSR_HALTED_Msk                (1UL << SCB_DFSR_HALTED_Pos)                   /*!< SCB DFSR: HALTED Mask */
+
+/*@} end of group CMSIS_SCB */
+
+
+/** \ingroup  CMSIS_core_register
+    \defgroup CMSIS_SCnSCB System Controls not in SCB (SCnSCB)
+    \brief      Type definitions for the System Control and ID Register not in the SCB
+  @{
+ */
+
+/** \brief  Structure type to access the System Control and ID Register not in the SCB.
+ */
+typedef struct
+{
+       uint32_t RESERVED0[1];
+  __I  uint32_t ICTR;                    /*!< Offset: 0x004 (R/ )  Interrupt Controller Type Register      */
+  __IO uint32_t ACTLR;                   /*!< Offset: 0x008 (R/W)  Auxiliary Control Register              */
+} SCnSCB_Type;
+
+/* Interrupt Controller Type Register Definitions */
+#define SCnSCB_ICTR_INTLINESNUM_Pos         0                                          /*!< ICTR: INTLINESNUM Position */
+#define SCnSCB_ICTR_INTLINESNUM_Msk        (0xFUL << SCnSCB_ICTR_INTLINESNUM_Pos)      /*!< ICTR: INTLINESNUM Mask */
+
+/* Auxiliary Control Register Definitions */
+#define SCnSCB_ACTLR_DISOOFP_Pos            9                                          /*!< ACTLR: DISOOFP Position */
+#define SCnSCB_ACTLR_DISOOFP_Msk           (1UL << SCnSCB_ACTLR_DISOOFP_Pos)           /*!< ACTLR: DISOOFP Mask */
+
+#define SCnSCB_ACTLR_DISFPCA_Pos            8                                          /*!< ACTLR: DISFPCA Position */
+#define SCnSCB_ACTLR_DISFPCA_Msk           (1UL << SCnSCB_ACTLR_DISFPCA_Pos)           /*!< ACTLR: DISFPCA Mask */
+
+#define SCnSCB_ACTLR_DISFOLD_Pos            2                                          /*!< ACTLR: DISFOLD Position */
+#define SCnSCB_ACTLR_DISFOLD_Msk           (1UL << SCnSCB_ACTLR_DISFOLD_Pos)           /*!< ACTLR: DISFOLD Mask */
+
+#define SCnSCB_ACTLR_DISDEFWBUF_Pos         1                                          /*!< ACTLR: DISDEFWBUF Position */
+#define SCnSCB_ACTLR_DISDEFWBUF_Msk        (1UL << SCnSCB_ACTLR_DISDEFWBUF_Pos)        /*!< ACTLR: DISDEFWBUF Mask */
+
+#define SCnSCB_ACTLR_DISMCYCINT_Pos         0                                          /*!< ACTLR: DISMCYCINT Position */
+#define SCnSCB_ACTLR_DISMCYCINT_Msk        (1UL << SCnSCB_ACTLR_DISMCYCINT_Pos)        /*!< ACTLR: DISMCYCINT Mask */
+
+/*@} end of group CMSIS_SCnotSCB */
+
+
+/** \ingroup  CMSIS_core_register
+    \defgroup CMSIS_SysTick     System Tick Timer (SysTick)
+    \brief      Type definitions for the System Timer Registers.
+  @{
+ */
+
+/** \brief  Structure type to access the System Timer (SysTick).
+ */
+typedef struct
+{
+  __IO uint32_t CTRL;                    /*!< Offset: 0x000 (R/W)  SysTick Control and Status Register */
+  __IO uint32_t LOAD;                    /*!< Offset: 0x004 (R/W)  SysTick Reload Value Register       */
+  __IO uint32_t VAL;                     /*!< Offset: 0x008 (R/W)  SysTick Current Value Register      */
+  __I  uint32_t CALIB;                   /*!< Offset: 0x00C (R/ )  SysTick Calibration Register        */
+} SysTick_Type;
+
+/* SysTick Control / Status Register Definitions */
+#define SysTick_CTRL_COUNTFLAG_Pos         16                                             /*!< SysTick CTRL: COUNTFLAG Position */
+#define SysTick_CTRL_COUNTFLAG_Msk         (1UL << SysTick_CTRL_COUNTFLAG_Pos)            /*!< SysTick CTRL: COUNTFLAG Mask */
+
+#define SysTick_CTRL_CLKSOURCE_Pos          2                                             /*!< SysTick CTRL: CLKSOURCE Position */
+#define SysTick_CTRL_CLKSOURCE_Msk         (1UL << SysTick_CTRL_CLKSOURCE_Pos)            /*!< SysTick CTRL: CLKSOURCE Mask */
+
+#define SysTick_CTRL_TICKINT_Pos            1                                             /*!< SysTick CTRL: TICKINT Position */
+#define SysTick_CTRL_TICKINT_Msk           (1UL << SysTick_CTRL_TICKINT_Pos)              /*!< SysTick CTRL: TICKINT Mask */
+
+#define SysTick_CTRL_ENABLE_Pos             0                                             /*!< SysTick CTRL: ENABLE Position */
+#define SysTick_CTRL_ENABLE_Msk            (1UL << SysTick_CTRL_ENABLE_Pos)               /*!< SysTick CTRL: ENABLE Mask */
+
+/* SysTick Reload Register Definitions */
+#define SysTick_LOAD_RELOAD_Pos             0                                             /*!< SysTick LOAD: RELOAD Position */
+#define SysTick_LOAD_RELOAD_Msk            (0xFFFFFFUL << SysTick_LOAD_RELOAD_Pos)        /*!< SysTick LOAD: RELOAD Mask */
+
+/* SysTick Current Register Definitions */
+#define SysTick_VAL_CURRENT_Pos             0                                             /*!< SysTick VAL: CURRENT Position */
+#define SysTick_VAL_CURRENT_Msk            (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos)        /*!< SysTick VAL: CURRENT Mask */
+
+/* SysTick Calibration Register Definitions */
+#define SysTick_CALIB_NOREF_Pos            31                                             /*!< SysTick CALIB: NOREF Position */
+#define SysTick_CALIB_NOREF_Msk            (1UL << SysTick_CALIB_NOREF_Pos)               /*!< SysTick CALIB: NOREF Mask */
+
+#define SysTick_CALIB_SKEW_Pos             30                                             /*!< SysTick CALIB: SKEW Position */
+#define SysTick_CALIB_SKEW_Msk             (1UL << SysTick_CALIB_SKEW_Pos)                /*!< SysTick CALIB: SKEW Mask */
+
+#define SysTick_CALIB_TENMS_Pos             0                                             /*!< SysTick CALIB: TENMS Position */
+#define SysTick_CALIB_TENMS_Msk            (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos)        /*!< SysTick CALIB: TENMS Mask */
+
+/*@} end of group CMSIS_SysTick */
+
+
+/** \ingroup  CMSIS_core_register
+    \defgroup CMSIS_ITM     Instrumentation Trace Macrocell (ITM)
+    \brief      Type definitions for the Instrumentation Trace Macrocell (ITM)
+  @{
+ */
+
+/** \brief  Structure type to access the Instrumentation Trace Macrocell Register (ITM).
+ */
+typedef struct
+{
+  __O  union
+  {
+    __O  uint8_t    u8;                  /*!< Offset: 0x000 ( /W)  ITM Stimulus Port 8-bit                   */
+    __O  uint16_t   u16;                 /*!< Offset: 0x000 ( /W)  ITM Stimulus Port 16-bit                  */
+    __O  uint32_t   u32;                 /*!< Offset: 0x000 ( /W)  ITM Stimulus Port 32-bit                  */
+  }  PORT [32];                          /*!< Offset: 0x000 ( /W)  ITM Stimulus Port Registers               */
+       uint32_t RESERVED0[864];
+  __IO uint32_t TER;                     /*!< Offset: 0xE00 (R/W)  ITM Trace Enable Register                 */
+       uint32_t RESERVED1[15];
+  __IO uint32_t TPR;                     /*!< Offset: 0xE40 (R/W)  ITM Trace Privilege Register              */
+       uint32_t RESERVED2[15];
+  __IO uint32_t TCR;                     /*!< Offset: 0xE80 (R/W)  ITM Trace Control Register                */
+       uint32_t RESERVED3[29];
+  __O  uint32_t IWR;                     /*!< Offset: 0xEF8 ( /W)  ITM Integration Write Register            */
+  __I  uint32_t IRR;                     /*!< Offset: 0xEFC (R/ )  ITM Integration Read Register             */
+  __IO uint32_t IMCR;                    /*!< Offset: 0xF00 (R/W)  ITM Integration Mode Control Register     */
+       uint32_t RESERVED4[43];
+  __O  uint32_t LAR;                     /*!< Offset: 0xFB0 ( /W)  ITM Lock Access Register                  */
+  __I  uint32_t LSR;                     /*!< Offset: 0xFB4 (R/ )  ITM Lock Status Register                  */
+       uint32_t RESERVED5[6];
+  __I  uint32_t PID4;                    /*!< Offset: 0xFD0 (R/ )  ITM Peripheral Identification Register #4 */
+  __I  uint32_t PID5;                    /*!< Offset: 0xFD4 (R/ )  ITM Peripheral Identification Register #5 */
+  __I  uint32_t PID6;                    /*!< Offset: 0xFD8 (R/ )  ITM Peripheral Identification Register #6 */
+  __I  uint32_t PID7;                    /*!< Offset: 0xFDC (R/ )  ITM Peripheral Identification Register #7 */
+  __I  uint32_t PID0;                    /*!< Offset: 0xFE0 (R/ )  ITM Peripheral Identification Register #0 */
+  __I  uint32_t PID1;                    /*!< Offset: 0xFE4 (R/ )  ITM Peripheral Identification Register #1 */
+  __I  uint32_t PID2;                    /*!< Offset: 0xFE8 (R/ )  ITM Peripheral Identification Register #2 */
+  __I  uint32_t PID3;                    /*!< Offset: 0xFEC (R/ )  ITM Peripheral Identification Register #3 */
+  __I  uint32_t CID0;                    /*!< Offset: 0xFF0 (R/ )  ITM Component  Identification Register #0 */
+  __I  uint32_t CID1;                    /*!< Offset: 0xFF4 (R/ )  ITM Component  Identification Register #1 */
+  __I  uint32_t CID2;                    /*!< Offset: 0xFF8 (R/ )  ITM Component  Identification Register #2 */
+  __I  uint32_t CID3;                    /*!< Offset: 0xFFC (R/ )  ITM Component  Identification Register #3 */
+} ITM_Type;
+
+/* ITM Trace Privilege Register Definitions */
+#define ITM_TPR_PRIVMASK_Pos                0                                             /*!< ITM TPR: PRIVMASK Position */
+#define ITM_TPR_PRIVMASK_Msk               (0xFUL << ITM_TPR_PRIVMASK_Pos)                /*!< ITM TPR: PRIVMASK Mask */
+
+/* ITM Trace Control Register Definitions */
+#define ITM_TCR_BUSY_Pos                   23                                             /*!< ITM TCR: BUSY Position */
+#define ITM_TCR_BUSY_Msk                   (1UL << ITM_TCR_BUSY_Pos)                      /*!< ITM TCR: BUSY Mask */
+
+#define ITM_TCR_TraceBusID_Pos             16                                             /*!< ITM TCR: ATBID Position */
+#define ITM_TCR_TraceBusID_Msk             (0x7FUL << ITM_TCR_TraceBusID_Pos)             /*!< ITM TCR: ATBID Mask */
+
+#define ITM_TCR_GTSFREQ_Pos                10                                             /*!< ITM TCR: Global timestamp frequency Position */
+#define ITM_TCR_GTSFREQ_Msk                (3UL << ITM_TCR_GTSFREQ_Pos)                   /*!< ITM TCR: Global timestamp frequency Mask */
+
+#define ITM_TCR_TSPrescale_Pos              8                                             /*!< ITM TCR: TSPrescale Position */
+#define ITM_TCR_TSPrescale_Msk             (3UL << ITM_TCR_TSPrescale_Pos)                /*!< ITM TCR: TSPrescale Mask */
+
+#define ITM_TCR_SWOENA_Pos                  4                                             /*!< ITM TCR: SWOENA Position */
+#define ITM_TCR_SWOENA_Msk                 (1UL << ITM_TCR_SWOENA_Pos)                    /*!< ITM TCR: SWOENA Mask */
+
+#define ITM_TCR_DWTENA_Pos                  3                                             /*!< ITM TCR: DWTENA Position */
+#define ITM_TCR_DWTENA_Msk                 (1UL << ITM_TCR_DWTENA_Pos)                    /*!< ITM TCR: DWTENA Mask */
+
+#define ITM_TCR_SYNCENA_Pos                 2                                             /*!< ITM TCR: SYNCENA Position */
+#define ITM_TCR_SYNCENA_Msk                (1UL << ITM_TCR_SYNCENA_Pos)                   /*!< ITM TCR: SYNCENA Mask */
+
+#define ITM_TCR_TSENA_Pos                   1                                             /*!< ITM TCR: TSENA Position */
+#define ITM_TCR_TSENA_Msk                  (1UL << ITM_TCR_TSENA_Pos)                     /*!< ITM TCR: TSENA Mask */
+
+#define ITM_TCR_ITMENA_Pos                  0                                             /*!< ITM TCR: ITM Enable bit Position */
+#define ITM_TCR_ITMENA_Msk                 (1UL << ITM_TCR_ITMENA_Pos)                    /*!< ITM TCR: ITM Enable bit Mask */
+
+/* ITM Integration Write Register Definitions */
+#define ITM_IWR_ATVALIDM_Pos                0                                             /*!< ITM IWR: ATVALIDM Position */
+#define ITM_IWR_ATVALIDM_Msk               (1UL << ITM_IWR_ATVALIDM_Pos)                  /*!< ITM IWR: ATVALIDM Mask */
+
+/* ITM Integration Read Register Definitions */
+#define ITM_IRR_ATREADYM_Pos                0                                             /*!< ITM IRR: ATREADYM Position */
+#define ITM_IRR_ATREADYM_Msk               (1UL << ITM_IRR_ATREADYM_Pos)                  /*!< ITM IRR: ATREADYM Mask */
+
+/* ITM Integration Mode Control Register Definitions */
+#define ITM_IMCR_INTEGRATION_Pos            0                                             /*!< ITM IMCR: INTEGRATION Position */
+#define ITM_IMCR_INTEGRATION_Msk           (1UL << ITM_IMCR_INTEGRATION_Pos)              /*!< ITM IMCR: INTEGRATION Mask */
+
+/* ITM Lock Status Register Definitions */
+#define ITM_LSR_ByteAcc_Pos                 2                                             /*!< ITM LSR: ByteAcc Position */
+#define ITM_LSR_ByteAcc_Msk                (1UL << ITM_LSR_ByteAcc_Pos)                   /*!< ITM LSR: ByteAcc Mask */
+
+#define ITM_LSR_Access_Pos                  1                                             /*!< ITM LSR: Access Position */
+#define ITM_LSR_Access_Msk                 (1UL << ITM_LSR_Access_Pos)                    /*!< ITM LSR: Access Mask */
+
+#define ITM_LSR_Present_Pos                 0                                             /*!< ITM LSR: Present Position */
+#define ITM_LSR_Present_Msk                (1UL << ITM_LSR_Present_Pos)                   /*!< ITM LSR: Present Mask */
+
+/*@}*/ /* end of group CMSIS_ITM */
+
+
+/** \ingroup  CMSIS_core_register
+    \defgroup CMSIS_DWT     Data Watchpoint and Trace (DWT)
+    \brief      Type definitions for the Data Watchpoint and Trace (DWT)
+  @{
+ */
+
+/** \brief  Structure type to access the Data Watchpoint and Trace Register (DWT).
+ */
+typedef struct
+{
+  __IO uint32_t CTRL;                    /*!< Offset: 0x000 (R/W)  Control Register                          */
+  __IO uint32_t CYCCNT;                  /*!< Offset: 0x004 (R/W)  Cycle Count Register                      */
+  __IO uint32_t CPICNT;                  /*!< Offset: 0x008 (R/W)  CPI Count Register                        */
+  __IO uint32_t EXCCNT;                  /*!< Offset: 0x00C (R/W)  Exception Overhead Count Register         */
+  __IO uint32_t SLEEPCNT;                /*!< Offset: 0x010 (R/W)  Sleep Count Register                      */
+  __IO uint32_t LSUCNT;                  /*!< Offset: 0x014 (R/W)  LSU Count Register                        */
+  __IO uint32_t FOLDCNT;                 /*!< Offset: 0x018 (R/W)  Folded-instruction Count Register         */
+  __I  uint32_t PCSR;                    /*!< Offset: 0x01C (R/ )  Program Counter Sample Register           */
+  __IO uint32_t COMP0;                   /*!< Offset: 0x020 (R/W)  Comparator Register 0                     */
+  __IO uint32_t MASK0;                   /*!< Offset: 0x024 (R/W)  Mask Register 0                           */
+  __IO uint32_t FUNCTION0;               /*!< Offset: 0x028 (R/W)  Function Register 0                       */
+       uint32_t RESERVED0[1];
+  __IO uint32_t COMP1;                   /*!< Offset: 0x030 (R/W)  Comparator Register 1                     */
+  __IO uint32_t MASK1;                   /*!< Offset: 0x034 (R/W)  Mask Register 1                           */
+  __IO uint32_t FUNCTION1;               /*!< Offset: 0x038 (R/W)  Function Register 1                       */
+       uint32_t RESERVED1[1];
+  __IO uint32_t COMP2;                   /*!< Offset: 0x040 (R/W)  Comparator Register 2                     */
+  __IO uint32_t MASK2;                   /*!< Offset: 0x044 (R/W)  Mask Register 2                           */
+  __IO uint32_t FUNCTION2;               /*!< Offset: 0x048 (R/W)  Function Register 2                       */
+       uint32_t RESERVED2[1];
+  __IO uint32_t COMP3;                   /*!< Offset: 0x050 (R/W)  Comparator Register 3                     */
+  __IO uint32_t MASK3;                   /*!< Offset: 0x054 (R/W)  Mask Register 3                           */
+  __IO uint32_t FUNCTION3;               /*!< Offset: 0x058 (R/W)  Function Register 3                       */
+} DWT_Type;
+
+/* DWT Control Register Definitions */
+#define DWT_CTRL_NUMCOMP_Pos               28                                          /*!< DWT CTRL: NUMCOMP Position */
+#define DWT_CTRL_NUMCOMP_Msk               (0xFUL << DWT_CTRL_NUMCOMP_Pos)             /*!< DWT CTRL: NUMCOMP Mask */
+
+#define DWT_CTRL_NOTRCPKT_Pos              27                                          /*!< DWT CTRL: NOTRCPKT Position */
+#define DWT_CTRL_NOTRCPKT_Msk              (0x1UL << DWT_CTRL_NOTRCPKT_Pos)            /*!< DWT CTRL: NOTRCPKT Mask */
+
+#define DWT_CTRL_NOEXTTRIG_Pos             26                                          /*!< DWT CTRL: NOEXTTRIG Position */
+#define DWT_CTRL_NOEXTTRIG_Msk             (0x1UL << DWT_CTRL_NOEXTTRIG_Pos)           /*!< DWT CTRL: NOEXTTRIG Mask */
+
+#define DWT_CTRL_NOCYCCNT_Pos              25                                          /*!< DWT CTRL: NOCYCCNT Position */
+#define DWT_CTRL_NOCYCCNT_Msk              (0x1UL << DWT_CTRL_NOCYCCNT_Pos)            /*!< DWT CTRL: NOCYCCNT Mask */
+
+#define DWT_CTRL_NOPRFCNT_Pos              24                                          /*!< DWT CTRL: NOPRFCNT Position */
+#define DWT_CTRL_NOPRFCNT_Msk              (0x1UL << DWT_CTRL_NOPRFCNT_Pos)            /*!< DWT CTRL: NOPRFCNT Mask */
+
+#define DWT_CTRL_CYCEVTENA_Pos             22                                          /*!< DWT CTRL: CYCEVTENA Position */
+#define DWT_CTRL_CYCEVTENA_Msk             (0x1UL << DWT_CTRL_CYCEVTENA_Pos)           /*!< DWT CTRL: CYCEVTENA Mask */
+
+#define DWT_CTRL_FOLDEVTENA_Pos            21                                          /*!< DWT CTRL: FOLDEVTENA Position */
+#define DWT_CTRL_FOLDEVTENA_Msk            (0x1UL << DWT_CTRL_FOLDEVTENA_Pos)          /*!< DWT CTRL: FOLDEVTENA Mask */
+
+#define DWT_CTRL_LSUEVTENA_Pos             20                                          /*!< DWT CTRL: LSUEVTENA Position */
+#define DWT_CTRL_LSUEVTENA_Msk             (0x1UL << DWT_CTRL_LSUEVTENA_Pos)           /*!< DWT CTRL: LSUEVTENA Mask */
+
+#define DWT_CTRL_SLEEPEVTENA_Pos           19                                          /*!< DWT CTRL: SLEEPEVTENA Position */
+#define DWT_CTRL_SLEEPEVTENA_Msk           (0x1UL << DWT_CTRL_SLEEPEVTENA_Pos)         /*!< DWT CTRL: SLEEPEVTENA Mask */
+
+#define DWT_CTRL_EXCEVTENA_Pos             18                                          /*!< DWT CTRL: EXCEVTENA Position */
+#define DWT_CTRL_EXCEVTENA_Msk             (0x1UL << DWT_CTRL_EXCEVTENA_Pos)           /*!< DWT CTRL: EXCEVTENA Mask */
+
+#define DWT_CTRL_CPIEVTENA_Pos             17                                          /*!< DWT CTRL: CPIEVTENA Position */
+#define DWT_CTRL_CPIEVTENA_Msk             (0x1UL << DWT_CTRL_CPIEVTENA_Pos)           /*!< DWT CTRL: CPIEVTENA Mask */
+
+#define DWT_CTRL_EXCTRCENA_Pos             16                                          /*!< DWT CTRL: EXCTRCENA Position */
+#define DWT_CTRL_EXCTRCENA_Msk             (0x1UL << DWT_CTRL_EXCTRCENA_Pos)           /*!< DWT CTRL: EXCTRCENA Mask */
+
+#define DWT_CTRL_PCSAMPLENA_Pos            12                                          /*!< DWT CTRL: PCSAMPLENA Position */
+#define DWT_CTRL_PCSAMPLENA_Msk            (0x1UL << DWT_CTRL_PCSAMPLENA_Pos)          /*!< DWT CTRL: PCSAMPLENA Mask */
+
+#define DWT_CTRL_SYNCTAP_Pos               10                                          /*!< DWT CTRL: SYNCTAP Position */
+#define DWT_CTRL_SYNCTAP_Msk               (0x3UL << DWT_CTRL_SYNCTAP_Pos)             /*!< DWT CTRL: SYNCTAP Mask */
+
+#define DWT_CTRL_CYCTAP_Pos                 9                                          /*!< DWT CTRL: CYCTAP Position */
+#define DWT_CTRL_CYCTAP_Msk                (0x1UL << DWT_CTRL_CYCTAP_Pos)              /*!< DWT CTRL: CYCTAP Mask */
+
+#define DWT_CTRL_POSTINIT_Pos               5                                          /*!< DWT CTRL: POSTINIT Position */
+#define DWT_CTRL_POSTINIT_Msk              (0xFUL << DWT_CTRL_POSTINIT_Pos)            /*!< DWT CTRL: POSTINIT Mask */
+
+#define DWT_CTRL_POSTPRESET_Pos             1                                          /*!< DWT CTRL: POSTPRESET Position */
+#define DWT_CTRL_POSTPRESET_Msk            (0xFUL << DWT_CTRL_POSTPRESET_Pos)          /*!< DWT CTRL: POSTPRESET Mask */
+
+#define DWT_CTRL_CYCCNTENA_Pos              0                                          /*!< DWT CTRL: CYCCNTENA Position */
+#define DWT_CTRL_CYCCNTENA_Msk             (0x1UL << DWT_CTRL_CYCCNTENA_Pos)           /*!< DWT CTRL: CYCCNTENA Mask */
+
+/* DWT CPI Count Register Definitions */
+#define DWT_CPICNT_CPICNT_Pos               0                                          /*!< DWT CPICNT: CPICNT Position */
+#define DWT_CPICNT_CPICNT_Msk              (0xFFUL << DWT_CPICNT_CPICNT_Pos)           /*!< DWT CPICNT: CPICNT Mask */
+
+/* DWT Exception Overhead Count Register Definitions */
+#define DWT_EXCCNT_EXCCNT_Pos               0                                          /*!< DWT EXCCNT: EXCCNT Position */
+#define DWT_EXCCNT_EXCCNT_Msk              (0xFFUL << DWT_EXCCNT_EXCCNT_Pos)           /*!< DWT EXCCNT: EXCCNT Mask */
+
+/* DWT Sleep Count Register Definitions */
+#define DWT_SLEEPCNT_SLEEPCNT_Pos           0                                          /*!< DWT SLEEPCNT: SLEEPCNT Position */
+#define DWT_SLEEPCNT_SLEEPCNT_Msk          (0xFFUL << DWT_SLEEPCNT_SLEEPCNT_Pos)       /*!< DWT SLEEPCNT: SLEEPCNT Mask */
+
+/* DWT LSU Count Register Definitions */
+#define DWT_LSUCNT_LSUCNT_Pos               0                                          /*!< DWT LSUCNT: LSUCNT Position */
+#define DWT_LSUCNT_LSUCNT_Msk              (0xFFUL << DWT_LSUCNT_LSUCNT_Pos)           /*!< DWT LSUCNT: LSUCNT Mask */
+
+/* DWT Folded-instruction Count Register Definitions */
+#define DWT_FOLDCNT_FOLDCNT_Pos             0                                          /*!< DWT FOLDCNT: FOLDCNT Position */
+#define DWT_FOLDCNT_FOLDCNT_Msk            (0xFFUL << DWT_FOLDCNT_FOLDCNT_Pos)         /*!< DWT FOLDCNT: FOLDCNT Mask */
+
+/* DWT Comparator Mask Register Definitions */
+#define DWT_MASK_MASK_Pos                   0                                          /*!< DWT MASK: MASK Position */
+#define DWT_MASK_MASK_Msk                  (0x1FUL << DWT_MASK_MASK_Pos)               /*!< DWT MASK: MASK Mask */
+
+/* DWT Comparator Function Register Definitions */
+#define DWT_FUNCTION_MATCHED_Pos           24                                          /*!< DWT FUNCTION: MATCHED Position */
+#define DWT_FUNCTION_MATCHED_Msk           (0x1UL << DWT_FUNCTION_MATCHED_Pos)         /*!< DWT FUNCTION: MATCHED Mask */
+
+#define DWT_FUNCTION_DATAVADDR1_Pos        16                                          /*!< DWT FUNCTION: DATAVADDR1 Position */
+#define DWT_FUNCTION_DATAVADDR1_Msk        (0xFUL << DWT_FUNCTION_DATAVADDR1_Pos)      /*!< DWT FUNCTION: DATAVADDR1 Mask */
+
+#define DWT_FUNCTION_DATAVADDR0_Pos        12                                          /*!< DWT FUNCTION: DATAVADDR0 Position */
+#define DWT_FUNCTION_DATAVADDR0_Msk        (0xFUL << DWT_FUNCTION_DATAVADDR0_Pos)      /*!< DWT FUNCTION: DATAVADDR0 Mask */
+
+#define DWT_FUNCTION_DATAVSIZE_Pos         10                                          /*!< DWT FUNCTION: DATAVSIZE Position */
+#define DWT_FUNCTION_DATAVSIZE_Msk         (0x3UL << DWT_FUNCTION_DATAVSIZE_Pos)       /*!< DWT FUNCTION: DATAVSIZE Mask */
+
+#define DWT_FUNCTION_LNK1ENA_Pos            9                                          /*!< DWT FUNCTION: LNK1ENA Position */
+#define DWT_FUNCTION_LNK1ENA_Msk           (0x1UL << DWT_FUNCTION_LNK1ENA_Pos)         /*!< DWT FUNCTION: LNK1ENA Mask */
+
+#define DWT_FUNCTION_DATAVMATCH_Pos         8                                          /*!< DWT FUNCTION: DATAVMATCH Position */
+#define DWT_FUNCTION_DATAVMATCH_Msk        (0x1UL << DWT_FUNCTION_DATAVMATCH_Pos)      /*!< DWT FUNCTION: DATAVMATCH Mask */
+
+#define DWT_FUNCTION_CYCMATCH_Pos           7                                          /*!< DWT FUNCTION: CYCMATCH Position */
+#define DWT_FUNCTION_CYCMATCH_Msk          (0x1UL << DWT_FUNCTION_CYCMATCH_Pos)        /*!< DWT FUNCTION: CYCMATCH Mask */
+
+#define DWT_FUNCTION_EMITRANGE_Pos          5                                          /*!< DWT FUNCTION: EMITRANGE Position */
+#define DWT_FUNCTION_EMITRANGE_Msk         (0x1UL << DWT_FUNCTION_EMITRANGE_Pos)       /*!< DWT FUNCTION: EMITRANGE Mask */
+
+#define DWT_FUNCTION_FUNCTION_Pos           0                                          /*!< DWT FUNCTION: FUNCTION Position */
+#define DWT_FUNCTION_FUNCTION_Msk          (0xFUL << DWT_FUNCTION_FUNCTION_Pos)        /*!< DWT FUNCTION: FUNCTION Mask */
+
+/*@}*/ /* end of group CMSIS_DWT */
+
+
+/** \ingroup  CMSIS_core_register
+    \defgroup CMSIS_TPI     Trace Port Interface (TPI)
+    \brief      Type definitions for the Trace Port Interface (TPI)
+  @{
+ */
+
+/** \brief  Structure type to access the Trace Port Interface Register (TPI).
+ */
+typedef struct
+{
+  __IO uint32_t SSPSR;                   /*!< Offset: 0x000 (R/ )  Supported Parallel Port Size Register     */
+  __IO uint32_t CSPSR;                   /*!< Offset: 0x004 (R/W)  Current Parallel Port Size Register */
+       uint32_t RESERVED0[2];
+  __IO uint32_t ACPR;                    /*!< Offset: 0x010 (R/W)  Asynchronous Clock Prescaler Register */
+       uint32_t RESERVED1[55];
+  __IO uint32_t SPPR;                    /*!< Offset: 0x0F0 (R/W)  Selected Pin Protocol Register */
+       uint32_t RESERVED2[131];
+  __I  uint32_t FFSR;                    /*!< Offset: 0x300 (R/ )  Formatter and Flush Status Register */
+  __IO uint32_t FFCR;                    /*!< Offset: 0x304 (R/W)  Formatter and Flush Control Register */
+  __I  uint32_t FSCR;                    /*!< Offset: 0x308 (R/ )  Formatter Synchronization Counter Register */
+       uint32_t RESERVED3[759];
+  __I  uint32_t TRIGGER;                 /*!< Offset: 0xEE8 (R/ )  TRIGGER */
+  __I  uint32_t FIFO0;                   /*!< Offset: 0xEEC (R/ )  Integration ETM Data */
+  __I  uint32_t ITATBCTR2;               /*!< Offset: 0xEF0 (R/ )  ITATBCTR2 */
+       uint32_t RESERVED4[1];
+  __I  uint32_t ITATBCTR0;               /*!< Offset: 0xEF8 (R/ )  ITATBCTR0 */
+  __I  uint32_t FIFO1;                   /*!< Offset: 0xEFC (R/ )  Integration ITM Data */
+  __IO uint32_t ITCTRL;                  /*!< Offset: 0xF00 (R/W)  Integration Mode Control */
+       uint32_t RESERVED5[39];
+  __IO uint32_t CLAIMSET;                /*!< Offset: 0xFA0 (R/W)  Claim tag set */
+  __IO uint32_t CLAIMCLR;                /*!< Offset: 0xFA4 (R/W)  Claim tag clear */
+       uint32_t RESERVED7[8];
+  __I  uint32_t DEVID;                   /*!< Offset: 0xFC8 (R/ )  TPIU_DEVID */
+  __I  uint32_t DEVTYPE;                 /*!< Offset: 0xFCC (R/ )  TPIU_DEVTYPE */
+} TPI_Type;
+
+/* TPI Asynchronous Clock Prescaler Register Definitions */
+#define TPI_ACPR_PRESCALER_Pos              0                                          /*!< TPI ACPR: PRESCALER Position */
+#define TPI_ACPR_PRESCALER_Msk             (0x1FFFUL << TPI_ACPR_PRESCALER_Pos)        /*!< TPI ACPR: PRESCALER Mask */
+
+/* TPI Selected Pin Protocol Register Definitions */
+#define TPI_SPPR_TXMODE_Pos                 0                                          /*!< TPI SPPR: TXMODE Position */
+#define TPI_SPPR_TXMODE_Msk                (0x3UL << TPI_SPPR_TXMODE_Pos)              /*!< TPI SPPR: TXMODE Mask */
+
+/* TPI Formatter and Flush Status Register Definitions */
+#define TPI_FFSR_FtNonStop_Pos              3                                          /*!< TPI FFSR: FtNonStop Position */
+#define TPI_FFSR_FtNonStop_Msk             (0x1UL << TPI_FFSR_FtNonStop_Pos)           /*!< TPI FFSR: FtNonStop Mask */
+
+#define TPI_FFSR_TCPresent_Pos              2                                          /*!< TPI FFSR: TCPresent Position */
+#define TPI_FFSR_TCPresent_Msk             (0x1UL << TPI_FFSR_TCPresent_Pos)           /*!< TPI FFSR: TCPresent Mask */
+
+#define TPI_FFSR_FtStopped_Pos              1                                          /*!< TPI FFSR: FtStopped Position */
+#define TPI_FFSR_FtStopped_Msk             (0x1UL << TPI_FFSR_FtStopped_Pos)           /*!< TPI FFSR: FtStopped Mask */
+
+#define TPI_FFSR_FlInProg_Pos               0                                          /*!< TPI FFSR: FlInProg Position */
+#define TPI_FFSR_FlInProg_Msk              (0x1UL << TPI_FFSR_FlInProg_Pos)            /*!< TPI FFSR: FlInProg Mask */
+
+/* TPI Formatter and Flush Control Register Definitions */
+#define TPI_FFCR_TrigIn_Pos                 8                                          /*!< TPI FFCR: TrigIn Position */
+#define TPI_FFCR_TrigIn_Msk                (0x1UL << TPI_FFCR_TrigIn_Pos)              /*!< TPI FFCR: TrigIn Mask */
+
+#define TPI_FFCR_EnFCont_Pos                1                                          /*!< TPI FFCR: EnFCont Position */
+#define TPI_FFCR_EnFCont_Msk               (0x1UL << TPI_FFCR_EnFCont_Pos)             /*!< TPI FFCR: EnFCont Mask */
+
+/* TPI TRIGGER Register Definitions */
+#define TPI_TRIGGER_TRIGGER_Pos             0                                          /*!< TPI TRIGGER: TRIGGER Position */
+#define TPI_TRIGGER_TRIGGER_Msk            (0x1UL << TPI_TRIGGER_TRIGGER_Pos)          /*!< TPI TRIGGER: TRIGGER Mask */
+
+/* TPI Integration ETM Data Register Definitions (FIFO0) */
+#define TPI_FIFO0_ITM_ATVALID_Pos          29                                          /*!< TPI FIFO0: ITM_ATVALID Position */
+#define TPI_FIFO0_ITM_ATVALID_Msk          (0x3UL << TPI_FIFO0_ITM_ATVALID_Pos)        /*!< TPI FIFO0: ITM_ATVALID Mask */
+
+#define TPI_FIFO0_ITM_bytecount_Pos        27                                          /*!< TPI FIFO0: ITM_bytecount Position */
+#define TPI_FIFO0_ITM_bytecount_Msk        (0x3UL << TPI_FIFO0_ITM_bytecount_Pos)      /*!< TPI FIFO0: ITM_bytecount Mask */
+
+#define TPI_FIFO0_ETM_ATVALID_Pos          26                                          /*!< TPI FIFO0: ETM_ATVALID Position */
+#define TPI_FIFO0_ETM_ATVALID_Msk          (0x3UL << TPI_FIFO0_ETM_ATVALID_Pos)        /*!< TPI FIFO0: ETM_ATVALID Mask */
+
+#define TPI_FIFO0_ETM_bytecount_Pos        24                                          /*!< TPI FIFO0: ETM_bytecount Position */
+#define TPI_FIFO0_ETM_bytecount_Msk        (0x3UL << TPI_FIFO0_ETM_bytecount_Pos)      /*!< TPI FIFO0: ETM_bytecount Mask */
+
+#define TPI_FIFO0_ETM2_Pos                 16                                          /*!< TPI FIFO0: ETM2 Position */
+#define TPI_FIFO0_ETM2_Msk                 (0xFFUL << TPI_FIFO0_ETM2_Pos)              /*!< TPI FIFO0: ETM2 Mask */
+
+#define TPI_FIFO0_ETM1_Pos                  8                                          /*!< TPI FIFO0: ETM1 Position */
+#define TPI_FIFO0_ETM1_Msk                 (0xFFUL << TPI_FIFO0_ETM1_Pos)              /*!< TPI FIFO0: ETM1 Mask */
+
+#define TPI_FIFO0_ETM0_Pos                  0                                          /*!< TPI FIFO0: ETM0 Position */
+#define TPI_FIFO0_ETM0_Msk                 (0xFFUL << TPI_FIFO0_ETM0_Pos)              /*!< TPI FIFO0: ETM0 Mask */
+
+/* TPI ITATBCTR2 Register Definitions */
+#define TPI_ITATBCTR2_ATREADY_Pos           0                                          /*!< TPI ITATBCTR2: ATREADY Position */
+#define TPI_ITATBCTR2_ATREADY_Msk          (0x1UL << TPI_ITATBCTR2_ATREADY_Pos)        /*!< TPI ITATBCTR2: ATREADY Mask */
+
+/* TPI Integration ITM Data Register Definitions (FIFO1) */
+#define TPI_FIFO1_ITM_ATVALID_Pos          29                                          /*!< TPI FIFO1: ITM_ATVALID Position */
+#define TPI_FIFO1_ITM_ATVALID_Msk          (0x3UL << TPI_FIFO1_ITM_ATVALID_Pos)        /*!< TPI FIFO1: ITM_ATVALID Mask */
+
+#define TPI_FIFO1_ITM_bytecount_Pos        27                                          /*!< TPI FIFO1: ITM_bytecount Position */
+#define TPI_FIFO1_ITM_bytecount_Msk        (0x3UL << TPI_FIFO1_ITM_bytecount_Pos)      /*!< TPI FIFO1: ITM_bytecount Mask */
+
+#define TPI_FIFO1_ETM_ATVALID_Pos          26                                          /*!< TPI FIFO1: ETM_ATVALID Position */
+#define TPI_FIFO1_ETM_ATVALID_Msk          (0x3UL << TPI_FIFO1_ETM_ATVALID_Pos)        /*!< TPI FIFO1: ETM_ATVALID Mask */
+
+#define TPI_FIFO1_ETM_bytecount_Pos        24                                          /*!< TPI FIFO1: ETM_bytecount Position */
+#define TPI_FIFO1_ETM_bytecount_Msk        (0x3UL << TPI_FIFO1_ETM_bytecount_Pos)      /*!< TPI FIFO1: ETM_bytecount Mask */
+
+#define TPI_FIFO1_ITM2_Pos                 16                                          /*!< TPI FIFO1: ITM2 Position */
+#define TPI_FIFO1_ITM2_Msk                 (0xFFUL << TPI_FIFO1_ITM2_Pos)              /*!< TPI FIFO1: ITM2 Mask */
+
+#define TPI_FIFO1_ITM1_Pos                  8                                          /*!< TPI FIFO1: ITM1 Position */
+#define TPI_FIFO1_ITM1_Msk                 (0xFFUL << TPI_FIFO1_ITM1_Pos)              /*!< TPI FIFO1: ITM1 Mask */
+
+#define TPI_FIFO1_ITM0_Pos                  0                                          /*!< TPI FIFO1: ITM0 Position */
+#define TPI_FIFO1_ITM0_Msk                 (0xFFUL << TPI_FIFO1_ITM0_Pos)              /*!< TPI FIFO1: ITM0 Mask */
+
+/* TPI ITATBCTR0 Register Definitions */
+#define TPI_ITATBCTR0_ATREADY_Pos           0                                          /*!< TPI ITATBCTR0: ATREADY Position */
+#define TPI_ITATBCTR0_ATREADY_Msk          (0x1UL << TPI_ITATBCTR0_ATREADY_Pos)        /*!< TPI ITATBCTR0: ATREADY Mask */
+
+/* TPI Integration Mode Control Register Definitions */
+#define TPI_ITCTRL_Mode_Pos                 0                                          /*!< TPI ITCTRL: Mode Position */
+#define TPI_ITCTRL_Mode_Msk                (0x1UL << TPI_ITCTRL_Mode_Pos)              /*!< TPI ITCTRL: Mode Mask */
+
+/* TPI DEVID Register Definitions */
+#define TPI_DEVID_NRZVALID_Pos             11                                          /*!< TPI DEVID: NRZVALID Position */
+#define TPI_DEVID_NRZVALID_Msk             (0x1UL << TPI_DEVID_NRZVALID_Pos)           /*!< TPI DEVID: NRZVALID Mask */
+
+#define TPI_DEVID_MANCVALID_Pos            10                                          /*!< TPI DEVID: MANCVALID Position */
+#define TPI_DEVID_MANCVALID_Msk            (0x1UL << TPI_DEVID_MANCVALID_Pos)          /*!< TPI DEVID: MANCVALID Mask */
+
+#define TPI_DEVID_PTINVALID_Pos             9                                          /*!< TPI DEVID: PTINVALID Position */
+#define TPI_DEVID_PTINVALID_Msk            (0x1UL << TPI_DEVID_PTINVALID_Pos)          /*!< TPI DEVID: PTINVALID Mask */
+
+#define TPI_DEVID_MinBufSz_Pos              6                                          /*!< TPI DEVID: MinBufSz Position */
+#define TPI_DEVID_MinBufSz_Msk             (0x7UL << TPI_DEVID_MinBufSz_Pos)           /*!< TPI DEVID: MinBufSz Mask */
+
+#define TPI_DEVID_AsynClkIn_Pos             5                                          /*!< TPI DEVID: AsynClkIn Position */
+#define TPI_DEVID_AsynClkIn_Msk            (0x1UL << TPI_DEVID_AsynClkIn_Pos)          /*!< TPI DEVID: AsynClkIn Mask */
+
+#define TPI_DEVID_NrTraceInput_Pos          0                                          /*!< TPI DEVID: NrTraceInput Position */
+#define TPI_DEVID_NrTraceInput_Msk         (0x1FUL << TPI_DEVID_NrTraceInput_Pos)      /*!< TPI DEVID: NrTraceInput Mask */
+
+/* TPI DEVTYPE Register Definitions */
+#define TPI_DEVTYPE_SubType_Pos             0                                          /*!< TPI DEVTYPE: SubType Position */
+#define TPI_DEVTYPE_SubType_Msk            (0xFUL << TPI_DEVTYPE_SubType_Pos)          /*!< TPI DEVTYPE: SubType Mask */
+
+#define TPI_DEVTYPE_MajorType_Pos           4                                          /*!< TPI DEVTYPE: MajorType Position */
+#define TPI_DEVTYPE_MajorType_Msk          (0xFUL << TPI_DEVTYPE_MajorType_Pos)        /*!< TPI DEVTYPE: MajorType Mask */
+
+/*@}*/ /* end of group CMSIS_TPI */
+
+
+#if (__MPU_PRESENT == 1)
+/** \ingroup  CMSIS_core_register
+    \defgroup CMSIS_MPU     Memory Protection Unit (MPU)
+    \brief      Type definitions for the Memory Protection Unit (MPU)
+  @{
+ */
+
+/** \brief  Structure type to access the Memory Protection Unit (MPU).
+ */
+typedef struct
+{
+  __I  uint32_t TYPE;                    /*!< Offset: 0x000 (R/ )  MPU Type Register                              */
+  __IO uint32_t CTRL;                    /*!< Offset: 0x004 (R/W)  MPU Control Register                           */
+  __IO uint32_t RNR;                     /*!< Offset: 0x008 (R/W)  MPU Region RNRber Register                     */
+  __IO uint32_t RBAR;                    /*!< Offset: 0x00C (R/W)  MPU Region Base Address Register               */
+  __IO uint32_t RASR;                    /*!< Offset: 0x010 (R/W)  MPU Region Attribute and Size Register         */
+  __IO uint32_t RBAR_A1;                 /*!< Offset: 0x014 (R/W)  MPU Alias 1 Region Base Address Register       */
+  __IO uint32_t RASR_A1;                 /*!< Offset: 0x018 (R/W)  MPU Alias 1 Region Attribute and Size Register */
+  __IO uint32_t RBAR_A2;                 /*!< Offset: 0x01C (R/W)  MPU Alias 2 Region Base Address Register       */
+  __IO uint32_t RASR_A2;                 /*!< Offset: 0x020 (R/W)  MPU Alias 2 Region Attribute and Size Register */
+  __IO uint32_t RBAR_A3;                 /*!< Offset: 0x024 (R/W)  MPU Alias 3 Region Base Address Register       */
+  __IO uint32_t RASR_A3;                 /*!< Offset: 0x028 (R/W)  MPU Alias 3 Region Attribute and Size Register */
+} MPU_Type;
+
+/* MPU Type Register */
+#define MPU_TYPE_IREGION_Pos               16                                             /*!< MPU TYPE: IREGION Position */
+#define MPU_TYPE_IREGION_Msk               (0xFFUL << MPU_TYPE_IREGION_Pos)               /*!< MPU TYPE: IREGION Mask */
+
+#define MPU_TYPE_DREGION_Pos                8                                             /*!< MPU TYPE: DREGION Position */
+#define MPU_TYPE_DREGION_Msk               (0xFFUL << MPU_TYPE_DREGION_Pos)               /*!< MPU TYPE: DREGION Mask */
+
+#define MPU_TYPE_SEPARATE_Pos               0                                             /*!< MPU TYPE: SEPARATE Position */
+#define MPU_TYPE_SEPARATE_Msk              (1UL << MPU_TYPE_SEPARATE_Pos)                 /*!< MPU TYPE: SEPARATE Mask */
+
+/* MPU Control Register */
+#define MPU_CTRL_PRIVDEFENA_Pos             2                                             /*!< MPU CTRL: PRIVDEFENA Position */
+#define MPU_CTRL_PRIVDEFENA_Msk            (1UL << MPU_CTRL_PRIVDEFENA_Pos)               /*!< MPU CTRL: PRIVDEFENA Mask */
+
+#define MPU_CTRL_HFNMIENA_Pos               1                                             /*!< MPU CTRL: HFNMIENA Position */
+#define MPU_CTRL_HFNMIENA_Msk              (1UL << MPU_CTRL_HFNMIENA_Pos)                 /*!< MPU CTRL: HFNMIENA Mask */
+
+#define MPU_CTRL_ENABLE_Pos                 0                                             /*!< MPU CTRL: ENABLE Position */
+#define MPU_CTRL_ENABLE_Msk                (1UL << MPU_CTRL_ENABLE_Pos)                   /*!< MPU CTRL: ENABLE Mask */
+
+/* MPU Region Number Register */
+#define MPU_RNR_REGION_Pos                  0                                             /*!< MPU RNR: REGION Position */
+#define MPU_RNR_REGION_Msk                 (0xFFUL << MPU_RNR_REGION_Pos)                 /*!< MPU RNR: REGION Mask */
+
+/* MPU Region Base Address Register */
+#define MPU_RBAR_ADDR_Pos                   5                                             /*!< MPU RBAR: ADDR Position */
+#define MPU_RBAR_ADDR_Msk                  (0x7FFFFFFUL << MPU_RBAR_ADDR_Pos)             /*!< MPU RBAR: ADDR Mask */
+
+#define MPU_RBAR_VALID_Pos                  4                                             /*!< MPU RBAR: VALID Position */
+#define MPU_RBAR_VALID_Msk                 (1UL << MPU_RBAR_VALID_Pos)                    /*!< MPU RBAR: VALID Mask */
+
+#define MPU_RBAR_REGION_Pos                 0                                             /*!< MPU RBAR: REGION Position */
+#define MPU_RBAR_REGION_Msk                (0xFUL << MPU_RBAR_REGION_Pos)                 /*!< MPU RBAR: REGION Mask */
+
+/* MPU Region Attribute and Size Register */
+#define MPU_RASR_ATTRS_Pos                 16                                             /*!< MPU RASR: MPU Region Attribute field Position */
+#define MPU_RASR_ATTRS_Msk                 (0xFFFFUL << MPU_RASR_ATTRS_Pos)               /*!< MPU RASR: MPU Region Attribute field Mask */
+
+#define MPU_RASR_XN_Pos                    28                                             /*!< MPU RASR: ATTRS.XN Position */
+#define MPU_RASR_XN_Msk                    (1UL << MPU_RASR_XN_Pos)                       /*!< MPU RASR: ATTRS.XN Mask */
+
+#define MPU_RASR_AP_Pos                    24                                             /*!< MPU RASR: ATTRS.AP Position */
+#define MPU_RASR_AP_Msk                    (0x7UL << MPU_RASR_AP_Pos)                     /*!< MPU RASR: ATTRS.AP Mask */
+
+#define MPU_RASR_TEX_Pos                   19                                             /*!< MPU RASR: ATTRS.TEX Position */
+#define MPU_RASR_TEX_Msk                   (0x7UL << MPU_RASR_TEX_Pos)                    /*!< MPU RASR: ATTRS.TEX Mask */
+
+#define MPU_RASR_S_Pos                     18                                             /*!< MPU RASR: ATTRS.S Position */
+#define MPU_RASR_S_Msk                     (1UL << MPU_RASR_S_Pos)                        /*!< MPU RASR: ATTRS.S Mask */
+
+#define MPU_RASR_C_Pos                     17                                             /*!< MPU RASR: ATTRS.C Position */
+#define MPU_RASR_C_Msk                     (1UL << MPU_RASR_C_Pos)                        /*!< MPU RASR: ATTRS.C Mask */
+
+#define MPU_RASR_B_Pos                     16                                             /*!< MPU RASR: ATTRS.B Position */
+#define MPU_RASR_B_Msk                     (1UL << MPU_RASR_B_Pos)                        /*!< MPU RASR: ATTRS.B Mask */
+
+#define MPU_RASR_SRD_Pos                    8                                             /*!< MPU RASR: Sub-Region Disable Position */
+#define MPU_RASR_SRD_Msk                   (0xFFUL << MPU_RASR_SRD_Pos)                   /*!< MPU RASR: Sub-Region Disable Mask */
+
+#define MPU_RASR_SIZE_Pos                   1                                             /*!< MPU RASR: Region Size Field Position */
+#define MPU_RASR_SIZE_Msk                  (0x1FUL << MPU_RASR_SIZE_Pos)                  /*!< MPU RASR: Region Size Field Mask */
+
+#define MPU_RASR_ENABLE_Pos                 0                                             /*!< MPU RASR: Region enable bit Position */
+#define MPU_RASR_ENABLE_Msk                (1UL << MPU_RASR_ENABLE_Pos)                   /*!< MPU RASR: Region enable bit Disable Mask */
+
+/*@} end of group CMSIS_MPU */
+#endif
+
+
+#if (__FPU_PRESENT == 1)
+/** \ingroup  CMSIS_core_register
+    \defgroup CMSIS_FPU     Floating Point Unit (FPU)
+    \brief      Type definitions for the Floating Point Unit (FPU)
+  @{
+ */
+
+/** \brief  Structure type to access the Floating Point Unit (FPU).
+ */
+typedef struct
+{
+       uint32_t RESERVED0[1];
+  __IO uint32_t FPCCR;                   /*!< Offset: 0x004 (R/W)  Floating-Point Context Control Register               */
+  __IO uint32_t FPCAR;                   /*!< Offset: 0x008 (R/W)  Floating-Point Context Address Register               */
+  __IO uint32_t FPDSCR;                  /*!< Offset: 0x00C (R/W)  Floating-Point Default Status Control Register        */
+  __I  uint32_t MVFR0;                   /*!< Offset: 0x010 (R/ )  Media and FP Feature Register 0                       */
+  __I  uint32_t MVFR1;                   /*!< Offset: 0x014 (R/ )  Media and FP Feature Register 1                       */
+} FPU_Type;
+
+/* Floating-Point Context Control Register */
+#define FPU_FPCCR_ASPEN_Pos                31                                             /*!< FPCCR: ASPEN bit Position */
+#define FPU_FPCCR_ASPEN_Msk                (1UL << FPU_FPCCR_ASPEN_Pos)                   /*!< FPCCR: ASPEN bit Mask */
+
+#define FPU_FPCCR_LSPEN_Pos                30                                             /*!< FPCCR: LSPEN Position */
+#define FPU_FPCCR_LSPEN_Msk                (1UL << FPU_FPCCR_LSPEN_Pos)                   /*!< FPCCR: LSPEN bit Mask */
+
+#define FPU_FPCCR_MONRDY_Pos                8                                             /*!< FPCCR: MONRDY Position */
+#define FPU_FPCCR_MONRDY_Msk               (1UL << FPU_FPCCR_MONRDY_Pos)                  /*!< FPCCR: MONRDY bit Mask */
+
+#define FPU_FPCCR_BFRDY_Pos                 6                                             /*!< FPCCR: BFRDY Position */
+#define FPU_FPCCR_BFRDY_Msk                (1UL << FPU_FPCCR_BFRDY_Pos)                   /*!< FPCCR: BFRDY bit Mask */
+
+#define FPU_FPCCR_MMRDY_Pos                 5                                             /*!< FPCCR: MMRDY Position */
+#define FPU_FPCCR_MMRDY_Msk                (1UL << FPU_FPCCR_MMRDY_Pos)                   /*!< FPCCR: MMRDY bit Mask */
+
+#define FPU_FPCCR_HFRDY_Pos                 4                                             /*!< FPCCR: HFRDY Position */
+#define FPU_FPCCR_HFRDY_Msk                (1UL << FPU_FPCCR_HFRDY_Pos)                   /*!< FPCCR: HFRDY bit Mask */
+
+#define FPU_FPCCR_THREAD_Pos                3                                             /*!< FPCCR: processor mode bit Position */
+#define FPU_FPCCR_THREAD_Msk               (1UL << FPU_FPCCR_THREAD_Pos)                  /*!< FPCCR: processor mode active bit Mask */
+
+#define FPU_FPCCR_USER_Pos                  1                                             /*!< FPCCR: privilege level bit Position */
+#define FPU_FPCCR_USER_Msk                 (1UL << FPU_FPCCR_USER_Pos)                    /*!< FPCCR: privilege level bit Mask */
+
+#define FPU_FPCCR_LSPACT_Pos                0                                             /*!< FPCCR: Lazy state preservation active bit Position */
+#define FPU_FPCCR_LSPACT_Msk               (1UL << FPU_FPCCR_LSPACT_Pos)                  /*!< FPCCR: Lazy state preservation active bit Mask */
+
+/* Floating-Point Context Address Register */
+#define FPU_FPCAR_ADDRESS_Pos               3                                             /*!< FPCAR: ADDRESS bit Position */
+#define FPU_FPCAR_ADDRESS_Msk              (0x1FFFFFFFUL << FPU_FPCAR_ADDRESS_Pos)        /*!< FPCAR: ADDRESS bit Mask */
+
+/* Floating-Point Default Status Control Register */
+#define FPU_FPDSCR_AHP_Pos                 26                                             /*!< FPDSCR: AHP bit Position */
+#define FPU_FPDSCR_AHP_Msk                 (1UL << FPU_FPDSCR_AHP_Pos)                    /*!< FPDSCR: AHP bit Mask */
+
+#define FPU_FPDSCR_DN_Pos                  25                                             /*!< FPDSCR: DN bit Position */
+#define FPU_FPDSCR_DN_Msk                  (1UL << FPU_FPDSCR_DN_Pos)                     /*!< FPDSCR: DN bit Mask */
+
+#define FPU_FPDSCR_FZ_Pos                  24                                             /*!< FPDSCR: FZ bit Position */
+#define FPU_FPDSCR_FZ_Msk                  (1UL << FPU_FPDSCR_FZ_Pos)                     /*!< FPDSCR: FZ bit Mask */
+
+#define FPU_FPDSCR_RMode_Pos               22                                             /*!< FPDSCR: RMode bit Position */
+#define FPU_FPDSCR_RMode_Msk               (3UL << FPU_FPDSCR_RMode_Pos)                  /*!< FPDSCR: RMode bit Mask */
+
+/* Media and FP Feature Register 0 */
+#define FPU_MVFR0_FP_rounding_modes_Pos    28                                             /*!< MVFR0: FP rounding modes bits Position */
+#define FPU_MVFR0_FP_rounding_modes_Msk    (0xFUL << FPU_MVFR0_FP_rounding_modes_Pos)     /*!< MVFR0: FP rounding modes bits Mask */
+
+#define FPU_MVFR0_Short_vectors_Pos        24                                             /*!< MVFR0: Short vectors bits Position */
+#define FPU_MVFR0_Short_vectors_Msk        (0xFUL << FPU_MVFR0_Short_vectors_Pos)         /*!< MVFR0: Short vectors bits Mask */
+
+#define FPU_MVFR0_Square_root_Pos          20                                             /*!< MVFR0: Square root bits Position */
+#define FPU_MVFR0_Square_root_Msk          (0xFUL << FPU_MVFR0_Square_root_Pos)           /*!< MVFR0: Square root bits Mask */
+
+#define FPU_MVFR0_Divide_Pos               16                                             /*!< MVFR0: Divide bits Position */
+#define FPU_MVFR0_Divide_Msk               (0xFUL << FPU_MVFR0_Divide_Pos)                /*!< MVFR0: Divide bits Mask */
+
+#define FPU_MVFR0_FP_excep_trapping_Pos    12                                             /*!< MVFR0: FP exception trapping bits Position */
+#define FPU_MVFR0_FP_excep_trapping_Msk    (0xFUL << FPU_MVFR0_FP_excep_trapping_Pos)     /*!< MVFR0: FP exception trapping bits Mask */
+
+#define FPU_MVFR0_Double_precision_Pos      8                                             /*!< MVFR0: Double-precision bits Position */
+#define FPU_MVFR0_Double_precision_Msk     (0xFUL << FPU_MVFR0_Double_precision_Pos)      /*!< MVFR0: Double-precision bits Mask */
+
+#define FPU_MVFR0_Single_precision_Pos      4                                             /*!< MVFR0: Single-precision bits Position */
+#define FPU_MVFR0_Single_precision_Msk     (0xFUL << FPU_MVFR0_Single_precision_Pos)      /*!< MVFR0: Single-precision bits Mask */
+
+#define FPU_MVFR0_A_SIMD_registers_Pos      0                                             /*!< MVFR0: A_SIMD registers bits Position */
+#define FPU_MVFR0_A_SIMD_registers_Msk     (0xFUL << FPU_MVFR0_A_SIMD_registers_Pos)      /*!< MVFR0: A_SIMD registers bits Mask */
+
+/* Media and FP Feature Register 1 */
+#define FPU_MVFR1_FP_fused_MAC_Pos         28                                             /*!< MVFR1: FP fused MAC bits Position */
+#define FPU_MVFR1_FP_fused_MAC_Msk         (0xFUL << FPU_MVFR1_FP_fused_MAC_Pos)          /*!< MVFR1: FP fused MAC bits Mask */
+
+#define FPU_MVFR1_FP_HPFP_Pos              24                                             /*!< MVFR1: FP HPFP bits Position */
+#define FPU_MVFR1_FP_HPFP_Msk              (0xFUL << FPU_MVFR1_FP_HPFP_Pos)               /*!< MVFR1: FP HPFP bits Mask */
+
+#define FPU_MVFR1_D_NaN_mode_Pos            4                                             /*!< MVFR1: D_NaN mode bits Position */
+#define FPU_MVFR1_D_NaN_mode_Msk           (0xFUL << FPU_MVFR1_D_NaN_mode_Pos)            /*!< MVFR1: D_NaN mode bits Mask */
+
+#define FPU_MVFR1_FtZ_mode_Pos              0                                             /*!< MVFR1: FtZ mode bits Position */
+#define FPU_MVFR1_FtZ_mode_Msk             (0xFUL << FPU_MVFR1_FtZ_mode_Pos)              /*!< MVFR1: FtZ mode bits Mask */
+
+/*@} end of group CMSIS_FPU */
+#endif
+
+
+/** \ingroup  CMSIS_core_register
+    \defgroup CMSIS_CoreDebug       Core Debug Registers (CoreDebug)
+    \brief      Type definitions for the Core Debug Registers
+  @{
+ */
+
+/** \brief  Structure type to access the Core Debug Register (CoreDebug).
+ */
+typedef struct
+{
+  __IO uint32_t DHCSR;                   /*!< Offset: 0x000 (R/W)  Debug Halting Control and Status Register    */
+  __O  uint32_t DCRSR;                   /*!< Offset: 0x004 ( /W)  Debug Core Register Selector Register        */
+  __IO uint32_t DCRDR;                   /*!< Offset: 0x008 (R/W)  Debug Core Register Data Register            */
+  __IO uint32_t DEMCR;                   /*!< Offset: 0x00C (R/W)  Debug Exception and Monitor Control Register */
+} CoreDebug_Type;
+
+/* Debug Halting Control and Status Register */
+#define CoreDebug_DHCSR_DBGKEY_Pos         16                                             /*!< CoreDebug DHCSR: DBGKEY Position */
+#define CoreDebug_DHCSR_DBGKEY_Msk         (0xFFFFUL << CoreDebug_DHCSR_DBGKEY_Pos)       /*!< CoreDebug DHCSR: DBGKEY Mask */
+
+#define CoreDebug_DHCSR_S_RESET_ST_Pos     25                                             /*!< CoreDebug DHCSR: S_RESET_ST Position */
+#define CoreDebug_DHCSR_S_RESET_ST_Msk     (1UL << CoreDebug_DHCSR_S_RESET_ST_Pos)        /*!< CoreDebug DHCSR: S_RESET_ST Mask */
+
+#define CoreDebug_DHCSR_S_RETIRE_ST_Pos    24                                             /*!< CoreDebug DHCSR: S_RETIRE_ST Position */
+#define CoreDebug_DHCSR_S_RETIRE_ST_Msk    (1UL << CoreDebug_DHCSR_S_RETIRE_ST_Pos)       /*!< CoreDebug DHCSR: S_RETIRE_ST Mask */
+
+#define CoreDebug_DHCSR_S_LOCKUP_Pos       19                                             /*!< CoreDebug DHCSR: S_LOCKUP Position */
+#define CoreDebug_DHCSR_S_LOCKUP_Msk       (1UL << CoreDebug_DHCSR_S_LOCKUP_Pos)          /*!< CoreDebug DHCSR: S_LOCKUP Mask */
+
+#define CoreDebug_DHCSR_S_SLEEP_Pos        18                                             /*!< CoreDebug DHCSR: S_SLEEP Position */
+#define CoreDebug_DHCSR_S_SLEEP_Msk        (1UL << CoreDebug_DHCSR_S_SLEEP_Pos)           /*!< CoreDebug DHCSR: S_SLEEP Mask */
+
+#define CoreDebug_DHCSR_S_HALT_Pos         17                                             /*!< CoreDebug DHCSR: S_HALT Position */
+#define CoreDebug_DHCSR_S_HALT_Msk         (1UL << CoreDebug_DHCSR_S_HALT_Pos)            /*!< CoreDebug DHCSR: S_HALT Mask */
+
+#define CoreDebug_DHCSR_S_REGRDY_Pos       16                                             /*!< CoreDebug DHCSR: S_REGRDY Position */
+#define CoreDebug_DHCSR_S_REGRDY_Msk       (1UL << CoreDebug_DHCSR_S_REGRDY_Pos)          /*!< CoreDebug DHCSR: S_REGRDY Mask */
+
+#define CoreDebug_DHCSR_C_SNAPSTALL_Pos     5                                             /*!< CoreDebug DHCSR: C_SNAPSTALL Position */
+#define CoreDebug_DHCSR_C_SNAPSTALL_Msk    (1UL << CoreDebug_DHCSR_C_SNAPSTALL_Pos)       /*!< CoreDebug DHCSR: C_SNAPSTALL Mask */
+
+#define CoreDebug_DHCSR_C_MASKINTS_Pos      3                                             /*!< CoreDebug DHCSR: C_MASKINTS Position */
+#define CoreDebug_DHCSR_C_MASKINTS_Msk     (1UL << CoreDebug_DHCSR_C_MASKINTS_Pos)        /*!< CoreDebug DHCSR: C_MASKINTS Mask */
+
+#define CoreDebug_DHCSR_C_STEP_Pos          2                                             /*!< CoreDebug DHCSR: C_STEP Position */
+#define CoreDebug_DHCSR_C_STEP_Msk         (1UL << CoreDebug_DHCSR_C_STEP_Pos)            /*!< CoreDebug DHCSR: C_STEP Mask */
+
+#define CoreDebug_DHCSR_C_HALT_Pos          1                                             /*!< CoreDebug DHCSR: C_HALT Position */
+#define CoreDebug_DHCSR_C_HALT_Msk         (1UL << CoreDebug_DHCSR_C_HALT_Pos)            /*!< CoreDebug DHCSR: C_HALT Mask */
+
+#define CoreDebug_DHCSR_C_DEBUGEN_Pos       0                                             /*!< CoreDebug DHCSR: C_DEBUGEN Position */
+#define CoreDebug_DHCSR_C_DEBUGEN_Msk      (1UL << CoreDebug_DHCSR_C_DEBUGEN_Pos)         /*!< CoreDebug DHCSR: C_DEBUGEN Mask */
+
+/* Debug Core Register Selector Register */
+#define CoreDebug_DCRSR_REGWnR_Pos         16                                             /*!< CoreDebug DCRSR: REGWnR Position */
+#define CoreDebug_DCRSR_REGWnR_Msk         (1UL << CoreDebug_DCRSR_REGWnR_Pos)            /*!< CoreDebug DCRSR: REGWnR Mask */
+
+#define CoreDebug_DCRSR_REGSEL_Pos          0                                             /*!< CoreDebug DCRSR: REGSEL Position */
+#define CoreDebug_DCRSR_REGSEL_Msk         (0x1FUL << CoreDebug_DCRSR_REGSEL_Pos)         /*!< CoreDebug DCRSR: REGSEL Mask */
+
+/* Debug Exception and Monitor Control Register */
+#define CoreDebug_DEMCR_TRCENA_Pos         24                                             /*!< CoreDebug DEMCR: TRCENA Position */
+#define CoreDebug_DEMCR_TRCENA_Msk         (1UL << CoreDebug_DEMCR_TRCENA_Pos)            /*!< CoreDebug DEMCR: TRCENA Mask */
+
+#define CoreDebug_DEMCR_MON_REQ_Pos        19                                             /*!< CoreDebug DEMCR: MON_R

<TRUNCATED>


[28/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/cmsis-core/src/ext/core_ca_mmu.h
----------------------------------------------------------------------
diff --git a/libs/cmsis-core/src/ext/core_ca_mmu.h b/libs/cmsis-core/src/ext/core_ca_mmu.h
deleted file mode 100644
index 1fb99c5..0000000
--- a/libs/cmsis-core/src/ext/core_ca_mmu.h
+++ /dev/null
@@ -1,848 +0,0 @@
-;/**************************************************************************//**
-; * @file     core_ca_mmu.h
-; * @brief    MMU Startup File for
-; *           VE_A9_MP Device Series
-; * @version  V1.01
-; * @date     25 March 2013
-; *
-; * @note
-; *
-; ******************************************************************************/
-;/* Copyright (c) 2012 ARM LIMITED
-;
-;   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 ARM 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 COPYRIGHT HOLDERS AND 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.
-;   ---------------------------------------------------------------------------*/
-
-#ifdef __cplusplus
- extern "C" {
-#endif
-
-#ifndef _MMU_FUNC_H
-#define _MMU_FUNC_H
-
-#define SECTION_DESCRIPTOR      (0x2)
-#define SECTION_MASK            (0xFFFFFFFC)
-
-#define SECTION_TEXCB_MASK      (0xFFFF8FF3)
-#define SECTION_B_SHIFT         (2)
-#define SECTION_C_SHIFT         (3)
-#define SECTION_TEX0_SHIFT      (12)
-#define SECTION_TEX1_SHIFT      (13)
-#define SECTION_TEX2_SHIFT      (14)
-
-#define SECTION_XN_MASK         (0xFFFFFFEF)
-#define SECTION_XN_SHIFT        (4)
-
-#define SECTION_DOMAIN_MASK     (0xFFFFFE1F)
-#define SECTION_DOMAIN_SHIFT    (5)
-
-#define SECTION_P_MASK          (0xFFFFFDFF)
-#define SECTION_P_SHIFT         (9)
-
-#define SECTION_AP_MASK         (0xFFFF73FF)
-#define SECTION_AP_SHIFT        (10)
-#define SECTION_AP2_SHIFT       (15)
-
-#define SECTION_S_MASK          (0xFFFEFFFF)
-#define SECTION_S_SHIFT         (16)
-
-#define SECTION_NG_MASK         (0xFFFDFFFF)
-#define SECTION_NG_SHIFT        (17)
-
-#define SECTION_NS_MASK         (0xFFF7FFFF)
-#define SECTION_NS_SHIFT        (19)
-
-
-#define PAGE_L1_DESCRIPTOR      (0x1)
-#define PAGE_L1_MASK            (0xFFFFFFFC)
-
-#define PAGE_L2_4K_DESC         (0x2)
-#define PAGE_L2_4K_MASK         (0xFFFFFFFD)
-
-#define PAGE_L2_64K_DESC        (0x1)
-#define PAGE_L2_64K_MASK        (0xFFFFFFFC)
-
-#define PAGE_4K_TEXCB_MASK      (0xFFFFFE33)
-#define PAGE_4K_B_SHIFT         (2)
-#define PAGE_4K_C_SHIFT         (3)
-#define PAGE_4K_TEX0_SHIFT      (6)
-#define PAGE_4K_TEX1_SHIFT      (7)
-#define PAGE_4K_TEX2_SHIFT      (8)
-
-#define PAGE_64K_TEXCB_MASK     (0xFFFF8FF3)
-#define PAGE_64K_B_SHIFT        (2)
-#define PAGE_64K_C_SHIFT        (3)
-#define PAGE_64K_TEX0_SHIFT     (12)
-#define PAGE_64K_TEX1_SHIFT     (13)
-#define PAGE_64K_TEX2_SHIFT     (14)
-
-#define PAGE_TEXCB_MASK         (0xFFFF8FF3)
-#define PAGE_B_SHIFT            (2)
-#define PAGE_C_SHIFT            (3)
-#define PAGE_TEX_SHIFT          (12)
-
-#define PAGE_XN_4K_MASK         (0xFFFFFFFE)
-#define PAGE_XN_4K_SHIFT        (0)
-#define PAGE_XN_64K_MASK        (0xFFFF7FFF)
-#define PAGE_XN_64K_SHIFT       (15)
-
-
-#define PAGE_DOMAIN_MASK        (0xFFFFFE1F)
-#define PAGE_DOMAIN_SHIFT       (5)
-
-#define PAGE_P_MASK             (0xFFFFFDFF)
-#define PAGE_P_SHIFT            (9)
-
-#define PAGE_AP_MASK            (0xFFFFFDCF)
-#define PAGE_AP_SHIFT           (4)
-#define PAGE_AP2_SHIFT          (9)
-
-#define PAGE_S_MASK             (0xFFFFFBFF)
-#define PAGE_S_SHIFT            (10)
-
-#define PAGE_NG_MASK            (0xFFFFF7FF)
-#define PAGE_NG_SHIFT           (11)
-
-#define PAGE_NS_MASK            (0xFFFFFFF7)
-#define PAGE_NS_SHIFT           (3)
-
-#define OFFSET_1M               (0x00100000)
-#define OFFSET_64K              (0x00010000)
-#define OFFSET_4K               (0x00001000)
-
-#define DESCRIPTOR_FAULT        (0x00000000)
-
-/* ###########################  MMU Function Access  ########################### */
-/** \ingroup  MMU_FunctionInterface
-    \defgroup MMU_Functions MMU Functions Interface
-  @{
- */
-
-/* Attributes enumerations */
-
-/* Region size attributes */
-typedef enum
-{
-   SECTION,
-   PAGE_4k,
-   PAGE_64k,
-} mmu_region_size_Type;
-
-/* Region type attributes */
-typedef enum
-{
-   NORMAL,
-   DEVICE,
-   SHARED_DEVICE,
-   NON_SHARED_DEVICE,
-   STRONGLY_ORDERED
-} mmu_memory_Type;
-
-/* Region cacheability attributes */
-typedef enum
-{
-   NON_CACHEABLE,
-   WB_WA,
-   WT,
-   WB_NO_WA,
-} mmu_cacheability_Type;
-
-/* Region parity check attributes */
-typedef enum
-{
-   ECC_DISABLED,
-   ECC_ENABLED,
-} mmu_ecc_check_Type;
-
-/* Region execution attributes */
-typedef enum
-{
-   EXECUTE,
-   NON_EXECUTE,
-} mmu_execute_Type;
-
-/* Region global attributes */
-typedef enum
-{
-   GLOBAL,
-   NON_GLOBAL,
-} mmu_global_Type;
-
-/* Region shareability attributes */
-typedef enum
-{
-   NON_SHARED,
-   SHARED,
-} mmu_shared_Type;
-
-/* Region security attributes */
-typedef enum
-{
-   SECURE,
-   NON_SECURE,
-} mmu_secure_Type;
-
-/* Region access attributes */
-typedef enum
-{
-   NO_ACCESS,
-   RW,
-   READ,
-} mmu_access_Type;
-
-/* Memory Region definition */
-typedef struct RegionStruct {
-    mmu_region_size_Type rg_t;
-    mmu_memory_Type mem_t;
-    uint8_t domain;
-    mmu_cacheability_Type inner_norm_t;
-    mmu_cacheability_Type outer_norm_t;
-    mmu_ecc_check_Type e_t;
-    mmu_execute_Type xn_t;
-    mmu_global_Type g_t;
-    mmu_secure_Type sec_t;
-    mmu_access_Type priv_t;
-    mmu_access_Type user_t;
-    mmu_shared_Type sh_t;
-
-} mmu_region_attributes_Type;
-
-/** \brief  Set section execution-never attribute
-
-    The function sets section execution-never attribute
-
-    \param [out]    descriptor_l1  L1 descriptor.
-    \param [in]                xn  Section execution-never attribute : EXECUTE , NON_EXECUTE.
-
-    \return          0  
- */
-__STATIC_INLINE int __xn_section(uint32_t *descriptor_l1, mmu_execute_Type xn)
-{
-    *descriptor_l1 &= SECTION_XN_MASK;
-    *descriptor_l1 |= ((xn & 0x1) << SECTION_XN_SHIFT);
-    return 0;
-}
-
-/** \brief  Set section domain
-
-    The function sets section domain
-
-    \param [out]    descriptor_l1  L1 descriptor.
-    \param [in]            domain  Section domain
-
-    \return          0  
- */
-__STATIC_INLINE int __domain_section(uint32_t *descriptor_l1, uint8_t domain)
-{
-    *descriptor_l1 &= SECTION_DOMAIN_MASK;
-    *descriptor_l1 |= ((domain & 0xF) << SECTION_DOMAIN_SHIFT);
-    return 0;
-}
-
-/** \brief  Set section parity check
-
-    The function sets section parity check
-
-    \param [out]    descriptor_l1  L1 descriptor.
-    \param [in]              p_bit Parity check: ECC_DISABLED, ECC_ENABLED
-
-    \return          0  
- */
-__STATIC_INLINE int __p_section(uint32_t *descriptor_l1, mmu_ecc_check_Type p_bit)
-{
-    *descriptor_l1 &= SECTION_P_MASK;
-    *descriptor_l1 |= ((p_bit & 0x1) << SECTION_P_SHIFT);
-    return 0;
-}
-
-/** \brief  Set section access privileges
-
-    The function sets section access privileges
-
-    \param [out]    descriptor_l1  L1 descriptor.
-    \param [in]              user  User Level Access: NO_ACCESS, RW, READ
-    \param [in]              priv  Privilege Level Access: NO_ACCESS, RW, READ
-    \param [in]               afe  Access flag enable
-
-    \return          0  
- */
-__STATIC_INLINE int __ap_section(uint32_t *descriptor_l1, mmu_access_Type user, mmu_access_Type priv,  uint32_t afe)
-{
-    uint32_t ap = 0;
-
-    if (afe == 0) { //full access
-        if ((priv == NO_ACCESS) && (user == NO_ACCESS)) { ap = 0x0; }
-        else if ((priv == RW) && (user == NO_ACCESS))   { ap = 0x1; }
-        else if ((priv == RW) && (user == READ))        { ap = 0x2; }
-        else if ((priv == RW) && (user == RW))          { ap = 0x3; }
-        else if ((priv == READ) && (user == NO_ACCESS)) { ap = 0x5; }
-        else if ((priv == READ) && (user == READ))      { ap = 0x6; }
-    }
-
-    else { //Simplified access
-        if ((priv == RW) && (user == NO_ACCESS))        { ap = 0x1; }
-        else if ((priv == RW) && (user == RW))          { ap = 0x3; }
-        else if ((priv == READ) && (user == NO_ACCESS)) { ap = 0x5; }
-        else if ((priv == READ) && (user == READ))      { ap = 0x7; }
-    }
-
-    *descriptor_l1 &= SECTION_AP_MASK;
-    *descriptor_l1 |= (ap & 0x3) << SECTION_AP_SHIFT;
-    *descriptor_l1 |= ((ap & 0x4)>>2) << SECTION_AP2_SHIFT;
-
-    return 0;
-}
-
-/** \brief  Set section shareability
-
-    The function sets section shareability
-
-    \param [out]    descriptor_l1  L1 descriptor.
-    \param [in]             s_bit  Section shareability: NON_SHARED, SHARED
-
-    \return          0  
- */
-__STATIC_INLINE int __shared_section(uint32_t *descriptor_l1, mmu_shared_Type s_bit)
-{
-    *descriptor_l1 &= SECTION_S_MASK;
-    *descriptor_l1 |= ((s_bit & 0x1) << SECTION_S_SHIFT);
-    return 0;
-}
-
-/** \brief  Set section Global attribute
-
-    The function sets section Global attribute
-
-    \param [out]    descriptor_l1  L1 descriptor.
-    \param [in]             g_bit  Section attribute: GLOBAL, NON_GLOBAL
-
-    \return          0  
- */
-__STATIC_INLINE int __global_section(uint32_t *descriptor_l1, mmu_global_Type g_bit)
-{
-    *descriptor_l1 &= SECTION_NG_MASK;
-    *descriptor_l1 |= ((g_bit & 0x1) << SECTION_NG_SHIFT);
-    return 0;
-}
-
-/** \brief  Set section Security attribute
-
-    The function sets section Global attribute
-
-    \param [out]    descriptor_l1  L1 descriptor.
-    \param [in]             s_bit  Section Security attribute: SECURE, NON_SECURE
-
-    \return          0  
- */
-__STATIC_INLINE int __secure_section(uint32_t *descriptor_l1, mmu_secure_Type s_bit)
-{
-    *descriptor_l1 &= SECTION_NS_MASK;
-    *descriptor_l1 |= ((s_bit & 0x1) << SECTION_NS_SHIFT);
-    return 0;
-}
-
-/* Page 4k or 64k */
-/** \brief  Set 4k/64k page execution-never attribute
-
-    The function sets 4k/64k page execution-never attribute
-
-    \param [out]    descriptor_l2  L2 descriptor.
-    \param [in]                xn  Page execution-never attribute : EXECUTE , NON_EXECUTE.
-    \param [in]              page  Page size: PAGE_4k, PAGE_64k,
-   
-    \return          0  
- */
-__STATIC_INLINE int __xn_page(uint32_t *descriptor_l2, mmu_execute_Type xn, mmu_region_size_Type page)
-{
-    if (page == PAGE_4k)
-    {
-        *descriptor_l2 &= PAGE_XN_4K_MASK;
-        *descriptor_l2 |= ((xn & 0x1) << PAGE_XN_4K_SHIFT);
-    }
-    else
-    {
-        *descriptor_l2 &= PAGE_XN_64K_MASK;
-        *descriptor_l2 |= ((xn & 0x1) << PAGE_XN_64K_SHIFT);
-    }
-    return 0;
-}
-
-/** \brief  Set 4k/64k page domain
-
-    The function sets 4k/64k page domain
-
-    \param [out]    descriptor_l1  L1 descriptor.
-    \param [in]            domain  Page domain
-
-    \return          0  
- */
-__STATIC_INLINE int __domain_page(uint32_t *descriptor_l1, uint8_t domain)
-{
-    *descriptor_l1 &= PAGE_DOMAIN_MASK;
-    *descriptor_l1 |= ((domain & 0xf) << PAGE_DOMAIN_SHIFT);
-    return 0;
-}
-
-/** \brief  Set 4k/64k page parity check
-
-    The function sets 4k/64k page parity check
-
-    \param [out]    descriptor_l1  L1 descriptor.
-    \param [in]              p_bit Parity check: ECC_DISABLED, ECC_ENABLED
-
-    \return          0  
- */
-__STATIC_INLINE int __p_page(uint32_t *descriptor_l1, mmu_ecc_check_Type p_bit)
-{
-    *descriptor_l1 &= SECTION_P_MASK;
-    *descriptor_l1 |= ((p_bit & 0x1) << SECTION_P_SHIFT);
-    return 0;
-}
-
-/** \brief  Set 4k/64k page access privileges
-
-    The function sets 4k/64k page access privileges
-
-    \param [out]    descriptor_l2  L2 descriptor.
-    \param [in]              user  User Level Access: NO_ACCESS, RW, READ
-    \param [in]              priv  Privilege Level Access: NO_ACCESS, RW, READ
-    \param [in]               afe  Access flag enable
-
-    \return          0  
- */
-__STATIC_INLINE int __ap_page(uint32_t *descriptor_l2, mmu_access_Type user, mmu_access_Type priv,  uint32_t afe)
-{
-    uint32_t ap = 0;
-
-    if (afe == 0) { //full access
-        if ((priv == NO_ACCESS) && (user == NO_ACCESS)) { ap = 0x0; }
-        else if ((priv == RW) && (user == NO_ACCESS))   { ap = 0x1; }
-        else if ((priv == RW) && (user == READ))        { ap = 0x2; }
-        else if ((priv == RW) && (user == RW))          { ap = 0x3; }
-        else if ((priv == READ) && (user == NO_ACCESS)) { ap = 0x5; }
-        else if ((priv == READ) && (user == READ))      { ap = 0x6; }
-    }
-
-    else { //Simplified access
-        if ((priv == RW) && (user == NO_ACCESS))        { ap = 0x1; }
-        else if ((priv == RW) && (user == RW))          { ap = 0x3; }
-        else if ((priv == READ) && (user == NO_ACCESS)) { ap = 0x5; }
-        else if ((priv == READ) && (user == READ))      { ap = 0x7; }
-    }
-
-    *descriptor_l2 &= PAGE_AP_MASK;
-    *descriptor_l2 |= (ap & 0x3) << PAGE_AP_SHIFT;
-    *descriptor_l2 |= ((ap & 0x4)>>2) << PAGE_AP2_SHIFT;
-
-    return 0;
-}
-
-/** \brief  Set 4k/64k page shareability
-
-    The function sets 4k/64k page shareability
-
-    \param [out]    descriptor_l2  L2 descriptor.
-    \param [in]             s_bit  4k/64k page shareability: NON_SHARED, SHARED
-
-    \return          0  
- */
-__STATIC_INLINE int __shared_page(uint32_t *descriptor_l2, mmu_shared_Type s_bit)
-{
-    *descriptor_l2 &= PAGE_S_MASK;
-    *descriptor_l2 |= ((s_bit & 0x1) << PAGE_S_SHIFT);
-    return 0;
-}
-
-/** \brief  Set 4k/64k page Global attribute
-
-    The function sets 4k/64k page Global attribute
-
-    \param [out]    descriptor_l2  L2 descriptor.
-    \param [in]             g_bit  4k/64k page attribute: GLOBAL, NON_GLOBAL
-
-    \return          0  
- */
-__STATIC_INLINE int __global_page(uint32_t *descriptor_l2, mmu_global_Type g_bit)
-{
-    *descriptor_l2 &= PAGE_NG_MASK;
-    *descriptor_l2 |= ((g_bit & 0x1) << PAGE_NG_SHIFT);
-    return 0;
-}
-
-/** \brief  Set 4k/64k page Security attribute
-
-    The function sets 4k/64k page Global attribute
-
-    \param [out]    descriptor_l1  L1 descriptor.
-    \param [in]             s_bit  4k/64k page Security attribute: SECURE, NON_SECURE
-
-    \return          0  
- */
-__STATIC_INLINE int __secure_page(uint32_t *descriptor_l1, mmu_secure_Type s_bit)
-{
-    *descriptor_l1 &= PAGE_NS_MASK;
-    *descriptor_l1 |= ((s_bit & 0x1) << PAGE_NS_SHIFT);
-    return 0;
-}
-
-
-/** \brief  Set Section memory attributes
-
-    The function sets section memory attributes
-
-    \param [out]    descriptor_l1  L1 descriptor.
-    \param [in]               mem  Section memory type: NORMAL, DEVICE, SHARED_DEVICE, NON_SHARED_DEVICE, STRONGLY_ORDERED
-    \param [in]             outer  Outer cacheability: NON_CACHEABLE, WB_WA, WT, WB_NO_WA,
-    \param [in]             inner  Inner cacheability: NON_CACHEABLE, WB_WA, WT, WB_NO_WA,
-
-    \return          0  
- */
-__STATIC_INLINE int __memory_section(uint32_t *descriptor_l1, mmu_memory_Type mem, mmu_cacheability_Type outer, mmu_cacheability_Type inner)
-{
-    *descriptor_l1 &= SECTION_TEXCB_MASK;
-
-    if (STRONGLY_ORDERED == mem)
-    {
-        return 0;
-    }
-    else if (SHARED_DEVICE == mem)
-    {
-        *descriptor_l1 |= (1 << SECTION_B_SHIFT);
-    }
-    else if (NON_SHARED_DEVICE == mem)
-    {
-        *descriptor_l1 |= (1 << SECTION_TEX1_SHIFT);
-    }
-    else if (NORMAL == mem)
-    {
-           *descriptor_l1 |= 1 << SECTION_TEX2_SHIFT;
-           switch(inner)
-           {
-            case NON_CACHEABLE:
-            break;
-            case WB_WA:
-                *descriptor_l1 |= (1 << SECTION_B_SHIFT);
-                break;
-            case WT:
-                *descriptor_l1 |= 1 << SECTION_C_SHIFT;
-                break;
-            case WB_NO_WA:
-                *descriptor_l1 |= (1 << SECTION_B_SHIFT) | (1 << SECTION_C_SHIFT);
-                break;
-        }
-        switch(outer)
-        {
-            case NON_CACHEABLE:
-             break;
-            case WB_WA:
-                *descriptor_l1 |= (1 << SECTION_TEX0_SHIFT);
-                break;
-            case WT:
-                *descriptor_l1 |= 1 << SECTION_TEX1_SHIFT;
-                break;
-            case WB_NO_WA:
-                *descriptor_l1 |= (1 << SECTION_TEX0_SHIFT) | (1 << SECTION_TEX0_SHIFT);
-                break;
-        }
-    }
-
-    return 0;
-}
-
-/** \brief  Set 4k/64k page memory attributes
-
-    The function sets 4k/64k page memory attributes
-
-    \param [out]    descriptor_l2  L2 descriptor.
-    \param [in]               mem  4k/64k page memory type: NORMAL, DEVICE, SHARED_DEVICE, NON_SHARED_DEVICE, STRONGLY_ORDERED
-    \param [in]             outer  Outer cacheability: NON_CACHEABLE, WB_WA, WT, WB_NO_WA,
-    \param [in]             inner  Inner cacheability: NON_CACHEABLE, WB_WA, WT, WB_NO_WA,
-
-    \return          0  
- */
-__STATIC_INLINE int __memory_page(uint32_t *descriptor_l2, mmu_memory_Type mem, mmu_cacheability_Type outer, mmu_cacheability_Type inner, mmu_region_size_Type page)
-{
-    *descriptor_l2 &= PAGE_4K_TEXCB_MASK;
-
-    if (page == PAGE_64k)
-    {
-        //same as section
-        __memory_section(descriptor_l2, mem, outer, inner);
-    }
-    else
-    {
-        if (STRONGLY_ORDERED == mem)
-        {
-            return 0;
-        }
-        else if (SHARED_DEVICE == mem)
-        {
-            *descriptor_l2 |= (1 << PAGE_4K_B_SHIFT);
-        }
-        else if (NON_SHARED_DEVICE == mem)
-        {
-             *descriptor_l2 |= (1 << PAGE_4K_TEX1_SHIFT);
-        }
-        else if (NORMAL == mem)
-        {
-            *descriptor_l2 |= 1 << PAGE_4K_TEX2_SHIFT;
-            switch(inner)
-            {
-                case NON_CACHEABLE:
-                break;
-                case WB_WA:
-                     *descriptor_l2 |= (1 << PAGE_4K_B_SHIFT);
-                     break;
-                case WT:
-                    *descriptor_l2 |= 1 << PAGE_4K_C_SHIFT;
-                     break;
-                case WB_NO_WA:
-                    *descriptor_l2 |= (1 << PAGE_4K_B_SHIFT) | (1 << PAGE_4K_C_SHIFT);
-                    break;
-            }
-            switch(outer)
-            {
-                case NON_CACHEABLE:
-                break;
-                case WB_WA:
-                      *descriptor_l2 |= (1 << PAGE_4K_TEX0_SHIFT);
-                    break;
-                case WT:
-                     *descriptor_l2 |= 1 << PAGE_4K_TEX1_SHIFT;
-                    break;
-                case WB_NO_WA:
-                    *descriptor_l2 |= (1 << PAGE_4K_TEX0_SHIFT) | (1 << PAGE_4K_TEX0_SHIFT);
-                    break;
-            }
-        }
-    }
-
-    return 0;
-}
-
-/** \brief  Create a L1 section descriptor
-
-    The function creates a section descriptor.
-    
-    Assumptions:
-    - 16MB super sections not suported
-    - TEX remap disabled, so memory type and attributes are described directly by bits in the descriptor
-    - Functions always return 0
-
-    \param [out]       descriptor  L1 descriptor
-    \param [out]      descriptor2  L2 descriptor
-    \param [in]               reg  Section attributes
-
-    \return          0  
- */
-__STATIC_INLINE int __get_section_descriptor(uint32_t *descriptor, mmu_region_attributes_Type reg)
-{
-    *descriptor  = 0;
-
-   __memory_section(descriptor, reg.mem_t, reg.outer_norm_t, reg.inner_norm_t);
-   __xn_section(descriptor,reg.xn_t);
-   __domain_section(descriptor, reg.domain);
-   __p_section(descriptor, reg.e_t);
-   __ap_section(descriptor, reg.priv_t, reg.user_t, 1);
-   __shared_section(descriptor,reg.sh_t);
-   __global_section(descriptor,reg.g_t);
-   __secure_section(descriptor,reg.sec_t);
-   *descriptor &= SECTION_MASK;
-   *descriptor |= SECTION_DESCRIPTOR;
-
-   return 0;
-
-}
-
-
-/** \brief  Create a L1 and L2 4k/64k page descriptor
-
-    The function creates a 4k/64k page descriptor.
-    Assumptions:
-    - TEX remap disabled, so memory type and attributes are described directly by bits in the descriptor
-    - Functions always return 0
-
-    \param [out]       descriptor  L1 descriptor
-    \param [out]      descriptor2  L2 descriptor
-    \param [in]               reg  4k/64k page attributes
-
-    \return          0  
- */
-__STATIC_INLINE int __get_page_descriptor(uint32_t *descriptor, uint32_t *descriptor2, mmu_region_attributes_Type reg)
-{
-    *descriptor  = 0;
-    *descriptor2 = 0;
-
-    switch (reg.rg_t)
-    {
-        case PAGE_4k:
-            __memory_page(descriptor2, reg.mem_t, reg.outer_norm_t, reg.inner_norm_t, PAGE_4k);
-            __xn_page(descriptor2, reg.xn_t, PAGE_4k);
-            __domain_page(descriptor, reg.domain);
-            __p_page(descriptor, reg.e_t);
-            __ap_page(descriptor2, reg.priv_t, reg.user_t, 1);
-            __shared_page(descriptor2,reg.sh_t);
-            __global_page(descriptor2,reg.g_t);
-            __secure_page(descriptor,reg.sec_t);
-            *descriptor &= PAGE_L1_MASK;
-            *descriptor |= PAGE_L1_DESCRIPTOR;
-            *descriptor2 &= PAGE_L2_4K_MASK;
-            *descriptor2 |= PAGE_L2_4K_DESC;
-            break;
-
-        case PAGE_64k:
-            __memory_page(descriptor2, reg.mem_t, reg.outer_norm_t, reg.inner_norm_t, PAGE_64k);
-            __xn_page(descriptor2, reg.xn_t, PAGE_64k);
-            __domain_page(descriptor, reg.domain);
-            __p_page(descriptor, reg.e_t);
-            __ap_page(descriptor2, reg.priv_t, reg.user_t, 1);
-            __shared_page(descriptor2,reg.sh_t);
-            __global_page(descriptor2,reg.g_t);
-            __secure_page(descriptor,reg.sec_t);
-            *descriptor &= PAGE_L1_MASK;
-            *descriptor |= PAGE_L1_DESCRIPTOR;
-            *descriptor2 &= PAGE_L2_64K_MASK;
-            *descriptor2 |= PAGE_L2_64K_DESC;
-            break;
-
-        case SECTION:
-            //error
-            break;    
-
-    }
-
-   return 0;
-
-}
-
-/** \brief  Create a 1MB Section
-
-    \param [in]               ttb  Translation table base address
-    \param [in]      base_address  Section base address
-    \param [in]             count  Number of sections to create
-    \param [in]     descriptor_l1  L1 descriptor (region attributes) 
-
- */
-__STATIC_INLINE void __TTSection(uint32_t *ttb, uint32_t base_address, uint32_t count, uint32_t descriptor_l1)
-{
-    uint32_t offset;
-    uint32_t entry;
-    uint32_t i;
-
-    offset = base_address >> 20;
-    entry  = (base_address & 0xFFF00000) | descriptor_l1;
-
-    //4 bytes aligned
-    ttb = ttb + offset;
-
-    for (i = 0; i < count; i++ )
-    {
-        //4 bytes aligned
-       *ttb++ = entry;
-       entry += OFFSET_1M;
-    }
-}
-
-/** \brief  Create a 4k page entry
-
-    \param [in]               ttb  L1 table base address
-    \param [in]      base_address  4k base address
-    \param [in]             count  Number of 4k pages to create
-    \param [in]     descriptor_l1  L1 descriptor (region attributes) 
-    \param [in]            ttb_l2  L2 table base address
-    \param [in]     descriptor_l2  L2 descriptor (region attributes) 
-
- */
-__STATIC_INLINE void __TTPage_4k(uint32_t *ttb, uint32_t base_address, uint32_t count, uint32_t descriptor_l1, uint32_t *ttb_l2, uint32_t descriptor_l2 )
-{
-
-    uint32_t offset, offset2;
-    uint32_t entry, entry2;
-    uint32_t i;
-
-
-    offset = base_address >> 20;
-    entry  = ((int)ttb_l2 & 0xFFFFFC00) | descriptor_l1;
-
-    //4 bytes aligned
-    ttb += offset;
-    //create l1_entry
-    *ttb = entry;
-
-    offset2 = (base_address & 0xff000) >> 12;
-    ttb_l2 += offset2;
-    entry2 = (base_address & 0xFFFFF000) | descriptor_l2;
-    for (i = 0; i < count; i++ )
-    {
-        //4 bytes aligned
-       *ttb_l2++ = entry2;
-       entry2 += OFFSET_4K;
-    }
-}
-
-/** \brief  Create a 64k page entry
-
-    \param [in]               ttb  L1 table base address
-    \param [in]      base_address  64k base address
-    \param [in]             count  Number of 64k pages to create
-    \param [in]     descriptor_l1  L1 descriptor (region attributes) 
-    \param [in]            ttb_l2  L2 table base address
-    \param [in]     descriptor_l2  L2 descriptor (region attributes) 
-
- */
-__STATIC_INLINE void __TTPage_64k(uint32_t *ttb, uint32_t base_address, uint32_t count, uint32_t descriptor_l1, uint32_t *ttb_l2, uint32_t descriptor_l2 )
-{
-    uint32_t offset, offset2;
-    uint32_t entry, entry2;
-    uint32_t i,j;
-
-
-    offset = base_address >> 20;
-    entry  = ((int)ttb_l2 & 0xFFFFFC00) | descriptor_l1;
-
-    //4 bytes aligned
-    ttb += offset;
-    //create l1_entry
-    *ttb = entry;
-
-    offset2 = (base_address & 0xff000) >> 12;
-    ttb_l2 += offset2;
-    entry2 = (base_address & 0xFFFF0000) | descriptor_l2;
-    for (i = 0; i < count; i++ )
-    {
-        //create 16 entries
-        for (j = 0; j < 16; j++)
-            //4 bytes aligned
-            *ttb_l2++ = entry2;
-        entry2 += OFFSET_64K;
-    }
-}
-
-/*@} end of MMU_Functions */
-#endif
-
-#ifdef __cplusplus
-}
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/cmsis-core/src/ext/core_cm0.h
----------------------------------------------------------------------
diff --git a/libs/cmsis-core/src/ext/core_cm0.h b/libs/cmsis-core/src/ext/core_cm0.h
deleted file mode 100644
index dc821ba..0000000
--- a/libs/cmsis-core/src/ext/core_cm0.h
+++ /dev/null
@@ -1,682 +0,0 @@
-/**************************************************************************//**
- * @file     core_cm0.h
- * @brief    CMSIS Cortex-M0 Core Peripheral Access Layer Header File
- * @version  V3.20
- * @date     25. February 2013
- *
- * @note
- *
- ******************************************************************************/
-/* Copyright (c) 2009 - 2013 ARM LIMITED
-
-   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 ARM 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 COPYRIGHT HOLDERS AND CONTRIBUTORS BE
-   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-   POSSIBILITY OF SUCH DAMAGE.
-   ---------------------------------------------------------------------------*/
-
-
-#if defined ( __ICCARM__ )
- #pragma system_include  /* treat file as system include file for MISRA check */
-#endif
-
-#ifdef __cplusplus
- extern "C" {
-#endif
-
-#ifndef __CORE_CM0_H_GENERIC
-#define __CORE_CM0_H_GENERIC
-
-/** \page CMSIS_MISRA_Exceptions  MISRA-C:2004 Compliance Exceptions
-  CMSIS violates the following MISRA-C:2004 rules:
-
-   \li Required Rule 8.5, object/function definition in header file.<br>
-     Function definitions in header files are used to allow 'inlining'.
-
-   \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.<br>
-     Unions are used for effective representation of core registers.
-
-   \li Advisory Rule 19.7, Function-like macro defined.<br>
-     Function-like macros are used to allow more efficient code.
- */
-
-
-/*******************************************************************************
- *                 CMSIS definitions
- ******************************************************************************/
-/** \ingroup Cortex_M0
-  @{
- */
-
-/*  CMSIS CM0 definitions */
-#define __CM0_CMSIS_VERSION_MAIN  (0x03)                                   /*!< [31:16] CMSIS HAL main version   */
-#define __CM0_CMSIS_VERSION_SUB   (0x20)                                   /*!< [15:0]  CMSIS HAL sub version    */
-#define __CM0_CMSIS_VERSION       ((__CM0_CMSIS_VERSION_MAIN << 16) | \
-                                    __CM0_CMSIS_VERSION_SUB          )     /*!< CMSIS HAL version number         */
-
-#define __CORTEX_M                (0x00)                                   /*!< Cortex-M Core                    */
-
-
-#if   defined ( __CC_ARM )
-  #define __ASM            __asm                                      /*!< asm keyword for ARM Compiler          */
-  #define __INLINE         __inline                                   /*!< inline keyword for ARM Compiler       */
-  #define __STATIC_INLINE  static __inline
-
-#elif defined ( __ICCARM__ )
-  #define __ASM            __asm                                      /*!< asm keyword for IAR Compiler          */
-  #define __INLINE         inline                                     /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */
-  #define __STATIC_INLINE  static inline
-
-#elif defined ( __GNUC__ )
-  #define __ASM            __asm                                      /*!< asm keyword for GNU Compiler          */
-  #define __INLINE         inline                                     /*!< inline keyword for GNU Compiler       */
-  #define __STATIC_INLINE  static inline
-
-#elif defined ( __TASKING__ )
-  #define __ASM            __asm                                      /*!< asm keyword for TASKING Compiler      */
-  #define __INLINE         inline                                     /*!< inline keyword for TASKING Compiler   */
-  #define __STATIC_INLINE  static inline
-
-#endif
-
-/** __FPU_USED indicates whether an FPU is used or not. This core does not support an FPU at all
-*/
-#define __FPU_USED       0
-
-#if defined ( __CC_ARM )
-  #if defined __TARGET_FPU_VFP
-    #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
-  #endif
-
-#elif defined ( __ICCARM__ )
-  #if defined __ARMVFP__
-    #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
-  #endif
-
-#elif defined ( __GNUC__ )
-  #if defined (__VFP_FP__) && !defined(__SOFTFP__)
-    #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
-  #endif
-
-#elif defined ( __TASKING__ )
-  #if defined __FPU_VFP__
-    #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
-  #endif
-#endif
-
-#include <stdint.h>                      /* standard types definitions */
-#include <core_cmInstr.h>     /* Core Instruction Access */
-#include <core_cmFunc.h>     /* Core Function Access */
-
-#endif /* __CORE_CM0_H_GENERIC */
-
-#ifndef __CMSIS_GENERIC
-
-#ifndef __CORE_CM0_H_DEPENDANT
-#define __CORE_CM0_H_DEPENDANT
-
-/* check device defines and use defaults */
-#if defined __CHECK_DEVICE_DEFINES
-  #ifndef __CM0_REV
-    #define __CM0_REV               0x0000
-    #warning "__CM0_REV not defined in device header file; using default!"
-  #endif
-
-  #ifndef __NVIC_PRIO_BITS
-    #define __NVIC_PRIO_BITS          2
-    #warning "__NVIC_PRIO_BITS not defined in device header file; using default!"
-  #endif
-
-  #ifndef __Vendor_SysTickConfig
-    #define __Vendor_SysTickConfig    0
-    #warning "__Vendor_SysTickConfig not defined in device header file; using default!"
-  #endif
-#endif
-
-/* IO definitions (access restrictions to peripheral registers) */
-/**
-    \defgroup CMSIS_glob_defs CMSIS Global Defines
-
-    <strong>IO Type Qualifiers</strong> are used
-    \li to specify the access to peripheral variables.
-    \li for automatic generation of peripheral register debug information.
-*/
-#ifdef __cplusplus
-  #define   __I     volatile             /*!< Defines 'read only' permissions                 */
-#else
-  #define   __I     volatile const       /*!< Defines 'read only' permissions                 */
-#endif
-#define     __O     volatile             /*!< Defines 'write only' permissions                */
-#define     __IO    volatile             /*!< Defines 'read / write' permissions              */
-
-/*@} end of group Cortex_M0 */
-
-
-
-/*******************************************************************************
- *                 Register Abstraction
-  Core Register contain:
-  - Core Register
-  - Core NVIC Register
-  - Core SCB Register
-  - Core SysTick Register
- ******************************************************************************/
-/** \defgroup CMSIS_core_register Defines and Type Definitions
-    \brief Type definitions and defines for Cortex-M processor based devices.
-*/
-
-/** \ingroup    CMSIS_core_register
-    \defgroup   CMSIS_CORE  Status and Control Registers
-    \brief  Core Register type definitions.
-  @{
- */
-
-/** \brief  Union type to access the Application Program Status Register (APSR).
- */
-typedef union
-{
-  struct
-  {
-#if (__CORTEX_M != 0x04)
-    uint32_t _reserved0:27;              /*!< bit:  0..26  Reserved                           */
-#else
-    uint32_t _reserved0:16;              /*!< bit:  0..15  Reserved                           */
-    uint32_t GE:4;                       /*!< bit: 16..19  Greater than or Equal flags        */
-    uint32_t _reserved1:7;               /*!< bit: 20..26  Reserved                           */
-#endif
-    uint32_t Q:1;                        /*!< bit:     27  Saturation condition flag          */
-    uint32_t V:1;                        /*!< bit:     28  Overflow condition code flag       */
-    uint32_t C:1;                        /*!< bit:     29  Carry condition code flag          */
-    uint32_t Z:1;                        /*!< bit:     30  Zero condition code flag           */
-    uint32_t N:1;                        /*!< bit:     31  Negative condition code flag       */
-  } b;                                   /*!< Structure used for bit  access                  */
-  uint32_t w;                            /*!< Type      used for word access                  */
-} APSR_Type;
-
-
-/** \brief  Union type to access the Interrupt Program Status Register (IPSR).
- */
-typedef union
-{
-  struct
-  {
-    uint32_t ISR:9;                      /*!< bit:  0.. 8  Exception number                   */
-    uint32_t _reserved0:23;              /*!< bit:  9..31  Reserved                           */
-  } b;                                   /*!< Structure used for bit  access                  */
-  uint32_t w;                            /*!< Type      used for word access                  */
-} IPSR_Type;
-
-
-/** \brief  Union type to access the Special-Purpose Program Status Registers (xPSR).
- */
-typedef union
-{
-  struct
-  {
-    uint32_t ISR:9;                      /*!< bit:  0.. 8  Exception number                   */
-#if (__CORTEX_M != 0x04)
-    uint32_t _reserved0:15;              /*!< bit:  9..23  Reserved                           */
-#else
-    uint32_t _reserved0:7;               /*!< bit:  9..15  Reserved                           */
-    uint32_t GE:4;                       /*!< bit: 16..19  Greater than or Equal flags        */
-    uint32_t _reserved1:4;               /*!< bit: 20..23  Reserved                           */
-#endif
-    uint32_t T:1;                        /*!< bit:     24  Thumb bit        (read 0)          */
-    uint32_t IT:2;                       /*!< bit: 25..26  saved IT state   (read 0)          */
-    uint32_t Q:1;                        /*!< bit:     27  Saturation condition flag          */
-    uint32_t V:1;                        /*!< bit:     28  Overflow condition code flag       */
-    uint32_t C:1;                        /*!< bit:     29  Carry condition code flag          */
-    uint32_t Z:1;                        /*!< bit:     30  Zero condition code flag           */
-    uint32_t N:1;                        /*!< bit:     31  Negative condition code flag       */
-  } b;                                   /*!< Structure used for bit  access                  */
-  uint32_t w;                            /*!< Type      used for word access                  */
-} xPSR_Type;
-
-
-/** \brief  Union type to access the Control Registers (CONTROL).
- */
-typedef union
-{
-  struct
-  {
-    uint32_t nPRIV:1;                    /*!< bit:      0  Execution privilege in Thread mode */
-    uint32_t SPSEL:1;                    /*!< bit:      1  Stack to be used                   */
-    uint32_t FPCA:1;                     /*!< bit:      2  FP extension active flag           */
-    uint32_t _reserved0:29;              /*!< bit:  3..31  Reserved                           */
-  } b;                                   /*!< Structure used for bit  access                  */
-  uint32_t w;                            /*!< Type      used for word access                  */
-} CONTROL_Type;
-
-/*@} end of group CMSIS_CORE */
-
-
-/** \ingroup    CMSIS_core_register
-    \defgroup   CMSIS_NVIC  Nested Vectored Interrupt Controller (NVIC)
-    \brief      Type definitions for the NVIC Registers
-  @{
- */
-
-/** \brief  Structure type to access the Nested Vectored Interrupt Controller (NVIC).
- */
-typedef struct
-{
-  __IO uint32_t ISER[1];                 /*!< Offset: 0x000 (R/W)  Interrupt Set Enable Register           */
-       uint32_t RESERVED0[31];
-  __IO uint32_t ICER[1];                 /*!< Offset: 0x080 (R/W)  Interrupt Clear Enable Register          */
-       uint32_t RSERVED1[31];
-  __IO uint32_t ISPR[1];                 /*!< Offset: 0x100 (R/W)  Interrupt Set Pending Register           */
-       uint32_t RESERVED2[31];
-  __IO uint32_t ICPR[1];                 /*!< Offset: 0x180 (R/W)  Interrupt Clear Pending Register         */
-       uint32_t RESERVED3[31];
-       uint32_t RESERVED4[64];
-  __IO uint32_t IP[8];                   /*!< Offset: 0x300 (R/W)  Interrupt Priority Register              */
-}  NVIC_Type;
-
-/*@} end of group CMSIS_NVIC */
-
-
-/** \ingroup  CMSIS_core_register
-    \defgroup CMSIS_SCB     System Control Block (SCB)
-    \brief      Type definitions for the System Control Block Registers
-  @{
- */
-
-/** \brief  Structure type to access the System Control Block (SCB).
- */
-typedef struct
-{
-  __I  uint32_t CPUID;                   /*!< Offset: 0x000 (R/ )  CPUID Base Register                                   */
-  __IO uint32_t ICSR;                    /*!< Offset: 0x004 (R/W)  Interrupt Control and State Register                  */
-       uint32_t RESERVED0;
-  __IO uint32_t AIRCR;                   /*!< Offset: 0x00C (R/W)  Application Interrupt and Reset Control Register      */
-  __IO uint32_t SCR;                     /*!< Offset: 0x010 (R/W)  System Control Register                               */
-  __IO uint32_t CCR;                     /*!< Offset: 0x014 (R/W)  Configuration Control Register                        */
-       uint32_t RESERVED1;
-  __IO uint32_t SHP[2];                  /*!< Offset: 0x01C (R/W)  System Handlers Priority Registers. [0] is RESERVED   */
-  __IO uint32_t SHCSR;                   /*!< Offset: 0x024 (R/W)  System Handler Control and State Register             */
-} SCB_Type;
-
-/* SCB CPUID Register Definitions */
-#define SCB_CPUID_IMPLEMENTER_Pos          24                                             /*!< SCB CPUID: IMPLEMENTER Position */
-#define SCB_CPUID_IMPLEMENTER_Msk          (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos)          /*!< SCB CPUID: IMPLEMENTER Mask */
-
-#define SCB_CPUID_VARIANT_Pos              20                                             /*!< SCB CPUID: VARIANT Position */
-#define SCB_CPUID_VARIANT_Msk              (0xFUL << SCB_CPUID_VARIANT_Pos)               /*!< SCB CPUID: VARIANT Mask */
-
-#define SCB_CPUID_ARCHITECTURE_Pos         16                                             /*!< SCB CPUID: ARCHITECTURE Position */
-#define SCB_CPUID_ARCHITECTURE_Msk         (0xFUL << SCB_CPUID_ARCHITECTURE_Pos)          /*!< SCB CPUID: ARCHITECTURE Mask */
-
-#define SCB_CPUID_PARTNO_Pos                4                                             /*!< SCB CPUID: PARTNO Position */
-#define SCB_CPUID_PARTNO_Msk               (0xFFFUL << SCB_CPUID_PARTNO_Pos)              /*!< SCB CPUID: PARTNO Mask */
-
-#define SCB_CPUID_REVISION_Pos              0                                             /*!< SCB CPUID: REVISION Position */
-#define SCB_CPUID_REVISION_Msk             (0xFUL << SCB_CPUID_REVISION_Pos)              /*!< SCB CPUID: REVISION Mask */
-
-/* SCB Interrupt Control State Register Definitions */
-#define SCB_ICSR_NMIPENDSET_Pos            31                                             /*!< SCB ICSR: NMIPENDSET Position */
-#define SCB_ICSR_NMIPENDSET_Msk            (1UL << SCB_ICSR_NMIPENDSET_Pos)               /*!< SCB ICSR: NMIPENDSET Mask */
-
-#define SCB_ICSR_PENDSVSET_Pos             28                                             /*!< SCB ICSR: PENDSVSET Position */
-#define SCB_ICSR_PENDSVSET_Msk             (1UL << SCB_ICSR_PENDSVSET_Pos)                /*!< SCB ICSR: PENDSVSET Mask */
-
-#define SCB_ICSR_PENDSVCLR_Pos             27                                             /*!< SCB ICSR: PENDSVCLR Position */
-#define SCB_ICSR_PENDSVCLR_Msk             (1UL << SCB_ICSR_PENDSVCLR_Pos)                /*!< SCB ICSR: PENDSVCLR Mask */
-
-#define SCB_ICSR_PENDSTSET_Pos             26                                             /*!< SCB ICSR: PENDSTSET Position */
-#define SCB_ICSR_PENDSTSET_Msk             (1UL << SCB_ICSR_PENDSTSET_Pos)                /*!< SCB ICSR: PENDSTSET Mask */
-
-#define SCB_ICSR_PENDSTCLR_Pos             25                                             /*!< SCB ICSR: PENDSTCLR Position */
-#define SCB_ICSR_PENDSTCLR_Msk             (1UL << SCB_ICSR_PENDSTCLR_Pos)                /*!< SCB ICSR: PENDSTCLR Mask */
-
-#define SCB_ICSR_ISRPREEMPT_Pos            23                                             /*!< SCB ICSR: ISRPREEMPT Position */
-#define SCB_ICSR_ISRPREEMPT_Msk            (1UL << SCB_ICSR_ISRPREEMPT_Pos)               /*!< SCB ICSR: ISRPREEMPT Mask */
-
-#define SCB_ICSR_ISRPENDING_Pos            22                                             /*!< SCB ICSR: ISRPENDING Position */
-#define SCB_ICSR_ISRPENDING_Msk            (1UL << SCB_ICSR_ISRPENDING_Pos)               /*!< SCB ICSR: ISRPENDING Mask */
-
-#define SCB_ICSR_VECTPENDING_Pos           12                                             /*!< SCB ICSR: VECTPENDING Position */
-#define SCB_ICSR_VECTPENDING_Msk           (0x1FFUL << SCB_ICSR_VECTPENDING_Pos)          /*!< SCB ICSR: VECTPENDING Mask */
-
-#define SCB_ICSR_VECTACTIVE_Pos             0                                             /*!< SCB ICSR: VECTACTIVE Position */
-#define SCB_ICSR_VECTACTIVE_Msk            (0x1FFUL << SCB_ICSR_VECTACTIVE_Pos)           /*!< SCB ICSR: VECTACTIVE Mask */
-
-/* SCB Application Interrupt and Reset Control Register Definitions */
-#define SCB_AIRCR_VECTKEY_Pos              16                                             /*!< SCB AIRCR: VECTKEY Position */
-#define SCB_AIRCR_VECTKEY_Msk              (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos)            /*!< SCB AIRCR: VECTKEY Mask */
-
-#define SCB_AIRCR_VECTKEYSTAT_Pos          16                                             /*!< SCB AIRCR: VECTKEYSTAT Position */
-#define SCB_AIRCR_VECTKEYSTAT_Msk          (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos)        /*!< SCB AIRCR: VECTKEYSTAT Mask */
-
-#define SCB_AIRCR_ENDIANESS_Pos            15                                             /*!< SCB AIRCR: ENDIANESS Position */
-#define SCB_AIRCR_ENDIANESS_Msk            (1UL << SCB_AIRCR_ENDIANESS_Pos)               /*!< SCB AIRCR: ENDIANESS Mask */
-
-#define SCB_AIRCR_SYSRESETREQ_Pos           2                                             /*!< SCB AIRCR: SYSRESETREQ Position */
-#define SCB_AIRCR_SYSRESETREQ_Msk          (1UL << SCB_AIRCR_SYSRESETREQ_Pos)             /*!< SCB AIRCR: SYSRESETREQ Mask */
-
-#define SCB_AIRCR_VECTCLRACTIVE_Pos         1                                             /*!< SCB AIRCR: VECTCLRACTIVE Position */
-#define SCB_AIRCR_VECTCLRACTIVE_Msk        (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos)           /*!< SCB AIRCR: VECTCLRACTIVE Mask */
-
-/* SCB System Control Register Definitions */
-#define SCB_SCR_SEVONPEND_Pos               4                                             /*!< SCB SCR: SEVONPEND Position */
-#define SCB_SCR_SEVONPEND_Msk              (1UL << SCB_SCR_SEVONPEND_Pos)                 /*!< SCB SCR: SEVONPEND Mask */
-
-#define SCB_SCR_SLEEPDEEP_Pos               2                                             /*!< SCB SCR: SLEEPDEEP Position */
-#define SCB_SCR_SLEEPDEEP_Msk              (1UL << SCB_SCR_SLEEPDEEP_Pos)                 /*!< SCB SCR: SLEEPDEEP Mask */
-
-#define SCB_SCR_SLEEPONEXIT_Pos             1                                             /*!< SCB SCR: SLEEPONEXIT Position */
-#define SCB_SCR_SLEEPONEXIT_Msk            (1UL << SCB_SCR_SLEEPONEXIT_Pos)               /*!< SCB SCR: SLEEPONEXIT Mask */
-
-/* SCB Configuration Control Register Definitions */
-#define SCB_CCR_STKALIGN_Pos                9                                             /*!< SCB CCR: STKALIGN Position */
-#define SCB_CCR_STKALIGN_Msk               (1UL << SCB_CCR_STKALIGN_Pos)                  /*!< SCB CCR: STKALIGN Mask */
-
-#define SCB_CCR_UNALIGN_TRP_Pos             3                                             /*!< SCB CCR: UNALIGN_TRP Position */
-#define SCB_CCR_UNALIGN_TRP_Msk            (1UL << SCB_CCR_UNALIGN_TRP_Pos)               /*!< SCB CCR: UNALIGN_TRP Mask */
-
-/* SCB System Handler Control and State Register Definitions */
-#define SCB_SHCSR_SVCALLPENDED_Pos         15                                             /*!< SCB SHCSR: SVCALLPENDED Position */
-#define SCB_SHCSR_SVCALLPENDED_Msk         (1UL << SCB_SHCSR_SVCALLPENDED_Pos)            /*!< SCB SHCSR: SVCALLPENDED Mask */
-
-/*@} end of group CMSIS_SCB */
-
-
-/** \ingroup  CMSIS_core_register
-    \defgroup CMSIS_SysTick     System Tick Timer (SysTick)
-    \brief      Type definitions for the System Timer Registers.
-  @{
- */
-
-/** \brief  Structure type to access the System Timer (SysTick).
- */
-typedef struct
-{
-  __IO uint32_t CTRL;                    /*!< Offset: 0x000 (R/W)  SysTick Control and Status Register */
-  __IO uint32_t LOAD;                    /*!< Offset: 0x004 (R/W)  SysTick Reload Value Register       */
-  __IO uint32_t VAL;                     /*!< Offset: 0x008 (R/W)  SysTick Current Value Register      */
-  __I  uint32_t CALIB;                   /*!< Offset: 0x00C (R/ )  SysTick Calibration Register        */
-} SysTick_Type;
-
-/* SysTick Control / Status Register Definitions */
-#define SysTick_CTRL_COUNTFLAG_Pos         16                                             /*!< SysTick CTRL: COUNTFLAG Position */
-#define SysTick_CTRL_COUNTFLAG_Msk         (1UL << SysTick_CTRL_COUNTFLAG_Pos)            /*!< SysTick CTRL: COUNTFLAG Mask */
-
-#define SysTick_CTRL_CLKSOURCE_Pos          2                                             /*!< SysTick CTRL: CLKSOURCE Position */
-#define SysTick_CTRL_CLKSOURCE_Msk         (1UL << SysTick_CTRL_CLKSOURCE_Pos)            /*!< SysTick CTRL: CLKSOURCE Mask */
-
-#define SysTick_CTRL_TICKINT_Pos            1                                             /*!< SysTick CTRL: TICKINT Position */
-#define SysTick_CTRL_TICKINT_Msk           (1UL << SysTick_CTRL_TICKINT_Pos)              /*!< SysTick CTRL: TICKINT Mask */
-
-#define SysTick_CTRL_ENABLE_Pos             0                                             /*!< SysTick CTRL: ENABLE Position */
-#define SysTick_CTRL_ENABLE_Msk            (1UL << SysTick_CTRL_ENABLE_Pos)               /*!< SysTick CTRL: ENABLE Mask */
-
-/* SysTick Reload Register Definitions */
-#define SysTick_LOAD_RELOAD_Pos             0                                             /*!< SysTick LOAD: RELOAD Position */
-#define SysTick_LOAD_RELOAD_Msk            (0xFFFFFFUL << SysTick_LOAD_RELOAD_Pos)        /*!< SysTick LOAD: RELOAD Mask */
-
-/* SysTick Current Register Definitions */
-#define SysTick_VAL_CURRENT_Pos             0                                             /*!< SysTick VAL: CURRENT Position */
-#define SysTick_VAL_CURRENT_Msk            (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos)        /*!< SysTick VAL: CURRENT Mask */
-
-/* SysTick Calibration Register Definitions */
-#define SysTick_CALIB_NOREF_Pos            31                                             /*!< SysTick CALIB: NOREF Position */
-#define SysTick_CALIB_NOREF_Msk            (1UL << SysTick_CALIB_NOREF_Pos)               /*!< SysTick CALIB: NOREF Mask */
-
-#define SysTick_CALIB_SKEW_Pos             30                                             /*!< SysTick CALIB: SKEW Position */
-#define SysTick_CALIB_SKEW_Msk             (1UL << SysTick_CALIB_SKEW_Pos)                /*!< SysTick CALIB: SKEW Mask */
-
-#define SysTick_CALIB_TENMS_Pos             0                                             /*!< SysTick CALIB: TENMS Position */
-#define SysTick_CALIB_TENMS_Msk            (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos)        /*!< SysTick CALIB: TENMS Mask */
-
-/*@} end of group CMSIS_SysTick */
-
-
-/** \ingroup  CMSIS_core_register
-    \defgroup CMSIS_CoreDebug       Core Debug Registers (CoreDebug)
-    \brief      Cortex-M0 Core Debug Registers (DCB registers, SHCSR, and DFSR)
-                are only accessible over DAP and not via processor. Therefore
-                they are not covered by the Cortex-M0 header file.
-  @{
- */
-/*@} end of group CMSIS_CoreDebug */
-
-
-/** \ingroup    CMSIS_core_register
-    \defgroup   CMSIS_core_base     Core Definitions
-    \brief      Definitions for base addresses, unions, and structures.
-  @{
- */
-
-/* Memory mapping of Cortex-M0 Hardware */
-#define SCS_BASE            (0xE000E000UL)                            /*!< System Control Space Base Address */
-#define SysTick_BASE        (SCS_BASE +  0x0010UL)                    /*!< SysTick Base Address              */
-#define NVIC_BASE           (SCS_BASE +  0x0100UL)                    /*!< NVIC Base Address                 */
-#define SCB_BASE            (SCS_BASE +  0x0D00UL)                    /*!< System Control Block Base Address */
-
-#define SCB                 ((SCB_Type       *)     SCB_BASE      )   /*!< SCB configuration struct           */
-#define SysTick             ((SysTick_Type   *)     SysTick_BASE  )   /*!< SysTick configuration struct       */
-#define NVIC                ((NVIC_Type      *)     NVIC_BASE     )   /*!< NVIC configuration struct          */
-
-
-/*@} */
-
-
-
-/*******************************************************************************
- *                Hardware Abstraction Layer
-  Core Function Interface contains:
-  - Core NVIC Functions
-  - Core SysTick Functions
-  - Core Register Access Functions
- ******************************************************************************/
-/** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference
-*/
-
-
-
-/* ##########################   NVIC functions  #################################### */
-/** \ingroup  CMSIS_Core_FunctionInterface
-    \defgroup CMSIS_Core_NVICFunctions NVIC Functions
-    \brief      Functions that manage interrupts and exceptions via the NVIC.
-    @{
- */
-
-/* Interrupt Priorities are WORD accessible only under ARMv6M                   */
-/* The following MACROS handle generation of the register offset and byte masks */
-#define _BIT_SHIFT(IRQn)         (  (((uint32_t)(IRQn)       )    &  0x03) * 8 )
-#define _SHP_IDX(IRQn)           ( ((((uint32_t)(IRQn) & 0x0F)-8) >>    2)     )
-#define _IP_IDX(IRQn)            (   ((uint32_t)(IRQn)            >>    2)     )
-
-
-/** \brief  Enable External Interrupt
-
-    The function enables a device-specific interrupt in the NVIC interrupt controller.
-
-    \param [in]      IRQn  External interrupt number. Value cannot be negative.
- */
-__STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn)
-{
-  NVIC->ISER[0] = (1 << ((uint32_t)(IRQn) & 0x1F));
-}
-
-
-/** \brief  Disable External Interrupt
-
-    The function disables a device-specific interrupt in the NVIC interrupt controller.
-
-    \param [in]      IRQn  External interrupt number. Value cannot be negative.
- */
-__STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn)
-{
-  NVIC->ICER[0] = (1 << ((uint32_t)(IRQn) & 0x1F));
-}
-
-
-/** \brief  Get Pending Interrupt
-
-    The function reads the pending register in the NVIC and returns the pending bit
-    for the specified interrupt.
-
-    \param [in]      IRQn  Interrupt number.
-
-    \return             0  Interrupt status is not pending.
-    \return             1  Interrupt status is pending.
- */
-__STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn)
-{
-  return((uint32_t) ((NVIC->ISPR[0] & (1 << ((uint32_t)(IRQn) & 0x1F)))?1:0));
-}
-
-
-/** \brief  Set Pending Interrupt
-
-    The function sets the pending bit of an external interrupt.
-
-    \param [in]      IRQn  Interrupt number. Value cannot be negative.
- */
-__STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn)
-{
-  NVIC->ISPR[0] = (1 << ((uint32_t)(IRQn) & 0x1F));
-}
-
-
-/** \brief  Clear Pending Interrupt
-
-    The function clears the pending bit of an external interrupt.
-
-    \param [in]      IRQn  External interrupt number. Value cannot be negative.
- */
-__STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn)
-{
-  NVIC->ICPR[0] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* Clear pending interrupt */
-}
-
-
-/** \brief  Set Interrupt Priority
-
-    The function sets the priority of an interrupt.
-
-    \note The priority cannot be set for every core interrupt.
-
-    \param [in]      IRQn  Interrupt number.
-    \param [in]  priority  Priority to set.
- */
-__STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority)
-{
-  if(IRQn < 0) {
-    SCB->SHP[_SHP_IDX(IRQn)] = (SCB->SHP[_SHP_IDX(IRQn)] & ~(0xFF << _BIT_SHIFT(IRQn))) |
-        (((priority << (8 - __NVIC_PRIO_BITS)) & 0xFF) << _BIT_SHIFT(IRQn)); }
-  else {
-    NVIC->IP[_IP_IDX(IRQn)] = (NVIC->IP[_IP_IDX(IRQn)] & ~(0xFF << _BIT_SHIFT(IRQn))) |
-        (((priority << (8 - __NVIC_PRIO_BITS)) & 0xFF) << _BIT_SHIFT(IRQn)); }
-}
-
-
-/** \brief  Get Interrupt Priority
-
-    The function reads the priority of an interrupt. The interrupt
-    number can be positive to specify an external (device specific)
-    interrupt, or negative to specify an internal (core) interrupt.
-
-
-    \param [in]   IRQn  Interrupt number.
-    \return             Interrupt Priority. Value is aligned automatically to the implemented
-                        priority bits of the microcontroller.
- */
-__STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn)
-{
-
-  if(IRQn < 0) {
-    return((uint32_t)(((SCB->SHP[_SHP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & 0xFF) >> (8 - __NVIC_PRIO_BITS)));  } /* get priority for Cortex-M0 system interrupts */
-  else {
-    return((uint32_t)(((NVIC->IP[ _IP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & 0xFF) >> (8 - __NVIC_PRIO_BITS)));  } /* get priority for device specific interrupts  */
-}
-
-
-/** \brief  System Reset
-
-    The function initiates a system reset request to reset the MCU.
- */
-__STATIC_INLINE void NVIC_SystemReset(void)
-{
-  __DSB();                                                     /* Ensure all outstanding memory accesses included
-                                                                  buffered write are completed before reset */
-  SCB->AIRCR  = ((0x5FA << SCB_AIRCR_VECTKEY_Pos)      |
-                 SCB_AIRCR_SYSRESETREQ_Msk);
-  __DSB();                                                     /* Ensure completion of memory access */
-  while(1);                                                    /* wait until reset */
-}
-
-/*@} end of CMSIS_Core_NVICFunctions */
-
-
-
-/* ##################################    SysTick function  ############################################ */
-/** \ingroup  CMSIS_Core_FunctionInterface
-    \defgroup CMSIS_Core_SysTickFunctions SysTick Functions
-    \brief      Functions that configure the System.
-  @{
- */
-
-#if (__Vendor_SysTickConfig == 0)
-
-/** \brief  System Tick Configuration
-
-    The function initializes the System Timer and its interrupt, and starts the System Tick Timer.
-    Counter is in free running mode to generate periodic interrupts.
-
-    \param [in]  ticks  Number of ticks between two interrupts.
-
-    \return          0  Function succeeded.
-    \return          1  Function failed.
-
-    \note     When the variable <b>__Vendor_SysTickConfig</b> is set to 1, then the
-    function <b>SysTick_Config</b> is not included. In this case, the file <b><i>device</i>.h</b>
-    must contain a vendor-specific implementation of this function.
-
- */
-__STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks)
-{
-  if ((ticks - 1) > SysTick_LOAD_RELOAD_Msk)  return (1);      /* Reload value impossible */
-
-  SysTick->LOAD  = ticks - 1;                                  /* set reload register */
-  NVIC_SetPriority (SysTick_IRQn, (1<<__NVIC_PRIO_BITS) - 1);  /* set Priority for Systick Interrupt */
-  SysTick->VAL   = 0;                                          /* Load the SysTick Counter Value */
-  SysTick->CTRL  = SysTick_CTRL_CLKSOURCE_Msk |
-                   SysTick_CTRL_TICKINT_Msk   |
-                   SysTick_CTRL_ENABLE_Msk;                    /* Enable SysTick IRQ and SysTick Timer */
-  return (0);                                                  /* Function successful */
-}
-
-#endif
-
-/*@} end of CMSIS_Core_SysTickFunctions */
-
-
-
-
-#endif /* __CORE_CM0_H_DEPENDANT */
-
-#endif /* __CMSIS_GENERIC */
-
-#ifdef __cplusplus
-}
-#endif


[45/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/encoding/tinycbor/include/tinycbor/cbor.h
----------------------------------------------------------------------
diff --git a/encoding/tinycbor/include/tinycbor/cbor.h b/encoding/tinycbor/include/tinycbor/cbor.h
new file mode 100644
index 0000000..f78e4af
--- /dev/null
+++ b/encoding/tinycbor/include/tinycbor/cbor.h
@@ -0,0 +1,479 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 Intel Corporation
+**
+** Permission is hereby granted, free of charge, to any person obtaining a copy
+** of this software and associated documentation files (the "Software"), to deal
+** in the Software without restriction, including without limitation the rights
+** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+** copies of the Software, and to permit persons to whom the Software is
+** furnished to do so, subject to the following conditions:
+**
+** The above copyright notice and this permission notice shall be included in
+** all copies or substantial portions of the Software.
+**
+** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+** THE SOFTWARE.
+**
+****************************************************************************/
+
+#ifndef CBOR_H
+#define CBOR_H
+
+#include <assert.h>
+#include <limits.h>
+#include <stddef.h>
+#include <stdint.h>
+#include <string.h>
+#include <stdio.h>
+
+#ifdef __cplusplus
+extern "C" {
+#else
+#include <stdbool.h>
+#endif
+
+#ifndef SIZE_MAX
+/* Some systems fail to define SIZE_MAX in <stdint.h>, even though C99 requires it...
+ * Conversion from signed to unsigned is defined in 6.3.1.3 (Signed and unsigned integers) p2,
+ * which says: "the value is converted by repeatedly adding or subtracting one more than the
+ * maximum value that can be represented in the new type until the value is in the range of the
+ * new type."
+ * So -1 gets converted to size_t by adding SIZE_MAX + 1, which results in SIZE_MAX.
+ */
+#  define SIZE_MAX ((size_t)-1)
+#endif
+
+#ifndef CBOR_API
+#  define CBOR_API
+#endif
+#ifndef CBOR_PRIVATE_API
+#  define CBOR_PRIVATE_API
+#endif
+#ifndef CBOR_INLINE_API
+#  if defined(__cplusplus)
+#    define CBOR_INLINE inline
+#    define CBOR_INLINE_API inline
+#  else
+#    define CBOR_INLINE_API static CBOR_INLINE
+#    if defined(_MSC_VER)
+#      define CBOR_INLINE __inline
+#    elif defined(__GNUC__)
+#      define CBOR_INLINE __inline__
+#    elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
+#      define CBOR_INLINE inline
+#    else
+#      define CBOR_INLINE
+#    endif
+#  endif
+#endif
+
+typedef enum CborType {
+    CborIntegerType     = 0x00,
+    CborByteStringType  = 0x40,
+    CborTextStringType  = 0x60,
+    CborArrayType       = 0x80,
+    CborMapType         = 0xa0,
+    CborTagType         = 0xc0,
+    CborSimpleType      = 0xe0,
+    CborBooleanType     = 0xf5,
+    CborNullType        = 0xf6,
+    CborUndefinedType   = 0xf7,
+    CborHalfFloatType   = 0xf9,
+    CborFloatType       = 0xfa,
+    CborDoubleType      = 0xfb,
+
+    CborInvalidType     = 0xff              /* equivalent to the break byte, so it will never be used */
+} CborType;
+
+typedef uint64_t CborTag;
+typedef enum CborKnownTags {
+    CborDateTimeStringTag          = 0,        /* RFC 3339 format: YYYY-MM-DD hh:mm:ss+zzzz */
+    CborUnixTime_tTag              = 1,
+    CborPositiveBignumTag          = 2,
+    CborNegativeBignumTag          = 3,
+    CborDecimalTag                 = 4,
+    CborBigfloatTag                = 5,
+    CborExpectedBase64urlTag       = 21,
+    CborExpectedBase64Tag          = 22,
+    CborExpectedBase16Tag          = 23,
+    CborUriTag                     = 32,
+    CborBase64urlTag               = 33,
+    CborBase64Tag                  = 34,
+    CborRegularExpressionTag       = 35,
+    CborMimeMessageTag             = 36,       /* RFC 2045-2047 */
+    CborSignatureTag               = 55799
+} CborKnownTags;
+
+/* Error API */
+
+typedef enum CborError {
+    CborNoError = 0,
+
+    /* errors in all modes */
+    CborUnknownError,
+    CborErrorUnknownLength,         /* request for length in array, map, or string with indeterminate length */
+    CborErrorAdvancePastEOF,
+    CborErrorIO,
+
+    /* parser errors streaming errors */
+    CborErrorGarbageAtEnd = 256,
+    CborErrorUnexpectedEOF,
+    CborErrorUnexpectedBreak,
+    CborErrorUnknownType,           /* can only heppen in major type 7 */
+    CborErrorIllegalType,           /* type not allowed here */
+    CborErrorIllegalNumber,
+    CborErrorIllegalSimpleType,     /* types of value less than 32 encoded in two bytes */
+
+    /* parser errors in strict mode parsing only */
+    CborErrorUnknownSimpleType = 512,
+    CborErrorUnknownTag,
+    CborErrorInappropriateTagForType,
+    CborErrorDuplicateObjectKeys,
+    CborErrorInvalidUtf8TextString,
+
+    /* encoder errors */
+    CborErrorTooManyItems = 768,
+    CborErrorTooFewItems,
+
+    /* internal implementation errors */
+    CborErrorDataTooLarge = 1024,
+    CborErrorNestingTooDeep,
+    CborErrorUnsupportedType,
+
+    /* errors in converting to JSON */
+    CborErrorJsonObjectKeyIsAggregate,
+    CborErrorJsonObjectKeyNotString,
+    CborErrorJsonNotImplemented,
+
+    CborErrorOutOfMemory = ~0U / 2 + 1,
+    CborErrorInternalError = ~0U
+} CborError;
+
+CBOR_API const char *cbor_error_string(CborError error);
+
+/* Encoder API */
+struct CborEncoder
+{
+    union {
+        uint8_t *ptr;
+        ptrdiff_t bytes_needed;
+    };
+    const uint8_t *end;
+    size_t added;
+    int flags;
+};
+typedef struct CborEncoder CborEncoder;
+
+static const size_t CborIndefiniteLength = SIZE_MAX;
+
+CBOR_API void cbor_encoder_init(CborEncoder *encoder, uint8_t *buffer, size_t size, int flags);
+CBOR_API CborError cbor_encode_uint(CborEncoder *encoder, uint64_t value);
+CBOR_API CborError cbor_encode_int(CborEncoder *encoder, int64_t value);
+CBOR_API CborError cbor_encode_negative_int(CborEncoder *encoder, uint64_t absolute_value);
+CBOR_API CborError cbor_encode_simple_value(CborEncoder *encoder, uint8_t value);
+CBOR_API CborError cbor_encode_tag(CborEncoder *encoder, CborTag tag);
+CBOR_API CborError cbor_encode_text_string(CborEncoder *encoder, const char *string, size_t length);
+CBOR_INLINE_API CborError cbor_encode_text_stringz(CborEncoder *encoder, const char *string)
+{ return cbor_encode_text_string(encoder, string, strlen(string)); }
+CBOR_API CborError cbor_encode_byte_string(CborEncoder *encoder, const uint8_t *string, size_t length);
+CBOR_API CborError cbor_encode_floating_point(CborEncoder *encoder, CborType fpType, const void *value);
+
+CBOR_INLINE_API CborError cbor_encode_boolean(CborEncoder *encoder, bool value)
+{ return cbor_encode_simple_value(encoder, (int)value - 1 + (CborBooleanType & 0x1f)); }
+CBOR_INLINE_API CborError cbor_encode_null(CborEncoder *encoder)
+{ return cbor_encode_simple_value(encoder, CborNullType & 0x1f); }
+CBOR_INLINE_API CborError cbor_encode_undefined(CborEncoder *encoder)
+{ return cbor_encode_simple_value(encoder, CborUndefinedType & 0x1f); }
+
+CBOR_INLINE_API CborError cbor_encode_half_float(CborEncoder *encoder, const void *value)
+{ return cbor_encode_floating_point(encoder, CborHalfFloatType, value); }
+CBOR_INLINE_API CborError cbor_encode_float(CborEncoder *encoder, float value)
+{ return cbor_encode_floating_point(encoder, CborFloatType, &value); }
+CBOR_INLINE_API CborError cbor_encode_double(CborEncoder *encoder, double value)
+{ return cbor_encode_floating_point(encoder, CborDoubleType, &value); }
+
+CBOR_API CborError cbor_encoder_create_array(CborEncoder *encoder, CborEncoder *arrayEncoder, size_t length);
+CBOR_API CborError cbor_encoder_create_map(CborEncoder *encoder, CborEncoder *mapEncoder, size_t length);
+CBOR_API CborError cbor_encoder_close_container(CborEncoder *encoder, const CborEncoder *containerEncoder);
+CBOR_API CborError cbor_encoder_close_container_checked(CborEncoder *encoder, const CborEncoder *containerEncoder);
+
+CBOR_INLINE_API size_t cbor_encoder_get_buffer_size(const CborEncoder *encoder, const uint8_t *buffer)
+{
+    return (size_t)(encoder->ptr - buffer);
+}
+
+CBOR_INLINE_API size_t cbor_encoder_get_extra_bytes_needed(const CborEncoder *encoder)
+{
+    return encoder->end ? 0 : (size_t)encoder->bytes_needed;
+}
+
+/* Parser API */
+
+enum CborParserIteratorFlags
+{
+    CborIteratorFlag_IntegerValueTooLarge   = 0x01,
+    CborIteratorFlag_NegativeInteger        = 0x02,
+    CborIteratorFlag_UnknownLength          = 0x04,
+    CborIteratorFlag_ContainerIsMap         = 0x20
+};
+
+struct CborParser
+{
+    const uint8_t *end;
+    int flags;
+};
+typedef struct CborParser CborParser;
+
+struct CborValue
+{
+    const CborParser *parser;
+    const uint8_t *ptr;
+    uint32_t remaining;
+    uint16_t extra;
+    uint8_t type;
+    uint8_t flags;
+};
+typedef struct CborValue CborValue;
+
+CBOR_API CborError cbor_parser_init(const uint8_t *buffer, size_t size, int flags, CborParser *parser, CborValue *it);
+
+CBOR_INLINE_API bool cbor_value_at_end(const CborValue *it)
+{ return it->remaining == 0; }
+CBOR_INLINE_API const uint8_t *cbor_value_get_next_byte(const CborValue *it)
+{ return it->ptr; }
+CBOR_API CborError cbor_value_advance_fixed(CborValue *it);
+CBOR_API CborError cbor_value_advance(CborValue *it);
+CBOR_INLINE_API bool cbor_value_is_container(const CborValue *it)
+{ return it->type == CborArrayType || it->type == CborMapType; }
+CBOR_API CborError cbor_value_enter_container(const CborValue *it, CborValue *recursed);
+CBOR_API CborError cbor_value_leave_container(CborValue *it, const CborValue *recursed);
+
+CBOR_PRIVATE_API uint64_t _cbor_value_decode_int64_internal(const CborValue *value);
+CBOR_INLINE_API uint64_t _cbor_value_extract_int64_helper(const CborValue *value)
+{
+    return value->flags & CborIteratorFlag_IntegerValueTooLarge ?
+                _cbor_value_decode_int64_internal(value) : value->extra;
+}
+
+CBOR_INLINE_API bool cbor_value_is_valid(const CborValue *value)
+{ return value && value->type != CborInvalidType; }
+CBOR_INLINE_API CborType cbor_value_get_type(const CborValue *value)
+{ return (CborType)value->type; }
+
+/* Null & undefined type */
+CBOR_INLINE_API bool cbor_value_is_null(const CborValue *value)
+{ return value->type == CborNullType; }
+CBOR_INLINE_API bool cbor_value_is_undefined(const CborValue *value)
+{ return value->type == CborUndefinedType; }
+
+/* Booleans */
+CBOR_INLINE_API bool cbor_value_is_boolean(const CborValue *value)
+{ return value->type == CborBooleanType; }
+CBOR_INLINE_API CborError cbor_value_get_boolean(const CborValue *value, bool *result)
+{
+    assert(cbor_value_is_boolean(value));
+    *result = !!value->extra;
+    return CborNoError;
+}
+
+/* Simple types */
+CBOR_INLINE_API bool cbor_value_is_simple_type(const CborValue *value)
+{ return value->type == CborSimpleType; }
+CBOR_INLINE_API CborError cbor_value_get_simple_type(const CborValue *value, uint8_t *result)
+{
+    assert(cbor_value_is_simple_type(value));
+    *result = (uint8_t)value->extra;
+    return CborNoError;
+}
+
+/* Integers */
+CBOR_INLINE_API bool cbor_value_is_integer(const CborValue *value)
+{ return value->type == CborIntegerType; }
+CBOR_INLINE_API bool cbor_value_is_unsigned_integer(const CborValue *value)
+{ return cbor_value_is_integer(value) && (value->flags & CborIteratorFlag_NegativeInteger) == 0; }
+CBOR_INLINE_API bool cbor_value_is_negative_integer(const CborValue *value)
+{ return cbor_value_is_integer(value) && (value->flags & CborIteratorFlag_NegativeInteger); }
+
+CBOR_INLINE_API CborError cbor_value_get_raw_integer(const CborValue *value, uint64_t *result)
+{
+    assert(cbor_value_is_integer(value));
+    *result = _cbor_value_extract_int64_helper(value);
+    return CborNoError;
+}
+
+CBOR_INLINE_API CborError cbor_value_get_uint64(const CborValue *value, uint64_t *result)
+{
+    assert(cbor_value_is_unsigned_integer(value));
+    *result = _cbor_value_extract_int64_helper(value);
+    return CborNoError;
+}
+
+CBOR_INLINE_API CborError cbor_value_get_int64(const CborValue *value, int64_t *result)
+{
+    assert(cbor_value_is_integer(value));
+    *result = (int64_t) _cbor_value_extract_int64_helper(value);
+    if (value->flags & CborIteratorFlag_NegativeInteger)
+        *result = -*result - 1;
+    return CborNoError;
+}
+
+CBOR_INLINE_API CborError cbor_value_get_int(const CborValue *value, int *result)
+{
+    assert(cbor_value_is_integer(value));
+    *result = (int) _cbor_value_extract_int64_helper(value);
+    if (value->flags & CborIteratorFlag_NegativeInteger)
+        *result = -*result - 1;
+    return CborNoError;
+}
+
+CBOR_API CborError cbor_value_get_int64_checked(const CborValue *value, int64_t *result);
+CBOR_API CborError cbor_value_get_int_checked(const CborValue *value, int *result);
+
+CBOR_INLINE_API bool cbor_value_is_length_known(const CborValue *value)
+{ return (value->flags & CborIteratorFlag_UnknownLength) == 0; }
+
+/* Tags */
+CBOR_INLINE_API bool cbor_value_is_tag(const CborValue *value)
+{ return value->type == CborTagType; }
+CBOR_INLINE_API CborError cbor_value_get_tag(const CborValue *value, CborTag *result)
+{
+    assert(cbor_value_is_tag(value));
+    *result = _cbor_value_extract_int64_helper(value);
+    return CborNoError;
+}
+CBOR_API CborError cbor_value_skip_tag(CborValue *it);
+
+/* Strings */
+CBOR_INLINE_API bool cbor_value_is_byte_string(const CborValue *value)
+{ return value->type == CborByteStringType; }
+CBOR_INLINE_API bool cbor_value_is_text_string(const CborValue *value)
+{ return value->type == CborTextStringType; }
+
+CBOR_INLINE_API CborError cbor_value_get_string_length(const CborValue *value, size_t *length)
+{
+    assert(cbor_value_is_byte_string(value) || cbor_value_is_text_string(value));
+    if (!cbor_value_is_length_known(value))
+        return CborErrorUnknownLength;
+    uint64_t v = _cbor_value_extract_int64_helper(value);
+    *length = v;
+    if (*length != v)
+        return CborErrorDataTooLarge;
+    return CborNoError;
+}
+
+CBOR_PRIVATE_API CborError _cbor_value_copy_string(const CborValue *value, void *buffer,
+                                                   size_t *buflen, CborValue *next);
+CBOR_PRIVATE_API CborError _cbor_value_dup_string(const CborValue *value, void **buffer,
+                                                  size_t *buflen, CborValue *next);
+
+CBOR_API CborError cbor_value_calculate_string_length(const CborValue *value, size_t *length);
+
+CBOR_INLINE_API CborError cbor_value_copy_text_string(const CborValue *value, char *buffer,
+                                                      size_t *buflen, CborValue *next)
+{
+    assert(cbor_value_is_text_string(value));
+    return _cbor_value_copy_string(value, buffer, buflen, next);
+}
+CBOR_INLINE_API CborError cbor_value_copy_byte_string(const CborValue *value, uint8_t *buffer,
+                                                      size_t *buflen, CborValue *next)
+{
+    assert(cbor_value_is_byte_string(value));
+    return _cbor_value_copy_string(value, buffer, buflen, next);
+}
+
+CBOR_INLINE_API CborError cbor_value_dup_text_string(const CborValue *value, char **buffer,
+                                                     size_t *buflen, CborValue *next)
+{
+    assert(cbor_value_is_text_string(value));
+    return _cbor_value_dup_string(value, (void **)buffer, buflen, next);
+}
+CBOR_INLINE_API CborError cbor_value_dup_byte_string(const CborValue *value, uint8_t **buffer,
+                                                     size_t *buflen, CborValue *next)
+{
+    assert(cbor_value_is_byte_string(value));
+    return _cbor_value_dup_string(value, (void **)buffer, buflen, next);
+}
+
+/* ### TBD: partial reading API */
+
+CBOR_API CborError cbor_value_text_string_equals(const CborValue *value, const char *string, bool *result);
+
+/* Maps and arrays */
+CBOR_INLINE_API bool cbor_value_is_array(const CborValue *value)
+{ return value->type == CborArrayType; }
+CBOR_INLINE_API bool cbor_value_is_map(const CborValue *value)
+{ return value->type == CborMapType; }
+
+CBOR_INLINE_API CborError cbor_value_get_array_length(const CborValue *value, size_t *length)
+{
+    assert(cbor_value_is_array(value));
+    if (!cbor_value_is_length_known(value))
+        return CborErrorUnknownLength;
+    uint64_t v = _cbor_value_extract_int64_helper(value);
+    *length = v;
+    if (*length != v)
+        return CborErrorDataTooLarge;
+    return CborNoError;
+}
+
+CBOR_INLINE_API CborError cbor_value_get_map_length(const CborValue *value, size_t *length)
+{
+    assert(cbor_value_is_map(value));
+    if (!cbor_value_is_length_known(value))
+        return CborErrorUnknownLength;
+    uint64_t v = _cbor_value_extract_int64_helper(value);
+    *length = v;
+    if (*length != v)
+        return CborErrorDataTooLarge;
+    return CborNoError;
+}
+
+CBOR_API CborError cbor_value_map_find_value(const CborValue *map, const char *string, CborValue *element);
+
+/* Floating point */
+CBOR_INLINE_API bool cbor_value_is_half_float(const CborValue *value)
+{ return value->type == CborHalfFloatType; }
+CBOR_API CborError cbor_value_get_half_float(const CborValue *value, void *result);
+
+CBOR_INLINE_API bool cbor_value_is_float(const CborValue *value)
+{ return value->type == CborFloatType; }
+CBOR_INLINE_API CborError cbor_value_get_float(const CborValue *value, float *result)
+{
+    assert(cbor_value_is_float(value));
+    assert(value->flags & CborIteratorFlag_IntegerValueTooLarge);
+    uint32_t data = (uint32_t)_cbor_value_decode_int64_internal(value);
+    memcpy(result, &data, sizeof(*result));
+    return CborNoError;
+}
+
+CBOR_INLINE_API bool cbor_value_is_double(const CborValue *value)
+{ return value->type == CborDoubleType; }
+CBOR_INLINE_API CborError cbor_value_get_double(const CborValue *value, double *result)
+{
+    assert(cbor_value_is_double(value));
+    assert(value->flags & CborIteratorFlag_IntegerValueTooLarge);
+    uint64_t data = _cbor_value_decode_int64_internal(value);
+    memcpy(result, &data, sizeof(*result));
+    return CborNoError;
+}
+
+/* Human-readable (dump) API */
+CBOR_API CborError cbor_value_to_pretty_advance(FILE *out, CborValue *value);
+CBOR_INLINE_API CborError cbor_value_to_pretty(FILE *out, const CborValue *value)
+{
+    CborValue copy = *value;
+    return cbor_value_to_pretty_advance(out, &copy);
+}
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* CBOR_H */
+

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/encoding/tinycbor/include/tinycbor/cborconstants_p.h
----------------------------------------------------------------------
diff --git a/encoding/tinycbor/include/tinycbor/cborconstants_p.h b/encoding/tinycbor/include/tinycbor/cborconstants_p.h
new file mode 100644
index 0000000..d5808c3
--- /dev/null
+++ b/encoding/tinycbor/include/tinycbor/cborconstants_p.h
@@ -0,0 +1,52 @@
+#ifndef CBORCONSTANTS_P_H
+#define CBORCONSTANTS_P_H
+
+/*
+ * CBOR Major types
+ * Encoded in the high 3 bits of the descriptor byte
+ * See http://tools.ietf.org/html/rfc7049#section-2.1
+ */
+typedef enum CborMajorTypes {
+    UnsignedIntegerType = 0U,
+    NegativeIntegerType = 1U,
+    ByteStringType = 2U,
+    TextStringType = 3U,
+    ArrayType = 4U,
+    MapType = 5U,           /* a.k.a. object */
+    TagType = 6U,
+    SimpleTypesType = 7U
+} CborMajorTypes;
+
+/*
+ * CBOR simple and floating point types
+ * Encoded in the low 8 bits of the descriptor byte when the
+ * Major Type is 7.
+ */
+typedef enum CborSimpleTypes {
+    FalseValue              = 20,
+    TrueValue               = 21,
+    NullValue               = 22,
+    UndefinedValue          = 23,
+    SimpleTypeInNextByte    = 24,   /* not really a simple type */
+    HalfPrecisionFloat      = 25,   /* ditto */
+    SinglePrecisionFloat    = 26,   /* ditto */
+    DoublePrecisionFloat    = 27,   /* ditto */
+    Break                   = 31
+} CborSimpleTypes;
+
+enum {
+    SmallValueBitLength     = 5U,
+    SmallValueMask          = (1U << SmallValueBitLength) - 1,      /* 31 */
+    Value8Bit               = 24U,
+    Value16Bit              = 25U,
+    Value32Bit              = 26U,
+    Value64Bit              = 27U,
+    IndefiniteLength        = 31U,
+
+    MajorTypeShift          = SmallValueBitLength,
+    MajorTypeMask           = ~0U << MajorTypeShift,
+
+    BreakByte               = (unsigned)Break | (SimpleTypesType << MajorTypeShift)
+};
+
+#endif /* CBORCONSTANTS_P_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/encoding/tinycbor/include/tinycbor/cborjson.h
----------------------------------------------------------------------
diff --git a/encoding/tinycbor/include/tinycbor/cborjson.h b/encoding/tinycbor/include/tinycbor/cborjson.h
new file mode 100644
index 0000000..8ff27b9
--- /dev/null
+++ b/encoding/tinycbor/include/tinycbor/cborjson.h
@@ -0,0 +1,62 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 Intel Corporation
+**
+** Permission is hereby granted, free of charge, to any person obtaining a copy
+** of this software and associated documentation files (the "Software"), to deal
+** in the Software without restriction, including without limitation the rights
+** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+** copies of the Software, and to permit persons to whom the Software is
+** furnished to do so, subject to the following conditions:
+**
+** The above copyright notice and this permission notice shall be included in
+** all copies or substantial portions of the Software.
+**
+** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+** THE SOFTWARE.
+**
+****************************************************************************/
+
+#ifndef CBORJSON_H
+#define CBORJSON_H
+
+#include "cbor.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Conversion to JSON */
+enum CborToJsonFlags
+{
+    CborConvertAddMetadata = 1,
+    CborConvertTagsToObjects = 2,
+    CborConvertIgnoreTags = 0,
+
+    CborConvertObeyByteStringTags = 0,
+    CborConvertByteStringsToBase64Url = 4,
+
+    CborConvertRequireMapStringKeys = 0,
+    CborConvertStringifyMapKeys = 8,
+
+    CborConvertDefaultFlags = 0
+};
+
+CBOR_API CborError cbor_value_to_json_advance(FILE *out, CborValue *value, int flags);
+CBOR_INLINE_API CborError cbor_value_to_json(FILE *out, const CborValue *value, int flags)
+{
+    CborValue copy = *value;
+    return cbor_value_to_json_advance(out, &copy, flags);
+}
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* CBORJSON_H */
+

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/encoding/tinycbor/include/tinycbor/compilersupport_p.h
----------------------------------------------------------------------
diff --git a/encoding/tinycbor/include/tinycbor/compilersupport_p.h b/encoding/tinycbor/include/tinycbor/compilersupport_p.h
new file mode 100644
index 0000000..4e0dbe3
--- /dev/null
+++ b/encoding/tinycbor/include/tinycbor/compilersupport_p.h
@@ -0,0 +1,218 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 Intel Corporation
+**
+** Permission is hereby granted, free of charge, to any person obtaining a copy
+** of this software and associated documentation files (the "Software"), to deal
+** in the Software without restriction, including without limitation the rights
+** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+** copies of the Software, and to permit persons to whom the Software is
+** furnished to do so, subject to the following conditions:
+**
+** The above copyright notice and this permission notice shall be included in
+** all copies or substantial portions of the Software.
+**
+** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+** THE SOFTWARE.
+**
+****************************************************************************/
+
+#ifndef COMPILERSUPPORT_H
+#define COMPILERSUPPORT_H
+
+#include "cbor.h"
+
+#ifndef _BSD_SOURCE
+#  define _BSD_SOURCE
+#endif
+#ifndef _DEFAULT_SOURCE
+#  define _DEFAULT_SOURCE
+#endif
+#include <assert.h>
+#include <float.h>
+#include <stddef.h>
+#include <stdint.h>
+#include <string.h>
+
+#ifndef __cplusplus
+#  include <stdbool.h>
+#endif
+
+#ifdef __F16C__
+#  include <immintrin.h>
+#endif
+
+#if __STDC_VERSION__ >= 201112L || __cplusplus >= 201103L || __cpp_static_assert >= 200410
+#  define cbor_static_assert(x)         _Static_assert(x, #x)
+#elif !defined(__cplusplus) && defined(__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__ >= 406)
+#  define cbor_static_assert(x)         _Static_assert(x, #x)
+#else
+#  define cbor_static_assert(x)         ((void)sizeof(char[2*!!(x) - 1]))
+#endif
+#if __STDC_VERSION__ >= 199901L || defined(__cplusplus)
+/* inline is a keyword */
+#else
+/* use the definition from cbor.h */
+#  define inline    CBOR_INLINE
+#endif
+
+#define STRINGIFY(x)            STRINGIFY2(x)
+#define STRINGIFY2(x)           #x
+
+#if !defined(UINT32_MAX) || !defined(INT64_MAX)
+/* C89? We can define UINT32_MAX portably, but not INT64_MAX */
+#  error "Your system has stdint.h but that doesn't define UINT32_MAX or INT64_MAX"
+#endif
+
+#ifndef DBL_DECIMAL_DIG
+/* DBL_DECIMAL_DIG is C11 */
+#  define DBL_DECIMAL_DIG       17
+#endif
+#define DBL_DECIMAL_DIG_STR     STRINGIFY(DBL_DECIMAL_DIG)
+
+#ifndef __has_builtin
+#  define __has_builtin(x)  0
+#endif
+
+#if (defined(__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__ >= 403)) || \
+    (__has_builtin(__builtin_bswap64) && __has_builtin(__builtin_bswap32))
+#  if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
+#    define cbor_ntohll     __builtin_bswap64
+#    define cbor_htonll     __builtin_bswap64
+#    define cbor_ntohl      __builtin_bswap32
+#    define cbor_htonl      __builtin_bswap32
+#    ifdef __INTEL_COMPILER
+#      define cbor_ntohs    _bswap16
+#      define cbor_htons    _bswap16
+#    elif (__GNUC__ * 100 + __GNUC_MINOR__ >= 608) || __has_builtin(__builtin_bswap16)
+#      define cbor_ntohs    __builtin_bswap16
+#      define cbor_htons    __builtin_bswap16
+#    else
+#      define cbor_ntohs(x) (((uint16_t)x >> 8) | ((uint16_t)x << 8))
+#      define cbor_htons    cbor_ntohs
+#    endif
+#  else
+#    define cbor_ntohll
+#    define cbor_htonll
+#    define cbor_ntohl
+#    define cbor_htonl
+#    define cbor_ntohs
+#    define cbor_htons
+#  endif
+#elif defined(__sun)
+#  include <sys/byteorder.h>
+#elif defined(_MSC_VER)
+/* MSVC, which implies Windows, which implies little-endian and sizeof(long) == 4 */
+#  define cbor_ntohll       _byteswap_uint64
+#  define cbor_htonll       _byteswap_uint64
+#  define cbor_ntohl        _byteswap_ulong
+#  define cbor_htonl        _byteswap_ulong
+#  define cbor_ntohs        _byteswap_ushort
+#  define cbor_htons        _byteswap_ushort
+#endif
+#ifndef cbor_ntohs
+#  include <arpa/inet.h>
+#  define cbor_ntohs        ntohs
+#  define cbor_htons        htons
+#endif
+#ifndef cbor_ntohl
+#  include <arpa/inet.h>
+#  define cbor_ntohl        ntohl
+#  define cbor_htonl        htonl
+#endif
+#ifndef cbor_ntohll
+#  define cbor_ntohll       ntohll
+#  define cbor_htonll       htonll
+/* ntohll isn't usually defined */
+#  ifndef ntohll
+#    if defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
+#      define ntohll
+#      define htonll
+#    elif defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
+#      define ntohll(x)       ((ntohl((uint32_t)(x)) * UINT64_C(0x100000000)) + (ntohl((x) >> 32)))
+#      define htonll          ntohll
+#    else
+#      error "Unable to determine byte order!"
+#    endif
+#  endif
+#endif
+
+
+#ifdef __cplusplus
+#  define CONST_CAST(t, v)  const_cast<t>(v)
+#else
+/* C-style const_cast without triggering a warning with -Wcast-qual */
+#  define CONST_CAST(t, v)  (t)(uintptr_t)(v)
+#endif
+
+#ifdef __GNUC__
+#  define likely(x)     __builtin_expect(!!(x), 1)
+#  define unlikely(x)   __builtin_expect(!!(x), 0)
+#  define unreachable() __builtin_unreachable()
+#elif defined(_MSC_VER)
+#  define likely(x)     (x)
+#  define unlikely(x)   (x)
+#  define unreachable() __assume(0)
+#else
+#  define likely(x)     (x)
+#  define unlikely(x)   (x)
+#  define unreachable() do {} while (0)
+#endif
+
+#if defined(__GNUC__) && !defined(__INTEL_COMPILER) && !defined(__clang__) && \
+    (__GNUC__ * 100 + __GNUC_MINOR__ >= 404)
+#  pragma GCC optimize("-ffunction-sections")
+#endif
+
+static inline bool add_check_overflow(size_t v1, size_t v2, size_t *r)
+{
+#if ((defined(__GNUC__) && (__GNUC__ >= 5)) && !defined(__INTEL_COMPILER)) || __has_builtin(__builtin_add_overflow)
+    return __builtin_add_overflow(v1, v2, r);
+#else
+    /* unsigned additions are well-defined */
+    *r = v1 + v2;
+    return v1 > v1 + v2;
+#endif
+}
+
+static inline unsigned short encode_half(double val)
+{
+#ifdef __F16C__
+    return _cvtss_sh(val, 3);
+#else
+    uint64_t v;
+    memcpy(&v, &val, sizeof(v));
+    int sign = v >> 63 << 15;
+    int exp = (v >> 52) & 0x7ff;
+    int mant = v << 12 >> 12 >> (53-11);    /* keep only the 11 most significant bits of the mantissa */
+    exp -= 1023;
+    if (exp == 1024) {
+        /* infinity or NaN */
+        exp = 16;
+        mant >>= 1;
+    } else if (exp >= 16) {
+        /* overflow, as largest number */
+        exp = 15;
+        mant = 1023;
+    } else if (exp >= -14) {
+        /* regular normal */
+    } else if (exp >= -24) {
+        /* subnormal */
+        mant |= 1024;
+        mant >>= -(exp + 14);
+        exp = -15;
+    } else {
+        /* underflow, make zero */
+        return 0;
+    }
+    return sign | ((exp + 15) << 10) | mant;
+#endif
+}
+
+#endif /* COMPILERSUPPORT_H */
+

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/encoding/tinycbor/include/tinycbor/extract_number_p.h
----------------------------------------------------------------------
diff --git a/encoding/tinycbor/include/tinycbor/extract_number_p.h b/encoding/tinycbor/include/tinycbor/extract_number_p.h
new file mode 100644
index 0000000..b65ca44
--- /dev/null
+++ b/encoding/tinycbor/include/tinycbor/extract_number_p.h
@@ -0,0 +1,78 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 Intel Corporation
+**
+** Permission is hereby granted, free of charge, to any person obtaining a copy
+** of this software and associated documentation files (the "Software"), to deal
+** in the Software without restriction, including without limitation the rights
+** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+** copies of the Software, and to permit persons to whom the Software is
+** furnished to do so, subject to the following conditions:
+**
+** The above copyright notice and this permission notice shall be included in
+** all copies or substantial portions of the Software.
+**
+** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+** THE SOFTWARE.
+**
+****************************************************************************/
+
+#define _BSD_SOURCE 1
+#define _DEFAULT_SOURCE 1
+#include "cbor.h"
+#include "cborconstants_p.h"
+#include "compilersupport_p.h"
+#include <stdlib.h>
+
+static inline uint16_t get16(const uint8_t *ptr)
+{
+    uint16_t result;
+    memcpy(&result, ptr, sizeof(result));
+    return cbor_ntohs(result);
+}
+
+static inline uint32_t get32(const uint8_t *ptr)
+{
+    uint32_t result;
+    memcpy(&result, ptr, sizeof(result));
+    return cbor_ntohl(result);
+}
+
+static inline uint64_t get64(const uint8_t *ptr)
+{
+    uint64_t result;
+    memcpy(&result, ptr, sizeof(result));
+    return cbor_ntohll(result);
+}
+
+static CborError extract_number(const uint8_t **ptr, const uint8_t *end, uint64_t *len)
+{
+    uint8_t additional_information = **ptr & SmallValueMask;
+    ++*ptr;
+    if (additional_information < Value8Bit) {
+        *len = additional_information;
+        return CborNoError;
+    }
+    if (unlikely(additional_information > Value64Bit))
+        return CborErrorIllegalNumber;
+
+    size_t bytesNeeded = (size_t)(1 << (additional_information - Value8Bit));
+    if (unlikely(bytesNeeded > (size_t)(end - *ptr))) {
+        return CborErrorUnexpectedEOF;
+    } else if (bytesNeeded == 1) {
+        *len = (uint8_t)(*ptr)[0];
+    } else if (bytesNeeded == 2) {
+        *len = get16(*ptr);
+    } else if (bytesNeeded == 4) {
+        *len = get32(*ptr);
+    } else {
+        *len = get64(*ptr);
+    }
+    *ptr += bytesNeeded;
+    return CborNoError;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/encoding/tinycbor/include/tinycbor/math_support_p.h
----------------------------------------------------------------------
diff --git a/encoding/tinycbor/include/tinycbor/math_support_p.h b/encoding/tinycbor/include/tinycbor/math_support_p.h
new file mode 100644
index 0000000..676f781
--- /dev/null
+++ b/encoding/tinycbor/include/tinycbor/math_support_p.h
@@ -0,0 +1,47 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 Intel Corporation
+**
+** Permission is hereby granted, free of charge, to any person obtaining a copy
+** of this software and associated documentation files (the "Software"), to deal
+** in the Software without restriction, including without limitation the rights
+** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+** copies of the Software, and to permit persons to whom the Software is
+** furnished to do so, subject to the following conditions:
+**
+** The above copyright notice and this permission notice shall be included in
+** all copies or substantial portions of the Software.
+**
+** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+** THE SOFTWARE.
+**
+****************************************************************************/
+
+#ifndef MATH_SUPPORT_H
+#define MATH_SUPPORT_H
+
+#include <math.h>
+
+/* this function was copied & adapted from RFC 7049 Appendix D */
+static inline double decode_half(unsigned short half)
+{
+#ifdef __F16C__
+    return _cvtsh_ss(half);
+#else
+    int exp = (half >> 10) & 0x1f;
+    int mant = half & 0x3ff;
+    double val;
+    if (exp == 0) val = ldexp(mant, -24);
+    else if (exp != 31) val = ldexp(mant + 1024, exp - 25);
+    else val = mant == 0 ? INFINITY : NAN;
+    return half & 0x8000 ? -val : val;
+#endif
+}
+
+#endif // MATH_SUPPORT_H
+

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/encoding/tinycbor/pkg.yml
----------------------------------------------------------------------
diff --git a/encoding/tinycbor/pkg.yml b/encoding/tinycbor/pkg.yml
new file mode 100644
index 0000000..3eb846d
--- /dev/null
+++ b/encoding/tinycbor/pkg.yml
@@ -0,0 +1,26 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+#
+
+pkg.name: libs/tinycbor 
+pkg.description: CBOR encoding/decoding library 
+pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
+pkg.homepage: "http://mynewt.apache.org/"
+pkg.keywords:
+
+pkg.cflags: -DWITHOUT_OPEN_MEMSTREAM -I../include/tinycbor
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/encoding/tinycbor/src/cborencoder.c
----------------------------------------------------------------------
diff --git a/encoding/tinycbor/src/cborencoder.c b/encoding/tinycbor/src/cborencoder.c
new file mode 100644
index 0000000..eef05cd
--- /dev/null
+++ b/encoding/tinycbor/src/cborencoder.c
@@ -0,0 +1,629 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 Intel Corporation
+**
+** Permission is hereby granted, free of charge, to any person obtaining a copy
+** of this software and associated documentation files (the "Software"), to deal
+** in the Software without restriction, including without limitation the rights
+** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+** copies of the Software, and to permit persons to whom the Software is
+** furnished to do so, subject to the following conditions:
+**
+** The above copyright notice and this permission notice shall be included in
+** all copies or substantial portions of the Software.
+**
+** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+** THE SOFTWARE.
+**
+****************************************************************************/
+
+#define _BSD_SOURCE 1
+#define _DEFAULT_SOURCE 1
+#ifndef __STDC_LIMIT_MACROS
+#  define __STDC_LIMIT_MACROS 1
+#endif
+
+#include "cbor.h"
+#include "cborconstants_p.h"
+#include "compilersupport_p.h"
+
+#include <assert.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "assert_p.h"       /* Always include last */
+
+/**
+ * \defgroup CborEncoding Encoding to CBOR
+ * \brief Group of functions used to encode data to CBOR.
+ *
+ * CborEncoder is used to encode data into a CBOR stream. The outermost
+ * CborEncoder is initialized by calling cbor_encoder_init(), with the buffer
+ * where the CBOR stream will be stored. The outermost CborEncoder is usually
+ * used to encode exactly one item, most often an array or map. It is possible
+ * to encode more than one item, but care must then be taken on the decoder
+ * side to ensure the state is reset after each item was decoded.
+ *
+ * Nested CborEncoder objects are created using cbor_encoder_create_array() and
+ * cbor_encoder_create_map(), later closed with cbor_encoder_close_container()
+ * or cbor_encoder_close_container_checked(). The pairs of creation and closing
+ * must be exactly matched and their parameters are always the same.
+ *
+ * CborEncoder writes directly to the user-supplied buffer, without extra
+ * buffering. CborEncoder does not allocate memory and CborEncoder objects are
+ * usually created on the stack of the encoding functions.
+ *
+ * The example below initializes a CborEncoder object with a buffer and encodes
+ * a single integer.
+ *
+ * \code
+ *      uint8_t buf[16];
+ *      CborEncoder encoder;
+ *      cbor_encoder_init(&encoder, &buf, sizeof(buf), 0);
+ *      cbor_encode_int(&encoder, some_value);
+ * \endcode
+ *
+ * As explained before, usually the outermost CborEncoder object is used to add
+ * one array or map, which in turn contains multiple elements. The example
+ * below creates a CBOR map with one element: a key "foo" and a boolean value.
+ *
+ * \code
+ *      uint8_t buf[16];
+ *      CborEncoder encoder, mapEncoder;
+ *      cbor_encoder_init(&encoder, &buf, sizeof(buf), 0);
+ *      cbor_encoder_create_map(&encoder, &mapEncoder, 1);
+ *      cbor_encode_text_stringz(&mapEncoder, "foo");
+ *      cbor_encode_boolean(&mapEncoder, some_value);
+ *      cbor_encoder_close_container(&encoder, &mapEncoder);
+ * \endcode
+ *
+ * <h3 class="groupheader">Error checking and buffer size</h2>
+ *
+ * All functions operating on CborEncoder return a condition of type CborError.
+ * If the encoding was successful, they return CborNoError. Some functions do
+ * extra checking on the input provided and may return some other error
+ * conditions (for example, cbor_encode_simple_value() checks that the type is
+ * of the correct type).
+ *
+ * In addition, all functions check whether the buffer has enough bytes to
+ * encode the item being appended. If that is not possible, they return
+ * CborErrorOutOfMemory.
+ *
+ * It is possible to continue with the encoding of data past the first function
+ * that returns CborErrorOutOfMemory. CborEncoder functions will not overrun
+ * the buffer, but will instead count how many more bytes are needed to
+ * complete the encoding. At the end, you can obtain that count by calling
+ * cbor_encoder_get_extra_bytes_needed().
+ *
+ * \section1 Finalizing the encoding
+ *
+ * Once all items have been appended and the containers have all been properly
+ * closed, the user-supplied buffer will contain the CBOR stream and may be
+ * immediately used. To obtain the size of the buffer, call
+ * cbor_encoder_get_buffer_size() with the original buffer pointer.
+ *
+ * The example below illustrates how one can encode an item with error checking
+ * and then pass on the buffer for network sending.
+ *
+ * \code
+ *      uint8_t buf[16];
+ *      CborError err;
+ *      CborEncoder encoder, mapEncoder;
+ *      cbor_encoder_init(&encoder, &buf, sizeof(buf), 0);
+ *      err = cbor_encoder_create_map(&encoder, &mapEncoder, 1);
+ *      if (!err)
+ *          return err;
+ *      err = cbor_encode_text_stringz(&mapEncoder, "foo");
+ *      if (!err)
+ *          return err;
+ *      err = cbor_encode_boolean(&mapEncoder, some_value);
+ *      if (!err)
+ *          return err;
+ *      err = cbor_encoder_close_container_checked(&encoder, &mapEncoder);
+ *      if (!err)
+ *          return err;
+ *
+ *      size_t len = cbor_encoder_get_buffer_size(&encoder, buf);
+ *      send_payload(buf, len);
+ *      return CborNoError;
+ * \endcode
+ *
+ * Finally, the example below illustrates expands on the one above and also
+ * deals with dynamically growing the buffer if the initial allocation wasn't
+ * big enough. Note the two places where the error checking was replaced with
+ * an assertion, showing where the author assumes no error can occur.
+ *
+ * \code
+ * uint8_t *encode_string_array(const char **strings, int n, size_t *bufsize)
+ * {
+ *     CborError err;
+ *     CborEncoder encoder, arrayEncoder;
+ *     size_t size = 256;
+ *     uint8_t *buf = NULL;
+ *
+ *     while (1) {
+ *         int i;
+ *         size_t more_bytes;
+ *         uint8_t *nbuf = realloc(buf, size);
+ *         if (nbuf == NULL)
+ *             goto error;
+ *         buf = nbuf;
+ *
+ *         cbor_encoder_init(&encoder, &buf, size, 0);
+ *         err = cbor_encoder_create_array(&encoder, &arrayEncoder, n);
+ *         assert(err);         // can't fail, the buffer is always big enough
+ *
+ *         for (i = 0; i < n; ++i) {
+ *             err = cbor_encode_text_stringz(&arrayEncoder, strings[i]);
+ *             if (err && err != CborErrorOutOfMemory)
+ *                 goto error;
+ *         }
+ *
+ *         err = cbor_encoder_close_container_checked(&encoder, &arrayEncoder);
+ *         assert(err);         // shouldn't fail!
+ *
+ *         more_bytes = cbor_encoder_get_extra_bytes_needed(encoder);
+ *         if (more_size) {
+ *             // buffer wasn't big enough, try again
+ *             size += more_bytes;
+ *             continue;
+ *         }
+ *
+ *         *bufsize = cbor_encoder_get_buffer_size(encoder, buf);
+ *         return buf;
+ *     }
+ *  error:
+ *     free(buf);
+ *     return NULL;
+ *  }
+ * \endcode
+ */
+
+/**
+ * \addtogroup CborEncoding
+ * @{
+ */
+
+/**
+ * \struct CborEncoder
+ * Structure used to encode to CBOR.
+ */
+
+/**
+ * Initializes a CborEncoder structure \a encoder by pointing it to buffer \a
+ * buffer of size \a size. The \a flags field is currently unused and must be
+ * zero.
+ */
+void cbor_encoder_init(CborEncoder *encoder, uint8_t *buffer, size_t size, int flags)
+{
+    encoder->ptr = buffer;
+    encoder->end = buffer + size;
+    encoder->added = 0;
+    encoder->flags = flags;
+}
+
+static inline void put16(void *where, uint16_t v)
+{
+    v = cbor_htons(v);
+    memcpy(where, &v, sizeof(v));
+}
+
+/* Note: Since this is currently only used in situations where OOM is the only
+ * valid error, we KNOW this to be true.  Thus, this function now returns just 'true',
+ * but if in the future, any function starts returning a non-OOM error, this will need
+ * to be changed to the test.  At the moment, this is done to prevent more branches
+ * being created in the tinycbor output */
+static inline bool isOomError(CborError err)
+{
+    (void) err;
+    return true;
+}
+
+static inline void put32(void *where, uint32_t v)
+{
+    v = cbor_htonl(v);
+    memcpy(where, &v, sizeof(v));
+}
+
+static inline void put64(void *where, uint64_t v)
+{
+    v = cbor_htonll(v);
+    memcpy(where, &v, sizeof(v));
+}
+
+static inline bool would_overflow(CborEncoder *encoder, size_t len)
+{
+    ptrdiff_t remaining = (ptrdiff_t)encoder->end;
+    remaining -= remaining ? (ptrdiff_t)encoder->ptr : encoder->bytes_needed;
+    remaining -= (ptrdiff_t)len;
+    return unlikely(remaining < 0);
+}
+
+static inline void advance_ptr(CborEncoder *encoder, size_t n)
+{
+    if (encoder->end)
+        encoder->ptr += n;
+    else
+        encoder->bytes_needed += n;
+}
+
+static inline CborError append_to_buffer(CborEncoder *encoder, const void *data, size_t len)
+{
+    if (would_overflow(encoder, len)) {
+        if (encoder->end != NULL) {
+            len -= encoder->end - encoder->ptr;
+            encoder->end = NULL;
+            encoder->bytes_needed = 0;
+        }
+
+        advance_ptr(encoder, len);
+        return CborErrorOutOfMemory;
+    }
+
+    memcpy(encoder->ptr, data, len);
+    encoder->ptr += len;
+    return CborNoError;
+}
+
+static inline CborError append_byte_to_buffer(CborEncoder *encoder, uint8_t byte)
+{
+    return append_to_buffer(encoder, &byte, 1);
+}
+
+static inline CborError encode_number_no_update(CborEncoder *encoder, uint64_t ui, uint8_t shiftedMajorType)
+{
+    /* Little-endian would have been so much more convenient here:
+     * We could just write at the beginning of buf but append_to_buffer
+     * only the necessary bytes.
+     * Since it has to be big endian, do it the other way around:
+     * write from the end. */
+    uint64_t buf[2];
+    uint8_t *const bufend = (uint8_t *)buf + sizeof(buf);
+    uint8_t *bufstart = bufend - 1;
+    put64(buf + 1, ui);     /* we probably have a bunch of zeros in the beginning */
+
+    if (ui < Value8Bit) {
+        *bufstart += shiftedMajorType;
+    } else {
+        unsigned more = 0;
+        if (ui > 0xffU)
+            ++more;
+        if (ui > 0xffffU)
+            ++more;
+        if (ui > 0xffffffffU)
+            ++more;
+        bufstart -= (size_t)1 << more;
+        *bufstart = shiftedMajorType + Value8Bit + more;
+    }
+
+    return append_to_buffer(encoder, bufstart, bufend - bufstart);
+}
+
+static inline CborError encode_number(CborEncoder *encoder, uint64_t ui, uint8_t shiftedMajorType)
+{
+    ++encoder->added;
+    return encode_number_no_update(encoder, ui, shiftedMajorType);
+}
+
+/**
+ * Appends the unsigned 64-bit integer \a value to the CBOR stream provided by
+ * \a encoder.
+ *
+ * \sa cbor_encode_negative_int, cbor_encode_int
+ */
+CborError cbor_encode_uint(CborEncoder *encoder, uint64_t value)
+{
+    return encode_number(encoder, value, UnsignedIntegerType << MajorTypeShift);
+}
+
+/**
+ * Appends the negative 64-bit integer whose absolute value is \a
+ * absolute_value to the CBOR stream provided by \a encoder.
+ *
+ * \sa cbor_encode_uint, cbor_encode_int
+ */
+CborError cbor_encode_negative_int(CborEncoder *encoder, uint64_t absolute_value)
+{
+    return encode_number(encoder, absolute_value, NegativeIntegerType << MajorTypeShift);
+}
+
+/**
+ * Appends the signed 64-bit integer \a value to the CBOR stream provided by
+ * \a encoder.
+ *
+ * \sa cbor_encode_negative_int, cbor_encode_uint
+ */
+CborError cbor_encode_int(CborEncoder *encoder, int64_t value)
+{
+    /* adapted from code in RFC 7049 appendix C (pseudocode) */
+    uint64_t ui = value >> 63;              /* extend sign to whole length */
+    uint8_t majorType = ui & 0x20;          /* extract major type */
+    ui ^= value;                            /* complement negatives */
+    return encode_number(encoder, ui, majorType);
+}
+
+/**
+ * Appends the CBOR Simple Type of value \a value to the CBOR stream provided by
+ * \a encoder.
+ *
+ * This function may return error CborErrorIllegalSimpleType if the \a value
+ * variable contains a number that is not a valid simple type.
+ */
+CborError cbor_encode_simple_value(CborEncoder *encoder, uint8_t value)
+{
+#ifndef CBOR_ENCODER_NO_CHECK_USER
+    /* check if this is a valid simple type */
+    if (value >= HalfPrecisionFloat && value <= Break)
+        return CborErrorIllegalSimpleType;
+#endif
+    return encode_number(encoder, value, SimpleTypesType << MajorTypeShift);
+}
+
+/**
+ * Appends the floating-point value of type \a fpType and pointed to by \a
+ * value to the CBOR stream provided by \a encoder. The value of \a fpType must
+ * be one of CborHalfFloatType, CborFloatType or CborDoubleType, otherwise the
+ * behavior of this function is undefined.
+ *
+ * This function is useful for code that needs to pass through floating point
+ * values but does not wish to have the actual floating-point code.
+ *
+ * \sa cbor_encode_half_float, cbor_encode_float, cbor_encode_double
+ */
+CborError cbor_encode_floating_point(CborEncoder *encoder, CborType fpType, const void *value)
+{
+    uint8_t buf[1 + sizeof(uint64_t)];
+    assert(fpType == CborHalfFloatType || fpType == CborFloatType || fpType == CborDoubleType);
+    buf[0] = fpType;
+
+    unsigned size = 2U << (fpType - CborHalfFloatType);
+    if (size == 8)
+        put64(buf + 1, *(const uint64_t*)value);
+    else if (size == 4)
+        put32(buf + 1, *(const uint32_t*)value);
+    else
+        put16(buf + 1, *(const uint16_t*)value);
+    ++encoder->added;
+    return append_to_buffer(encoder, buf, size + 1);
+}
+
+/**
+ * Appends the CBOR tag \a tag to the CBOR stream provided by \a encoder.
+ *
+ * \sa CborTag
+ */
+CborError cbor_encode_tag(CborEncoder *encoder, CborTag tag)
+{
+    /* tags don't count towards the number of elements in an array or map */
+    return encode_number_no_update(encoder, tag, TagType << MajorTypeShift);
+}
+
+static CborError encode_string(CborEncoder *encoder, size_t length, uint8_t shiftedMajorType, const void *string)
+{
+    CborError err = encode_number(encoder, length, shiftedMajorType);
+    if (err && !isOomError(err))
+        return err;
+    return append_to_buffer(encoder, string, length);
+}
+
+/**
+ * \fn CborError cbor_encode_text_stringz(CborEncoder *encoder, const char *string)
+ *
+ * Appends the null-terminated text string \a string to the CBOR stream
+ * provided by \a encoder. CBOR requires that \a string be valid UTF-8, but
+ * TinyCBOR makes no verification of correctness. The terminating null is not
+ * included in the stream.
+ *
+ * \sa cbor_encode_text_string, cbor_encode_byte_string
+ */
+
+/**
+ * Appends the text string \a string of length \a length to the CBOR stream
+ * provided by \a encoder. CBOR requires that \a string be valid UTF-8, but
+ * TinyCBOR makes no verification of correctness.
+ *
+ * \sa CborError cbor_encode_text_stringz, cbor_encode_byte_string
+ */
+CborError cbor_encode_byte_string(CborEncoder *encoder, const uint8_t *string, size_t length)
+{
+    return encode_string(encoder, length, ByteStringType << MajorTypeShift, string);
+}
+
+/**
+ * Appends the byte string \a string of length \a length to the CBOR stream
+ * provided by \a encoder. CBOR byte strings are arbitrary raw data.
+ *
+ * \sa cbor_encode_text_stringz, cbor_encode_text_string
+ */
+CborError cbor_encode_text_string(CborEncoder *encoder, const char *string, size_t length)
+{
+    return encode_string(encoder, length, TextStringType << MajorTypeShift, string);
+}
+
+#ifdef __GNUC__
+__attribute__((noinline))
+#endif
+static CborError create_container(CborEncoder *encoder, CborEncoder *container, size_t length, uint8_t shiftedMajorType)
+{
+    CborError err;
+    container->ptr = encoder->ptr;
+    container->end = encoder->end;
+    ++encoder->added;
+    container->added = 0;
+
+    cbor_static_assert(((MapType << MajorTypeShift) & CborIteratorFlag_ContainerIsMap) == CborIteratorFlag_ContainerIsMap);
+    cbor_static_assert(((ArrayType << MajorTypeShift) & CborIteratorFlag_ContainerIsMap) == 0);
+    container->flags = shiftedMajorType & CborIteratorFlag_ContainerIsMap;
+
+    if (length == CborIndefiniteLength) {
+        container->flags |= CborIteratorFlag_UnknownLength;
+        err = append_byte_to_buffer(container, shiftedMajorType + IndefiniteLength);
+    } else {
+        err = encode_number_no_update(container, length, shiftedMajorType);
+    }
+    if (err && !isOomError(err))
+        return err;
+
+    return CborNoError;
+}
+
+/**
+ * Creates a CBOR array in the CBOR stream provided by \a encoder and
+ * initializes \a arrayEncoder so that items can be added to the array using
+ * the CborEncoder functions. The array must be terminated by calling either
+ * cbor_encoder_close_container() or cbor_encoder_close_container_checked()
+ * with the same \a encoder and \a arrayEncoder parameters.
+ *
+ * The number of items inserted into the array must be exactly \a length items,
+ * otherwise the stream is invalid. If the number of items is not known when
+ * creating the array, the constant \ref CborIndefiniteLength may be passed as
+ * length instead.
+ *
+ * \sa cbor_encoder_create_map
+ */
+CborError cbor_encoder_create_array(CborEncoder *encoder, CborEncoder *arrayEncoder, size_t length)
+{
+    return create_container(encoder, arrayEncoder, length, ArrayType << MajorTypeShift);
+}
+
+/**
+ * Creates a CBOR map in the CBOR stream provided by \a encoder and
+ * initializes \a mapEncoder so that items can be added to the map using
+ * the CborEncoder functions. The map must be terminated by calling either
+ * cbor_encoder_close_container() or cbor_encoder_close_container_checked()
+ * with the same \a encoder and \a mapEncoder parameters.
+ *
+ * The number of pair of items inserted into the map must be exactly \a length
+ * items, otherwise the stream is invalid. If the number of items is not known
+ * when creating the map, the constant \ref CborIndefiniteLength may be passed as
+ * length instead.
+ *
+ * \b{Implementation limitation:} TinyCBOR cannot encode more than SIZE_MAX/2
+ * key-value pairs in the stream. If the length \a length is larger than this
+ * value, this function returns error CborErrorDataTooLarge.
+ *
+ * \sa cbor_encoder_create_array
+ */
+CborError cbor_encoder_create_map(CborEncoder *encoder, CborEncoder *mapEncoder, size_t length)
+{
+    if (length != CborIndefiniteLength && length > SIZE_MAX / 2)
+        return CborErrorDataTooLarge;
+    return create_container(encoder, mapEncoder, length, MapType << MajorTypeShift);
+}
+
+/**
+ * Closes the CBOR container (array or map) provided by \a containerEncoder and
+ * updates the CBOR stream provided by \a encoder. Both parameters must be the
+ * same as were passed to cbor_encoder_create_array() or
+ * cbor_encoder_create_map().
+ *
+ * This function does not verify that the number of items (or pair of items, in
+ * the case of a map) was correct. To execute that verification, call
+ * cbor_encoder_close_container_checked() instead.
+ *
+ * \sa cbor_encoder_create_array(), cbor_encoder_create_map()
+ */
+CborError cbor_encoder_close_container(CborEncoder *encoder, const CborEncoder *containerEncoder)
+{
+    if (encoder->end)
+        encoder->ptr = containerEncoder->ptr;
+    else
+        encoder->bytes_needed = containerEncoder->bytes_needed;
+    encoder->end = containerEncoder->end;
+    if (containerEncoder->flags & CborIteratorFlag_UnknownLength)
+        return append_byte_to_buffer(encoder, BreakByte);
+    return CborNoError;
+}
+
+/**
+ * \fn CborError cbor_encode_boolean(CborEncoder *encoder, bool value)
+ *
+ * Appends the boolean value \a value to the CBOR stream provided by \a encoder.
+ */
+
+/**
+ * \fn CborError cbor_encode_null(CborEncoder *encoder)
+ *
+ * Appends the CBOR type representing a null value to the CBOR stream provided
+ * by \a encoder.
+ *
+ * \sa cbor_encode_undefined()
+ */
+
+/**
+ * \fn CborError cbor_encode_undefined(CborEncoder *encoder)
+ *
+ * Appends the CBOR type representing an undefined value to the CBOR stream
+ * provided by \a encoder.
+ *
+ * \sa cbor_encode_null()
+ */
+
+/**
+ * \fn CborError cbor_encode_half_float(CborEncoder *encoder, const void *value)
+ *
+ * Appends the IEEE 754 half-precision (16-bit) floating point value pointed to
+ * by \a value to the CBOR stream provided by \a encoder.
+ *
+ * \sa cbor_encode_floating_point(), cbor_encode_float(), cbor_encode_double()
+ */
+
+/**
+ * \fn CborError cbor_encode_float(CborEncoder *encoder, float value)
+ *
+ * Appends the IEEE 754 single-precision (32-bit) floating point value \a value
+ * to the CBOR stream provided by \a encoder.
+ *
+ * \sa cbor_encode_floating_point(), cbor_encode_half_float(), cbor_encode_double()
+ */
+
+/**
+ * \fn CborError cbor_encode_double(CborEncoder *encoder, double value)
+ *
+ * Appends the IEEE 754 double-precision (64-bit) floating point value \a value
+ * to the CBOR stream provided by \a encoder.
+ *
+ * \sa cbor_encode_floating_point(), cbor_encode_half_float(), cbor_encode_float()
+ */
+
+/**
+ * \fn size_t cbor_encoder_get_buffer_size(const CborEncoder *encoder, const uint8_t *buffer)
+ *
+ * Returns the total size of the buffer starting at \a buffer after the
+ * encoding finished without errors. The \a encoder and \a buffer arguments
+ * must be the same as supplied to cbor_encoder_init().
+ *
+ * If the encoding process had errors, the return value of this function is
+ * meaningless. If the only errors were CborErrorOutOfMemory, instead use
+ * cbor_encoder_get_extra_bytes_needed() to find out by how much to grow the
+ * buffer before encoding again.
+ *
+ * See \ref CborEncoding for an example of using this function.
+ *
+ * \sa cbor_encoder_init(), cbor_encoder_get_extra_bytes_needed(), CborEncoding
+ */
+
+/**
+ * \fn size_t cbor_encoder_get_extra_bytes_needed(const CborEncoder *encoder)
+ *
+ * Returns how many more bytes the original buffer supplied to
+ * cbor_encoder_init() needs to be extended by so that no CborErrorOutOfMemory
+ * condition will happen for the encoding. If the buffer was big enough, this
+ * function returns 0. The \a encoder must be the original argument as passed
+ * to cbor_encoder_init().
+ *
+ * This function is usually called after an encoding sequence ended with one or
+ * more CborErrorOutOfMemory errors, but no other error. If any other error
+ * happened, the return value of this function is meaningless.
+ *
+ * See \ref CborEncoding for an example of using this function.
+ *
+ * \sa cbor_encoder_init(), cbor_encoder_get_buffer_size(), CborEncoding
+ */
+
+/** @} */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/encoding/tinycbor/src/cborencoder_close_container_checked.c
----------------------------------------------------------------------
diff --git a/encoding/tinycbor/src/cborencoder_close_container_checked.c b/encoding/tinycbor/src/cborencoder_close_container_checked.c
new file mode 100644
index 0000000..cad8335
--- /dev/null
+++ b/encoding/tinycbor/src/cborencoder_close_container_checked.c
@@ -0,0 +1,82 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 Intel Corporation
+**
+** Permission is hereby granted, free of charge, to any person obtaining a copy
+** of this software and associated documentation files (the "Software"), to deal
+** in the Software without restriction, including without limitation the rights
+** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+** copies of the Software, and to permit persons to whom the Software is
+** furnished to do so, subject to the following conditions:
+**
+** The above copyright notice and this permission notice shall be included in
+** all copies or substantial portions of the Software.
+**
+** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+** THE SOFTWARE.
+**
+****************************************************************************/
+
+#define _BSD_SOURCE 1
+#define _DEFAULT_SOURCE 1
+#ifndef __STDC_LIMIT_MACROS
+#  define __STDC_LIMIT_MACROS 1
+#endif
+
+#include "cbor.h"
+#include "cborconstants_p.h"
+#include "compilersupport_p.h"
+#include "extract_number_p.h"
+
+#include <assert.h>
+
+#include "assert_p.h"       /* Always include last */
+
+/**
+ * \addtogroup CborEncoding
+ * @{
+ */
+
+/**
+ *
+ * Closes the CBOR container (array or map) provided by \a containerEncoder and
+ * updates the CBOR stream provided by \a encoder. Both parameters must be the
+ * same as were passed to cbor_encoder_create_array() or
+ * cbor_encoder_create_map().
+ *
+ * Unlike cbor_encoder_close_container(), this function checks that the number
+ * of items (or pair of items, in the case of a map) was correct. If the number
+ * of items inserted does not match the length originally passed to
+ * cbor_encoder_create_array() or cbor_encoder_create_map(), this function
+ * returns either CborErrorTooFewItems or CborErrorTooManyItems.
+ *
+ * \sa cbor_encoder_create_array(), cbor_encoder_create_map()
+ */
+CborError cbor_encoder_close_container_checked(CborEncoder *encoder, const CborEncoder *containerEncoder)
+{
+    const uint8_t *ptr = encoder->ptr;
+    CborError err = cbor_encoder_close_container(encoder, containerEncoder);
+    if (containerEncoder->flags & CborIteratorFlag_UnknownLength || encoder->end == NULL)
+        return err;
+
+    /* check what the original length was */
+    uint64_t actually_added;
+    err = extract_number(&ptr, encoder->ptr, &actually_added);
+    if (err)
+        return err;
+
+    if (containerEncoder->flags & CborIteratorFlag_ContainerIsMap) {
+        if (actually_added > SIZE_MAX / 2)
+            return CborErrorDataTooLarge;
+        actually_added *= 2;
+    }
+    return actually_added == containerEncoder->added ? CborNoError :
+           actually_added < containerEncoder->added ? CborErrorTooManyItems : CborErrorTooFewItems;
+}
+
+/** @} */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/encoding/tinycbor/src/cborerrorstrings.c
----------------------------------------------------------------------
diff --git a/encoding/tinycbor/src/cborerrorstrings.c b/encoding/tinycbor/src/cborerrorstrings.c
new file mode 100644
index 0000000..d2fe42f
--- /dev/null
+++ b/encoding/tinycbor/src/cborerrorstrings.c
@@ -0,0 +1,165 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 Intel Corporation
+**
+** Permission is hereby granted, free of charge, to any person obtaining a copy
+** of this software and associated documentation files (the "Software"), to deal
+** in the Software without restriction, including without limitation the rights
+** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+** copies of the Software, and to permit persons to whom the Software is
+** furnished to do so, subject to the following conditions:
+**
+** The above copyright notice and this permission notice shall be included in
+** all copies or substantial portions of the Software.
+**
+** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+** THE SOFTWARE.
+**
+****************************************************************************/
+
+#include "cbor.h"
+
+#ifndef _
+#  define _(msg)    msg
+#endif
+
+/**
+ * \enum CborError
+ * \ingroup CborGlobals
+ * The CborError enum contains the possible error values used by the CBOR encoder and decoder.
+ *
+ * TinyCBOR functions report success by returning CborNoError, or one error
+ * condition by returning one of the values below. One exception is the
+ * out-of-memory condition (CborErrorOutOfMemory), which the functions for \ref
+ * CborEncoding may report in bit-wise OR with other conditions.
+ *
+ * This technique allows code to determine whether the only error condition was
+ * a lack of buffer space, which may not be a fatal condition if the buffer can
+ * be resized. Additionally, the functions for \ref CborEncoding may continue
+ * to be used even after CborErrorOutOfMemory is returned, and instead they
+ * will simply calculate the extra space needed.
+ *
+ * \value CborNoError                   No error occurred
+ * \omitvalue CborUnknownError
+ * \value CborErrorUnknownLength        Request for the length of an array, map or string whose length is not provided in the CBOR stream
+ * \value CborErrorAdvancePastEOF       Not enough data in the stream to decode item (decoding would advance past end of stream)
+ * \value CborErrorIO                   An I/O error occurred, probably due to an out-of-memory situation
+ * \value CborErrorGarbageAtEnd         Bytes exist past the end of the CBOR stream
+ * \value CborErrorUnexpectedEOF        End of stream reached unexpectedly
+ * \value CborErrorUnexpectedBreak      A CBOR break byte was found where not expected
+ * \value CborErrorUnknownType          An unknown type (future extension to CBOR) was found in the stream
+ * \value CborErrorIllegalType          An invalid type was found while parsing a chunked CBOR string
+ * \value CborErrorIllegalNumber        An illegal initial byte (encoding unspecified additional information) was found
+ * \value CborErrorIllegalSimpleType    An illegal encoding of a CBOR Simple Type of value less than 32 was found
+ * \omitvalue CborErrorUnknownSimpleType
+ * \omitvalue CborErrorUnknownTag
+ * \omitvalue CborErrorInappropriateTagForType
+ * \omitvalue CborErrorDuplicateObjectKeys
+ * \value CborErrorInvalidUtf8TextString Illegal UTF-8 encoding found while parsing CBOR Text String
+ * \value CborErrorTooManyItems         Too many items were added to CBOR map or array of pre-determined length
+ * \value CborErrorTooFewItems          Too few items were added to CBOR map or array of pre-determeined length
+ * \value CborErrorDataTooLarge         Data item size exceeds TinyCBOR's implementation limits
+ * \value CborErrorNestingTooDeep       Data item nesting exceeds TinyCBOR's implementation limits
+ * \omitvalue CborErrorUnsupportedType
+ * \value CborErrorJsonObjectKeyIsAggregate Conversion to JSON failed because the key in a map is a CBOR map or array
+ * \value CborErrorJsonObjectKeyNotString Conversion to JSON failed because the key in a map is not a text string
+ * \value CborErrorOutOfMemory          During CBOR encoding, the buffer provided is insufficient for encoding the data item;
+ *                                      in other situations, TinyCBOR failed to allocate memory
+ * \value CborErrorInternalError        An internal error occurred in TinyCBOR
+ */
+
+/**
+ * \ingroup CborGlobals
+ * Returns the error string corresponding to the CBOR error condition \a error.
+ */
+const char *cbor_error_string(CborError error)
+{
+    switch (error) {
+    case CborNoError:
+        return "";
+
+    case CborUnknownError:
+        return _("unknown error");
+
+    case CborErrorOutOfMemory:
+        return _("out of memory/need more memory");
+
+    case CborErrorUnknownLength:
+        return _("unknown length (attempted to get the length of a map/array/string of indeterminate length");
+
+    case CborErrorAdvancePastEOF:
+        return _("attempted to advance past EOF");
+
+    case CborErrorIO:
+        return _("I/O error");
+
+    case CborErrorGarbageAtEnd:
+        return _("garbage after the end of the content");
+
+    case CborErrorUnexpectedEOF:
+        return _("unexpected end of data");
+
+    case CborErrorUnexpectedBreak:
+        return _("unexpected 'break' byte");
+
+    case CborErrorUnknownType:
+        return _("illegal byte (encodes future extension type)");
+
+    case CborErrorIllegalType:
+        return _("mismatched string type in chunked string");
+
+    case CborErrorIllegalNumber:
+        return _("illegal initial byte (encodes unspecified additional information)");
+
+    case CborErrorIllegalSimpleType:
+        return _("illegal encoding of simple type smaller than 32");
+
+    case CborErrorUnknownSimpleType:
+        return _("unknown simple type");
+
+    case CborErrorUnknownTag:
+        return _("unknown tag");
+
+    case CborErrorInappropriateTagForType:
+        return _("inappropriate tag for type");
+
+    case CborErrorDuplicateObjectKeys:
+        return _("duplicate keys in object");
+
+    case CborErrorInvalidUtf8TextString:
+        return _("invalid UTF-8 content in string");
+
+    case CborErrorTooManyItems:
+        return _("too many items added to encoder");
+
+    case CborErrorTooFewItems:
+        return _("too few items added to encoder");
+
+    case CborErrorDataTooLarge:
+        return _("internal error: data too large");
+
+    case CborErrorNestingTooDeep:
+        return _("internal error: too many nested containers found in recursive function");
+
+    case CborErrorUnsupportedType:
+        return _("unsupported type");
+
+    case CborErrorJsonObjectKeyIsAggregate:
+        return _("conversion to JSON failed: key in object is an array or map");
+
+    case CborErrorJsonObjectKeyNotString:
+        return _("conversion to JSON failed: key in object is not a string");
+
+    case CborErrorJsonNotImplemented:
+        return _("conversion to JSON failed: open_memstream unavailable");
+
+    case CborErrorInternalError:
+        return _("internal error");
+    }
+    return cbor_error_string(CborUnknownError);
+}


[02/49] incubator-mynewt-core git commit: move crc and cbmem to util

Posted by st...@apache.org.
move crc and cbmem to util


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/54fbe73d
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/54fbe73d
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/54fbe73d

Branch: refs/heads/develop
Commit: 54fbe73d8949e4066e3f11f77a916780cd44e5b9
Parents: 6a7432f
Author: Sterling Hughes <st...@apache.org>
Authored: Wed Sep 28 16:48:03 2016 -0700
Committer: Sterling Hughes <st...@apache.org>
Committed: Wed Sep 28 18:32:22 2016 -0700

----------------------------------------------------------------------
 boot/boot_serial/pkg.yml                   |   2 +-
 encoding/crc/include/crc/base64.h          |  32 ---
 encoding/crc/include/crc/crc16.h           |  36 ---
 encoding/crc/include/crc/crc8.h            |  32 ---
 encoding/crc/include/crc/hex.h             |  25 ---
 encoding/crc/pkg.yml                       |  28 ---
 encoding/crc/src/crc16.c                   |  83 -------
 encoding/crc/src/crc8.c                    |  74 -------
 encoding/crc/test/pkg.yml                  |  30 ---
 encoding/crc/test/src/encoding_test.c      |  46 ----
 encoding/crc/test/src/encoding_test_priv.h |  25 ---
 encoding/crc/test/src/hex_test.c           | 125 -----------
 fs/fcb/pkg.yml                             |   2 +-
 fs/nffs/pkg.yml                            |   2 +-
 sys/shell/pkg.yml                          |   2 +-
 util/cbmem/include/cbmem/cbmem.h           |  66 ++++++
 util/cbmem/pkg.yml                         |  30 +++
 util/cbmem/src/cbmem.c                     | 277 ++++++++++++++++++++++++
 util/cbmem/test/pkg.yml                    |  30 +++
 util/cbmem/test/src/cbmem_test.c           | 176 +++++++++++++++
 util/cbmem/test/src/util_test.c            |  53 +++++
 util/cbmem/test/src/util_test_priv.h       |  25 +++
 util/crc/include/crc/crc16.h               |  36 +++
 util/crc/include/crc/crc8.h                |  32 +++
 util/crc/pkg.yml                           |  28 +++
 util/crc/src/crc16.c                       |  83 +++++++
 util/crc/src/crc8.c                        |  74 +++++++
 util/crc/test/pkg.yml                      |  30 +++
 util/crc/test/src/encoding_test.c          |  46 ++++
 util/crc/test/src/encoding_test_priv.h     |  25 +++
 util/crc/test/src/hex_test.c               | 125 +++++++++++
 31 files changed, 1140 insertions(+), 540 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/54fbe73d/boot/boot_serial/pkg.yml
----------------------------------------------------------------------
diff --git a/boot/boot_serial/pkg.yml b/boot/boot_serial/pkg.yml
index 69773a1..b2a9308 100644
--- a/boot/boot_serial/pkg.yml
+++ b/boot/boot_serial/pkg.yml
@@ -30,7 +30,7 @@ pkg.deps:
     - kernel/os
     - boot/bootutil
     - encoding/base64
-    - encoding/crc
+    - util/crc
 
 pkg.req_apis:
     - console

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/54fbe73d/encoding/crc/include/crc/base64.h
----------------------------------------------------------------------
diff --git a/encoding/crc/include/crc/base64.h b/encoding/crc/include/crc/base64.h
deleted file mode 100644
index 8e0c045..0000000
--- a/encoding/crc/include/crc/base64.h
+++ /dev/null
@@ -1,32 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 __UTIL_BASE64_H
-#define __UTIL_BASE64_H
-
-#include <stdint.h>
-#include <string.h>
-
-int base64_encode(const void *, int, char *, uint8_t);
-int base64_decode(const char *, void *buf);
-int base64_pad(char *, int);
-int base64_decode_len(const char *str);
-
-#define BASE64_ENCODE_SIZE(__size) ((((__size) * 4) / 3) + 4)
-
-#endif /* __UTIL_BASE64_H__ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/54fbe73d/encoding/crc/include/crc/crc16.h
----------------------------------------------------------------------
diff --git a/encoding/crc/include/crc/crc16.h b/encoding/crc/include/crc/crc16.h
deleted file mode 100644
index b9b965f..0000000
--- a/encoding/crc/include/crc/crc16.h
+++ /dev/null
@@ -1,36 +0,0 @@
-/*	
- * Copyright 2001-2010 Georges Menie (www.menie.org)
- * 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 the University of California, Berkeley 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 REGENTS 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 REGENTS AND 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.
- */
-
-#ifndef _CRC16_H_
-#define _CRC16_H_
-
-#include <inttypes.h>
-
-#define CRC16_INITIAL_CRC       0       /* what to seed crc16 with */
-unsigned short crc16_ccitt(uint16_t initial_crc, const void *buf, int len);
-
-#endif /* _CRC16_H_ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/54fbe73d/encoding/crc/include/crc/crc8.h
----------------------------------------------------------------------
diff --git a/encoding/crc/include/crc/crc8.h b/encoding/crc/include/crc/crc8.h
deleted file mode 100644
index 336acca..0000000
--- a/encoding/crc/include/crc/crc8.h
+++ /dev/null
@@ -1,32 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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.
- */
-
-/*
- * CRC8-CCITT, with normal polynomial; 0x07.
- */
-
-#ifndef _UTIL_CRC8_H_
-#define _UTIL_CRC8_H_
-
-#include <inttypes.h>
-
-uint8_t crc8_init(void);
-uint8_t crc8_calc(uint8_t val, void *buf, int cnt);
-
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/54fbe73d/encoding/crc/include/crc/hex.h
----------------------------------------------------------------------
diff --git a/encoding/crc/include/crc/hex.h b/encoding/crc/include/crc/hex.h
deleted file mode 100644
index 1e9d8c8..0000000
--- a/encoding/crc/include/crc/hex.h
+++ /dev/null
@@ -1,25 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 _UTIL_HEX_H_
-#define _UTIL_HEX_H_
-
-char *hex_format(void *src_v, int src_len, char *dst, int dst_len);
-int hex_parse(char *src, int src_len, void *dst_v, int dst_len);
-
-#endif /* _UTIL_HEX_H_ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/54fbe73d/encoding/crc/pkg.yml
----------------------------------------------------------------------
diff --git a/encoding/crc/pkg.yml b/encoding/crc/pkg.yml
deleted file mode 100644
index 49e531e..0000000
--- a/encoding/crc/pkg.yml
+++ /dev/null
@@ -1,28 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you 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.
-#
-
-pkg.name: encoding/crc
-pkg.description: Library containing encoding functions
-pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
-pkg.homepage: "http://mynewt.apache.org/"
-pkg.keywords:
-    - crc16 
-    - crc32
-    - crc8
-    - crc

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/54fbe73d/encoding/crc/src/crc16.c
----------------------------------------------------------------------
diff --git a/encoding/crc/src/crc16.c b/encoding/crc/src/crc16.c
deleted file mode 100644
index 6ece419..0000000
--- a/encoding/crc/src/crc16.c
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright 2001-2010 Georges Menie (www.menie.org)
- * 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 the University of California, Berkeley 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 REGENTS 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 REGENTS AND 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 <inttypes.h>
-#include "crc/crc16.h"
-
-/* CRC16 implementation acording to CCITT standards */
-
-static const uint16_t crc16tab[256]= {
-    0x0000,0x1021,0x2042,0x3063,0x4084,0x50a5,0x60c6,0x70e7,
-    0x8108,0x9129,0xa14a,0xb16b,0xc18c,0xd1ad,0xe1ce,0xf1ef,
-    0x1231,0x0210,0x3273,0x2252,0x52b5,0x4294,0x72f7,0x62d6,
-    0x9339,0x8318,0xb37b,0xa35a,0xd3bd,0xc39c,0xf3ff,0xe3de,
-    0x2462,0x3443,0x0420,0x1401,0x64e6,0x74c7,0x44a4,0x5485,
-    0xa56a,0xb54b,0x8528,0x9509,0xe5ee,0xf5cf,0xc5ac,0xd58d,
-    0x3653,0x2672,0x1611,0x0630,0x76d7,0x66f6,0x5695,0x46b4,
-    0xb75b,0xa77a,0x9719,0x8738,0xf7df,0xe7fe,0xd79d,0xc7bc,
-    0x48c4,0x58e5,0x6886,0x78a7,0x0840,0x1861,0x2802,0x3823,
-    0xc9cc,0xd9ed,0xe98e,0xf9af,0x8948,0x9969,0xa90a,0xb92b,
-    0x5af5,0x4ad4,0x7ab7,0x6a96,0x1a71,0x0a50,0x3a33,0x2a12,
-    0xdbfd,0xcbdc,0xfbbf,0xeb9e,0x9b79,0x8b58,0xbb3b,0xab1a,
-    0x6ca6,0x7c87,0x4ce4,0x5cc5,0x2c22,0x3c03,0x0c60,0x1c41,
-    0xedae,0xfd8f,0xcdec,0xddcd,0xad2a,0xbd0b,0x8d68,0x9d49,
-    0x7e97,0x6eb6,0x5ed5,0x4ef4,0x3e13,0x2e32,0x1e51,0x0e70,
-    0xff9f,0xefbe,0xdfdd,0xcffc,0xbf1b,0xaf3a,0x9f59,0x8f78,
-    0x9188,0x81a9,0xb1ca,0xa1eb,0xd10c,0xc12d,0xf14e,0xe16f,
-    0x1080,0x00a1,0x30c2,0x20e3,0x5004,0x4025,0x7046,0x6067,
-    0x83b9,0x9398,0xa3fb,0xb3da,0xc33d,0xd31c,0xe37f,0xf35e,
-    0x02b1,0x1290,0x22f3,0x32d2,0x4235,0x5214,0x6277,0x7256,
-    0xb5ea,0xa5cb,0x95a8,0x8589,0xf56e,0xe54f,0xd52c,0xc50d,
-    0x34e2,0x24c3,0x14a0,0x0481,0x7466,0x6447,0x5424,0x4405,
-    0xa7db,0xb7fa,0x8799,0x97b8,0xe75f,0xf77e,0xc71d,0xd73c,
-    0x26d3,0x36f2,0x0691,0x16b0,0x6657,0x7676,0x4615,0x5634,
-    0xd94c,0xc96d,0xf90e,0xe92f,0x99c8,0x89e9,0xb98a,0xa9ab,
-    0x5844,0x4865,0x7806,0x6827,0x18c0,0x08e1,0x3882,0x28a3,
-    0xcb7d,0xdb5c,0xeb3f,0xfb1e,0x8bf9,0x9bd8,0xabbb,0xbb9a,
-    0x4a75,0x5a54,0x6a37,0x7a16,0x0af1,0x1ad0,0x2ab3,0x3a92,
-    0xfd2e,0xed0f,0xdd6c,0xcd4d,0xbdaa,0xad8b,0x9de8,0x8dc9,
-    0x7c26,0x6c07,0x5c64,0x4c45,0x3ca2,0x2c83,0x1ce0,0x0cc1,
-    0xef1f,0xff3e,0xcf5d,0xdf7c,0xaf9b,0xbfba,0x8fd9,0x9ff8,
-    0x6e17,0x7e36,0x4e55,0x5e74,0x2e93,0x3eb2,0x0ed1,0x1ef0
-};
-
-uint16_t
-crc16_ccitt(uint16_t initial_crc, const void *buf, int len)
-{
-    const uint8_t *ptr;
-    uint16_t crc;
-    int counter;
-
-    crc = initial_crc;
-    ptr = buf;
-
-    for (counter = 0; counter < len; counter++) {
-        crc = (crc<<8) ^ crc16tab[((crc>>8) ^ *ptr++)&0x00FF];
-    }
-
-    return crc;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/54fbe73d/encoding/crc/src/crc8.c
----------------------------------------------------------------------
diff --git a/encoding/crc/src/crc8.c b/encoding/crc/src/crc8.c
deleted file mode 100644
index 384acb2..0000000
--- a/encoding/crc/src/crc8.c
+++ /dev/null
@@ -1,74 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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.
- */
-
-/*
- * Table computation:
- *
- * void
- * gen_small_table(uint8_t poly)
- * {
- *      int i;
- *	int j;
- *	uint8_t curr;
- *
- *	for (i = 0; i < 16; i++) {
- *		curr = i;
- *
- *		for (j = 0; j < 8; j++)  {
- *			if ((curr & 0x80) != 0) {
- *				curr = (curr << 1) ^ poly;
- *			} else {
- *				curr <<= 1;
- *			}
- *		}
- *
- *		small_table[i] = curr;
- *
- *		printf("0x%x, ", small_table[i]);
- *	}
- *	printf("\n");
- *}
- */
-
-#include "crc/crc8.h"
-
-static uint8_t crc8_small_table[16] = {
-    0x00, 0x07, 0x0e, 0x09, 0x1c, 0x1b, 0x12, 0x15,
-    0x38, 0x3f, 0x36, 0x31, 0x24, 0x23, 0x2a, 0x2d
-};
-
-uint8_t
-crc8_init(void)
-{
-    return 0xff;
-}
-
-uint8_t
-crc8_calc(uint8_t val, void *buf, int cnt)
-{
-	int i;
-	uint8_t *p = buf;
-
-	for (i = 0; i < cnt; i++) {
-		val ^= p[i];
-		val = (val << 4) ^ crc8_small_table[val >> 4];
-		val = (val << 4) ^ crc8_small_table[val >> 4];
-	}
-	return val;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/54fbe73d/encoding/crc/test/pkg.yml
----------------------------------------------------------------------
diff --git a/encoding/crc/test/pkg.yml b/encoding/crc/test/pkg.yml
deleted file mode 100644
index dac3cb1..0000000
--- a/encoding/crc/test/pkg.yml
+++ /dev/null
@@ -1,30 +0,0 @@
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you 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.
-#
-pkg.name: crypto/encoding/test
-pkg.type: unittest
-pkg.description: "Crypto encoding unit tests."
-pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
-pkg.homepage: "http://mynewt.apache.org/"
-pkg.keywords:
-
-pkg.deps: 
-    - libs/testutil
-    - libs/util
-
-pkg.deps.SELFTEST:
-    - libs/console/stub

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/54fbe73d/encoding/crc/test/src/encoding_test.c
----------------------------------------------------------------------
diff --git a/encoding/crc/test/src/encoding_test.c b/encoding/crc/test/src/encoding_test.c
deleted file mode 100644
index b21fee8..0000000
--- a/encoding/crc/test/src/encoding_test.c
+++ /dev/null
@@ -1,46 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include <assert.h>
-#include <stddef.h>
-#include "syscfg/syscfg.h"
-#include "testutil/testutil.h"
-#include "encoding_test_priv.h"
-
-
-int
-hex_fmt_test_all(void)
-{
-    hex_fmt_test_suite();
-    return tu_case_failed;
-}
-
-#if MYNEWT_VAL(SELFTEST)
-
-int
-main(int argc, char **argv)
-{
-    tu_config.tc_print_results = 1;
-    tu_init();
-
-    hex_fmt_test_all();
-    return tu_any_failed;
-}
-
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/54fbe73d/encoding/crc/test/src/encoding_test_priv.h
----------------------------------------------------------------------
diff --git a/encoding/crc/test/src/encoding_test_priv.h b/encoding/crc/test/src/encoding_test_priv.h
deleted file mode 100644
index fc2fcac..0000000
--- a/encoding/crc/test/src/encoding_test_priv.h
+++ /dev/null
@@ -1,25 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 __ENCODING_TEST_PRIV_
-#define __ENCODING_TEST_PRIV_
-
-int hex_fmt_test_suite(void);
-
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/54fbe73d/encoding/crc/test/src/hex_test.c
----------------------------------------------------------------------
diff --git a/encoding/crc/test/src/hex_test.c b/encoding/crc/test/src/hex_test.c
deleted file mode 100644
index 8183425..0000000
--- a/encoding/crc/test/src/hex_test.c
+++ /dev/null
@@ -1,125 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-#include <stdio.h>
-#include <string.h>
-
-#include "testutil/testutil.h"
-#include "util/hex.h"
-
-TEST_CASE(hex2str)
-{
-    int i;
-    char *ret;
-    char cmp_data[8];
-
-    struct {
-        char *in;
-        int inlen;
-        char *out;
-        int outlen;
-    } test_data[] = {
-        [0] = {
-            .in = "\x01",
-            .inlen = 1,
-            .out = "01",
-            .outlen = 2,
-        },
-        [1] = {
-            .in = "\xaf\xf2",
-            .inlen = 2,
-            .out = "aff2",
-            .outlen = 4,
-        }
-    };
-
-    for (i = 0; i < sizeof(test_data) / sizeof(test_data[0]); i++) {
-        ret = hex_format(test_data[i].in, test_data[i].inlen,
-          cmp_data, sizeof(cmp_data));
-        TEST_ASSERT(ret == cmp_data);
-        TEST_ASSERT(strlen(cmp_data) == test_data[i].outlen);
-        TEST_ASSERT(!strcmp(test_data[i].out, cmp_data));
-    }
-
-    /*
-     * Test not enough space. Must have space for '\0' at the end.
-     */
-    ret = hex_format("\x01\x02", 2, cmp_data, 1);
-    TEST_ASSERT(ret == NULL);
-
-    ret = hex_format("\x01\x02", 2, cmp_data, 2);
-    TEST_ASSERT(ret == NULL);
-}
-
-TEST_CASE(str2hex)
-{
-    int i;
-    char cmp_data[8];
-    int rc;
-
-    struct {
-        char *in;
-        int inlen;
-        char *out;
-        int outlen;
-    } test_data[] = {
-        [0] = {
-            .in = "01",
-            .inlen = 2,
-            .out = "\x01",
-            .outlen = 1,
-        },
-        [1] = {
-            .in = "AfF2",
-            .inlen = 4,
-            .out = "\xaf\xf2",
-            .outlen = 2,
-        }
-    };
-
-    for (i = 0; i < sizeof(test_data) / sizeof(test_data[0]); i++) {
-        rc = hex_parse(test_data[i].in, test_data[i].inlen,
-          cmp_data, sizeof(cmp_data));
-        TEST_ASSERT(rc == test_data[i].outlen);
-        TEST_ASSERT(!memcmp(test_data[i].out, cmp_data, rc));
-    }
-
-    /*
-     * Test invalid input
-     */
-    rc = hex_parse("HJ", 2, cmp_data, sizeof(cmp_data));
-    TEST_ASSERT(rc < 0);
-
-    rc = hex_parse("a", 1, cmp_data, sizeof(cmp_data));
-    TEST_ASSERT(rc < 0);
-
-    rc = hex_parse("0102", 4, cmp_data, 1);
-    TEST_ASSERT(rc < 0);
-
-    /*
-     * This should be valid.
-     */
-    rc = hex_parse("0102", 4, cmp_data, 2);
-    TEST_ASSERT(rc == 2);
-}
-
-TEST_SUITE(hex_fmt_test_suite)
-{
-    hex2str();
-    str2hex();
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/54fbe73d/fs/fcb/pkg.yml
----------------------------------------------------------------------
diff --git a/fs/fcb/pkg.yml b/fs/fcb/pkg.yml
index 9b90bb9..daa5557 100644
--- a/fs/fcb/pkg.yml
+++ b/fs/fcb/pkg.yml
@@ -26,4 +26,4 @@ pkg.keywords:
 
 pkg.deps:
     - kernel/os
-    - encoding/crc
+    - util/crc

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/54fbe73d/fs/nffs/pkg.yml
----------------------------------------------------------------------
diff --git a/fs/nffs/pkg.yml b/fs/nffs/pkg.yml
index 19d91be..b012149 100644
--- a/fs/nffs/pkg.yml
+++ b/fs/nffs/pkg.yml
@@ -28,7 +28,7 @@ pkg.keywords:
 
 pkg.deps:
     - fs/fs
-    - encoding/crc
+    - util/crc
     - hw/hal
     - kernel/os
     - test/testutil

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/54fbe73d/sys/shell/pkg.yml
----------------------------------------------------------------------
diff --git a/sys/shell/pkg.yml b/sys/shell/pkg.yml
index c4449e5..f704169 100644
--- a/sys/shell/pkg.yml
+++ b/sys/shell/pkg.yml
@@ -27,7 +27,7 @@ pkg.deps:
     - kernel/os
     - libs/util
     - encoding/base64 
-    - encoding/crc
+    - util/crc
 pkg.req_apis:
     - console
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/54fbe73d/util/cbmem/include/cbmem/cbmem.h
----------------------------------------------------------------------
diff --git a/util/cbmem/include/cbmem/cbmem.h b/util/cbmem/include/cbmem/cbmem.h
new file mode 100644
index 0000000..42decfb
--- /dev/null
+++ b/util/cbmem/include/cbmem/cbmem.h
@@ -0,0 +1,66 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 __UTIL_CBMEM_H__ 
+#define __UTIL_CBMEM_H__
+
+#include <os/os.h>
+
+struct cbmem_entry_hdr {
+    uint16_t ceh_len;
+    uint16_t ceh_flags;
+} __attribute__((packed));
+
+struct cbmem {
+    struct os_mutex c_lock;
+
+    struct cbmem_entry_hdr *c_entry_start;
+    struct cbmem_entry_hdr *c_entry_end;
+    uint8_t *c_buf;
+    uint8_t *c_buf_end;
+    uint8_t *c_buf_cur_end;
+};
+
+struct cbmem_iter {
+    struct cbmem_entry_hdr *ci_start;
+    struct cbmem_entry_hdr *ci_cur;
+    struct cbmem_entry_hdr *ci_end;
+};
+
+#define CBMEM_ENTRY_SIZE(__p) (sizeof(struct cbmem_entry_hdr) \
+        + ((struct cbmem_entry_hdr *) (__p))->ceh_len)
+#define CBMEM_ENTRY_NEXT(__p) ((struct cbmem_entry_hdr *) \
+        ((uint8_t *) (__p) + CBMEM_ENTRY_SIZE(__p)))
+
+typedef int (*cbmem_walk_func_t)(struct cbmem *, struct cbmem_entry_hdr *, 
+        void *arg);
+
+int cbmem_lock_acquire(struct cbmem *cbmem);
+int cbmem_lock_release(struct cbmem *cbmem);
+int cbmem_init(struct cbmem *cbmem, void *buf, uint32_t buf_len);
+int cbmem_append(struct cbmem *cbmem, void *data, uint16_t len);
+void cbmem_iter_start(struct cbmem *cbmem, struct cbmem_iter *iter);
+struct cbmem_entry_hdr *cbmem_iter_next(struct cbmem *cbmem, 
+        struct cbmem_iter *iter);
+int cbmem_read(struct cbmem *cbmem, struct cbmem_entry_hdr *hdr, void *buf, 
+        uint16_t off, uint16_t len);
+int cbmem_walk(struct cbmem *cbmem, cbmem_walk_func_t walk_func, void *arg);
+
+int cbmem_flush(struct cbmem *);
+
+#endif /* __UTIL_CBMEM_H__ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/54fbe73d/util/cbmem/pkg.yml
----------------------------------------------------------------------
diff --git a/util/cbmem/pkg.yml b/util/cbmem/pkg.yml
new file mode 100644
index 0000000..9957805
--- /dev/null
+++ b/util/cbmem/pkg.yml
@@ -0,0 +1,30 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+#
+
+pkg.name: libs/util
+pkg.description: Library containing miscellaneous utilities.
+pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
+pkg.homepage: "http://mynewt.apache.org/"
+pkg.keywords:
+    - base64
+    - circular buffer
+
+pkg.deps:
+    - hw/hal
+    - kernel/os

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/54fbe73d/util/cbmem/src/cbmem.c
----------------------------------------------------------------------
diff --git a/util/cbmem/src/cbmem.c b/util/cbmem/src/cbmem.c
new file mode 100644
index 0000000..63e098e
--- /dev/null
+++ b/util/cbmem/src/cbmem.c
@@ -0,0 +1,277 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include <os/os.h>
+#include <string.h>
+
+#include "cbmem/cbmem.h"
+
+
+int
+cbmem_init(struct cbmem *cbmem, void *buf, uint32_t buf_len)
+{
+    os_mutex_init(&cbmem->c_lock);
+
+    memset(cbmem, 0, sizeof(*cbmem));
+    cbmem->c_buf = buf;
+    cbmem->c_buf_end = buf + buf_len;
+
+    return (0);
+}
+
+int
+cbmem_lock_acquire(struct cbmem *cbmem)
+{
+    int rc;
+
+    if (!os_started()) {
+        return (0);
+    }
+
+    rc = os_mutex_pend(&cbmem->c_lock, OS_WAIT_FOREVER);
+    if (rc != 0) {
+        goto err;
+    }
+
+    return (0);
+err:
+    return (rc);
+}
+
+int
+cbmem_lock_release(struct cbmem *cbmem)
+{
+    int rc;
+
+    if (!os_started()) {
+        return (0);
+    }
+
+    rc = os_mutex_release(&cbmem->c_lock);
+    if (rc != 0) {
+        goto err;
+    }
+
+    return (0);
+err:
+    return (rc);
+}
+
+
+int
+cbmem_append(struct cbmem *cbmem, void *data, uint16_t len)
+{
+    struct cbmem_entry_hdr *dst;
+    uint8_t *start;
+    uint8_t *end;
+    int rc;
+
+    rc = cbmem_lock_acquire(cbmem);
+    if (rc != 0) {
+        goto err;
+    }
+
+    if (cbmem->c_entry_end) {
+        dst = CBMEM_ENTRY_NEXT(cbmem->c_entry_end);
+    } else {
+        dst = (struct cbmem_entry_hdr *) cbmem->c_buf;
+    }
+    end = (uint8_t *) dst + len + sizeof(*dst);
+
+    /* If this item would take us past the end of this buffer, then adjust
+     * the item to the beginning of the buffer.
+     */
+    if (end > cbmem->c_buf_end) {
+        cbmem->c_buf_cur_end = (uint8_t *) dst;
+        dst = (struct cbmem_entry_hdr *) cbmem->c_buf;
+        end = (uint8_t *) dst + len + sizeof(*dst);
+        if ((uint8_t *) cbmem->c_entry_start >= cbmem->c_buf_cur_end) {
+            cbmem->c_entry_start = (struct cbmem_entry_hdr *) cbmem->c_buf;
+        }
+    }
+
+    /* If the destination is prior to the start, and would overrwrite the
+     * start of the buffer, move start forward until you don't overwrite it
+     * anymore.
+     */
+    start = (uint8_t *) cbmem->c_entry_start;
+    if (start && (uint8_t *) dst < start + CBMEM_ENTRY_SIZE(start) &&
+            end > start) {
+        while (start < end) {
+            start = (uint8_t *) CBMEM_ENTRY_NEXT(start);
+            if (start == cbmem->c_buf_cur_end) {
+                start = cbmem->c_buf;
+                break;
+            }
+        }
+        cbmem->c_entry_start = (struct cbmem_entry_hdr *) start;
+    }
+
+    /* Copy the entry into the log
+     */
+    dst->ceh_len = len;
+    memcpy((uint8_t *) dst + sizeof(*dst), data, len);
+
+    cbmem->c_entry_end = dst;
+    if (!cbmem->c_entry_start) {
+        cbmem->c_entry_start = dst;
+    }
+
+    rc = cbmem_lock_release(cbmem);
+    if (rc != 0) {
+        goto err;
+    }
+
+    return (0);
+err:
+    return (-1);
+}
+
+void
+cbmem_iter_start(struct cbmem *cbmem, struct cbmem_iter *iter)
+{
+    iter->ci_start = cbmem->c_entry_start;
+    iter->ci_cur = cbmem->c_entry_start;
+    iter->ci_end = cbmem->c_entry_end;
+}
+
+struct cbmem_entry_hdr *
+cbmem_iter_next(struct cbmem *cbmem, struct cbmem_iter *iter)
+{
+    struct cbmem_entry_hdr *hdr;
+
+    if (iter->ci_start > iter->ci_end) {
+        hdr = iter->ci_cur;
+        iter->ci_cur = CBMEM_ENTRY_NEXT(iter->ci_cur);
+
+        if ((uint8_t *) iter->ci_cur >= cbmem->c_buf_cur_end) {
+            iter->ci_cur = (struct cbmem_entry_hdr *) cbmem->c_buf;
+            iter->ci_start = (struct cbmem_entry_hdr *) cbmem->c_buf;
+        }
+    } else {
+        hdr = iter->ci_cur;
+        if (!iter->ci_cur) {
+            goto err;
+        }
+
+        if (hdr == CBMEM_ENTRY_NEXT(iter->ci_end)) {
+            hdr = NULL;
+        } else {
+            iter->ci_cur = CBMEM_ENTRY_NEXT(iter->ci_cur);
+        }
+    }
+
+err:
+    return (hdr);
+}
+
+int
+cbmem_flush(struct cbmem *cbmem)
+{
+    int rc;
+
+    rc = cbmem_lock_acquire(cbmem);
+    if (rc != 0) {
+        goto err;
+    }
+
+    cbmem->c_entry_start = NULL;
+    cbmem->c_entry_end = NULL;
+    cbmem->c_buf_cur_end = NULL;
+
+    rc = cbmem_lock_release(cbmem);
+    if (rc != 0) {
+        goto err;
+    }
+
+    return (0);
+err:
+    return (rc);
+}
+
+int
+cbmem_read(struct cbmem *cbmem, struct cbmem_entry_hdr *hdr, void *buf,
+        uint16_t off, uint16_t len)
+{
+    int rc;
+
+    rc = cbmem_lock_acquire(cbmem);
+    if (rc != 0) {
+        goto err;
+    }
+
+    /* Only read the maximum number of bytes, if we exceed that,
+     * truncate the read.
+     */
+    if (off + len > hdr->ceh_len) {
+        len = hdr->ceh_len - off;
+    }
+
+    if (off > hdr->ceh_len) {
+        rc = -1;
+        cbmem_lock_release(cbmem);
+        goto err;
+    }
+
+    memcpy(buf, (uint8_t *) hdr + sizeof(*hdr) + off, len);
+
+    rc = cbmem_lock_release(cbmem);
+    if (rc != 0) {
+        goto err;
+    }
+
+    return (len);
+err:
+    return (-1);
+}
+
+int
+cbmem_walk(struct cbmem *cbmem, cbmem_walk_func_t walk_func, void *arg)
+{
+    struct cbmem_entry_hdr *hdr;
+    struct cbmem_iter iter;
+    int rc;
+
+    rc = cbmem_lock_acquire(cbmem);
+    if (rc != 0) {
+        goto err;
+    }
+
+    cbmem_iter_start(cbmem, &iter);
+    while (1) {
+        hdr = cbmem_iter_next(cbmem, &iter);
+        if (hdr == NULL) {
+            break;
+        }
+
+        rc = walk_func(cbmem, hdr, arg);
+        if (rc == 1) {
+            break;
+        }
+    }
+
+    rc = cbmem_lock_release(cbmem);
+    if (rc != 0) {
+        goto err;
+    }
+
+    return (0);
+err:
+    return (rc);
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/54fbe73d/util/cbmem/test/pkg.yml
----------------------------------------------------------------------
diff --git a/util/cbmem/test/pkg.yml b/util/cbmem/test/pkg.yml
new file mode 100644
index 0000000..b03db98
--- /dev/null
+++ b/util/cbmem/test/pkg.yml
@@ -0,0 +1,30 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+#
+pkg.name: util/cbmem/test
+pkg.type: unittest
+pkg.description: "Util unit tests."
+pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
+pkg.homepage: "http://mynewt.apache.org/"
+pkg.keywords:
+
+pkg.deps: 
+    - test/testutil
+    - util/cbmem
+
+pkg.deps.SELFTEST:
+    - sys/console/stub

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/54fbe73d/util/cbmem/test/src/cbmem_test.c
----------------------------------------------------------------------
diff --git a/util/cbmem/test/src/cbmem_test.c b/util/cbmem/test/src/cbmem_test.c
new file mode 100644
index 0000000..b486334
--- /dev/null
+++ b/util/cbmem/test/src/cbmem_test.c
@@ -0,0 +1,176 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+#include <stdio.h>
+#include <string.h>
+
+#include "testutil/testutil.h"
+#include "util/cbmem.h" 
+
+#define CBMEM1_BUF_SIZE (64 * 1024)
+
+struct cbmem cbmem1;
+uint8_t cbmem1_buf[CBMEM1_BUF_SIZE];
+uint8_t cbmem1_entry[1024];
+
+/*
+ * Things to test.
+ *
+ * - Wrap of the circular buffer.  
+ * - Reading through all entries.
+ */
+
+static void
+setup_cbmem1(void)
+{
+    int i;
+    int rc;
+
+    rc = cbmem_init(&cbmem1, cbmem1_buf, CBMEM1_BUF_SIZE);
+    TEST_ASSERT_FATAL(rc == 0, "cbmem_init() failed, non-zero RC = %d", rc);
+
+    memset(cbmem1_entry, 0xff, sizeof(cbmem1_entry));
+
+    /* Insert 65 1024 entries, and overflow buffer.  
+     * This should overflow two entries, because the buffer is sized for 64 
+     * entries, and then the headers themselves will eat into one of the entries, 
+     * so there should be a total of 63 entries.
+     * Ensure no data corruption.
+     */
+    for (i = 0; i < 65; i++) {
+        cbmem1_entry[0] = i;
+        rc = cbmem_append(&cbmem1, cbmem1_entry, sizeof(cbmem1_entry));
+        TEST_ASSERT_FATAL(rc == 0, "Could not append entry %d, rc = %d", i, rc);
+    }
+}
+
+static int 
+cbmem_test_case_1_walk(struct cbmem *cbmem, struct cbmem_entry_hdr *hdr, 
+        void *arg)
+{
+    uint8_t expected;
+    uint8_t actual;
+    int rc;
+
+    expected = *(uint8_t *) arg;
+
+    rc = cbmem_read(cbmem, hdr, &actual, 0, sizeof(actual));
+    TEST_ASSERT_FATAL(rc == 1, "Couldn't read 1 byte from cbmem");
+    TEST_ASSERT_FATAL(actual == expected, 
+            "Actual doesn't equal expected (%d = %d)", actual, expected);
+
+    *(uint8_t *) arg = ++expected;
+
+    return (0);
+}
+
+TEST_CASE(cbmem_test_case_1) 
+{
+    int i;
+    int rc;
+
+    /* i starts at 2, for the 2 overwritten entries. */
+    i = 2;
+    rc = cbmem_walk(&cbmem1, cbmem_test_case_1_walk, &i);
+    TEST_ASSERT_FATAL(rc == 0, "Could not walk cbmem tree!  rc = %d", rc);
+    TEST_ASSERT_FATAL(i == 65, 
+            "Did not go through every element of walk, %d processed", i - 2);
+
+}
+
+TEST_CASE(cbmem_test_case_2)
+{
+    struct cbmem_entry_hdr *hdr;
+    struct cbmem_iter iter;
+    uint8_t i;
+    uint8_t val;
+    int rc;
+
+    i = 2;
+    cbmem_iter_start(&cbmem1, &iter);
+    while (1) {
+        hdr = cbmem_iter_next(&cbmem1, &iter);
+        if (hdr == NULL) {
+            break;
+        }
+
+        rc = cbmem_read(&cbmem1, hdr, &val, 0, sizeof(val));
+        TEST_ASSERT_FATAL(rc == 1, "Couldn't read 1 byte from cbmem");
+        TEST_ASSERT_FATAL(val == i, "Entry index does not match %d vs %d", 
+                val, i);
+
+        i++;
+    }
+
+    /* i starts at 2, for the 2 overwritten entries */
+    TEST_ASSERT_FATAL(i == 65, 
+            "Did not iterate through all 63 elements of CBMEM1, processed %d", 
+            i - 2);
+}
+
+TEST_CASE(cbmem_test_case_3)
+{
+    struct cbmem_entry_hdr *hdr;
+    struct cbmem_iter iter;
+    uint16_t off;
+    uint16_t len;
+    uint8_t buf[128];
+    int i;
+    int rc;
+
+    i = 0;
+    cbmem_iter_start(&cbmem1, &iter);
+    while (1) {
+        hdr = cbmem_iter_next(&cbmem1, &iter);
+        if (hdr == NULL) {
+            break;
+        }
+        
+        /* first ensure we can read the entire entry */
+        off = 0;
+        len = 0;
+        while (1) {
+            rc = cbmem_read(&cbmem1, hdr, buf, off, sizeof(buf));
+            TEST_ASSERT_FATAL(rc >= 0,
+                    "Error reading from buffer rc=%d, off=%d,len=%d", rc, off, 
+                    sizeof(buf));
+            if (rc == 0) {
+                break;
+            }
+            off += rc;
+            len += rc;
+        }
+        TEST_ASSERT_FATAL(len == 1024, 
+                "Couldn't read full entry, expected %d got %d", 1024, len);
+        i++;
+
+        /* go apesh*t, and read data out of bounds, see what we get. */
+        rc = cbmem_read(&cbmem1, hdr, buf, 2048, sizeof(buf));
+        TEST_ASSERT_FATAL(rc < 0, 
+                "Reading invalid should return error, instead %d returned.",
+                rc);
+    }
+}
+
+TEST_SUITE(cbmem_test_suite)
+{
+    setup_cbmem1();
+    cbmem_test_case_1();
+    cbmem_test_case_2();
+    cbmem_test_case_3();
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/54fbe73d/util/cbmem/test/src/util_test.c
----------------------------------------------------------------------
diff --git a/util/cbmem/test/src/util_test.c b/util/cbmem/test/src/util_test.c
new file mode 100644
index 0000000..4e21a9a
--- /dev/null
+++ b/util/cbmem/test/src/util_test.c
@@ -0,0 +1,53 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include <assert.h>
+#include <stddef.h>
+#include "syscfg/syscfg.h"
+#include "testutil/testutil.h"
+#include "util_test_priv.h"
+
+int
+util_test_all(void)
+{
+    cbmem_test_suite();
+    return tu_case_failed;
+}
+
+int
+hex_fmt_test_all(void)
+{
+    hex_fmt_test_suite();
+    return tu_case_failed;
+}
+
+#if MYNEWT_VAL(SELFTEST)
+
+int
+main(int argc, char **argv)
+{
+    tu_config.tc_print_results = 1;
+    tu_init();
+
+    util_test_all();
+    hex_fmt_test_all();
+    return tu_any_failed;
+}
+
+#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/54fbe73d/util/cbmem/test/src/util_test_priv.h
----------------------------------------------------------------------
diff --git a/util/cbmem/test/src/util_test_priv.h b/util/cbmem/test/src/util_test_priv.h
new file mode 100644
index 0000000..93289b8
--- /dev/null
+++ b/util/cbmem/test/src/util_test_priv.h
@@ -0,0 +1,25 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 __UTIL_TEST_PRIV_
+#define __UTIL_TEST_PRIV_
+
+int cbmem_test_suite(void);
+
+#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/54fbe73d/util/crc/include/crc/crc16.h
----------------------------------------------------------------------
diff --git a/util/crc/include/crc/crc16.h b/util/crc/include/crc/crc16.h
new file mode 100644
index 0000000..b9b965f
--- /dev/null
+++ b/util/crc/include/crc/crc16.h
@@ -0,0 +1,36 @@
+/*	
+ * Copyright 2001-2010 Georges Menie (www.menie.org)
+ * 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 the University of California, Berkeley 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 REGENTS 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 REGENTS AND 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.
+ */
+
+#ifndef _CRC16_H_
+#define _CRC16_H_
+
+#include <inttypes.h>
+
+#define CRC16_INITIAL_CRC       0       /* what to seed crc16 with */
+unsigned short crc16_ccitt(uint16_t initial_crc, const void *buf, int len);
+
+#endif /* _CRC16_H_ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/54fbe73d/util/crc/include/crc/crc8.h
----------------------------------------------------------------------
diff --git a/util/crc/include/crc/crc8.h b/util/crc/include/crc/crc8.h
new file mode 100644
index 0000000..336acca
--- /dev/null
+++ b/util/crc/include/crc/crc8.h
@@ -0,0 +1,32 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.
+ */
+
+/*
+ * CRC8-CCITT, with normal polynomial; 0x07.
+ */
+
+#ifndef _UTIL_CRC8_H_
+#define _UTIL_CRC8_H_
+
+#include <inttypes.h>
+
+uint8_t crc8_init(void);
+uint8_t crc8_calc(uint8_t val, void *buf, int cnt);
+
+#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/54fbe73d/util/crc/pkg.yml
----------------------------------------------------------------------
diff --git a/util/crc/pkg.yml b/util/crc/pkg.yml
new file mode 100644
index 0000000..d5fd15b
--- /dev/null
+++ b/util/crc/pkg.yml
@@ -0,0 +1,28 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+#
+
+pkg.name: util/crc
+pkg.description: Library containing encoding functions
+pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
+pkg.homepage: "http://mynewt.apache.org/"
+pkg.keywords:
+    - crc16 
+    - crc32
+    - crc8
+    - crc

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/54fbe73d/util/crc/src/crc16.c
----------------------------------------------------------------------
diff --git a/util/crc/src/crc16.c b/util/crc/src/crc16.c
new file mode 100644
index 0000000..6ece419
--- /dev/null
+++ b/util/crc/src/crc16.c
@@ -0,0 +1,83 @@
+/*
+ * Copyright 2001-2010 Georges Menie (www.menie.org)
+ * 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 the University of California, Berkeley 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 REGENTS 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 REGENTS AND 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 <inttypes.h>
+#include "crc/crc16.h"
+
+/* CRC16 implementation acording to CCITT standards */
+
+static const uint16_t crc16tab[256]= {
+    0x0000,0x1021,0x2042,0x3063,0x4084,0x50a5,0x60c6,0x70e7,
+    0x8108,0x9129,0xa14a,0xb16b,0xc18c,0xd1ad,0xe1ce,0xf1ef,
+    0x1231,0x0210,0x3273,0x2252,0x52b5,0x4294,0x72f7,0x62d6,
+    0x9339,0x8318,0xb37b,0xa35a,0xd3bd,0xc39c,0xf3ff,0xe3de,
+    0x2462,0x3443,0x0420,0x1401,0x64e6,0x74c7,0x44a4,0x5485,
+    0xa56a,0xb54b,0x8528,0x9509,0xe5ee,0xf5cf,0xc5ac,0xd58d,
+    0x3653,0x2672,0x1611,0x0630,0x76d7,0x66f6,0x5695,0x46b4,
+    0xb75b,0xa77a,0x9719,0x8738,0xf7df,0xe7fe,0xd79d,0xc7bc,
+    0x48c4,0x58e5,0x6886,0x78a7,0x0840,0x1861,0x2802,0x3823,
+    0xc9cc,0xd9ed,0xe98e,0xf9af,0x8948,0x9969,0xa90a,0xb92b,
+    0x5af5,0x4ad4,0x7ab7,0x6a96,0x1a71,0x0a50,0x3a33,0x2a12,
+    0xdbfd,0xcbdc,0xfbbf,0xeb9e,0x9b79,0x8b58,0xbb3b,0xab1a,
+    0x6ca6,0x7c87,0x4ce4,0x5cc5,0x2c22,0x3c03,0x0c60,0x1c41,
+    0xedae,0xfd8f,0xcdec,0xddcd,0xad2a,0xbd0b,0x8d68,0x9d49,
+    0x7e97,0x6eb6,0x5ed5,0x4ef4,0x3e13,0x2e32,0x1e51,0x0e70,
+    0xff9f,0xefbe,0xdfdd,0xcffc,0xbf1b,0xaf3a,0x9f59,0x8f78,
+    0x9188,0x81a9,0xb1ca,0xa1eb,0xd10c,0xc12d,0xf14e,0xe16f,
+    0x1080,0x00a1,0x30c2,0x20e3,0x5004,0x4025,0x7046,0x6067,
+    0x83b9,0x9398,0xa3fb,0xb3da,0xc33d,0xd31c,0xe37f,0xf35e,
+    0x02b1,0x1290,0x22f3,0x32d2,0x4235,0x5214,0x6277,0x7256,
+    0xb5ea,0xa5cb,0x95a8,0x8589,0xf56e,0xe54f,0xd52c,0xc50d,
+    0x34e2,0x24c3,0x14a0,0x0481,0x7466,0x6447,0x5424,0x4405,
+    0xa7db,0xb7fa,0x8799,0x97b8,0xe75f,0xf77e,0xc71d,0xd73c,
+    0x26d3,0x36f2,0x0691,0x16b0,0x6657,0x7676,0x4615,0x5634,
+    0xd94c,0xc96d,0xf90e,0xe92f,0x99c8,0x89e9,0xb98a,0xa9ab,
+    0x5844,0x4865,0x7806,0x6827,0x18c0,0x08e1,0x3882,0x28a3,
+    0xcb7d,0xdb5c,0xeb3f,0xfb1e,0x8bf9,0x9bd8,0xabbb,0xbb9a,
+    0x4a75,0x5a54,0x6a37,0x7a16,0x0af1,0x1ad0,0x2ab3,0x3a92,
+    0xfd2e,0xed0f,0xdd6c,0xcd4d,0xbdaa,0xad8b,0x9de8,0x8dc9,
+    0x7c26,0x6c07,0x5c64,0x4c45,0x3ca2,0x2c83,0x1ce0,0x0cc1,
+    0xef1f,0xff3e,0xcf5d,0xdf7c,0xaf9b,0xbfba,0x8fd9,0x9ff8,
+    0x6e17,0x7e36,0x4e55,0x5e74,0x2e93,0x3eb2,0x0ed1,0x1ef0
+};
+
+uint16_t
+crc16_ccitt(uint16_t initial_crc, const void *buf, int len)
+{
+    const uint8_t *ptr;
+    uint16_t crc;
+    int counter;
+
+    crc = initial_crc;
+    ptr = buf;
+
+    for (counter = 0; counter < len; counter++) {
+        crc = (crc<<8) ^ crc16tab[((crc>>8) ^ *ptr++)&0x00FF];
+    }
+
+    return crc;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/54fbe73d/util/crc/src/crc8.c
----------------------------------------------------------------------
diff --git a/util/crc/src/crc8.c b/util/crc/src/crc8.c
new file mode 100644
index 0000000..384acb2
--- /dev/null
+++ b/util/crc/src/crc8.c
@@ -0,0 +1,74 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.
+ */
+
+/*
+ * Table computation:
+ *
+ * void
+ * gen_small_table(uint8_t poly)
+ * {
+ *      int i;
+ *	int j;
+ *	uint8_t curr;
+ *
+ *	for (i = 0; i < 16; i++) {
+ *		curr = i;
+ *
+ *		for (j = 0; j < 8; j++)  {
+ *			if ((curr & 0x80) != 0) {
+ *				curr = (curr << 1) ^ poly;
+ *			} else {
+ *				curr <<= 1;
+ *			}
+ *		}
+ *
+ *		small_table[i] = curr;
+ *
+ *		printf("0x%x, ", small_table[i]);
+ *	}
+ *	printf("\n");
+ *}
+ */
+
+#include "crc/crc8.h"
+
+static uint8_t crc8_small_table[16] = {
+    0x00, 0x07, 0x0e, 0x09, 0x1c, 0x1b, 0x12, 0x15,
+    0x38, 0x3f, 0x36, 0x31, 0x24, 0x23, 0x2a, 0x2d
+};
+
+uint8_t
+crc8_init(void)
+{
+    return 0xff;
+}
+
+uint8_t
+crc8_calc(uint8_t val, void *buf, int cnt)
+{
+	int i;
+	uint8_t *p = buf;
+
+	for (i = 0; i < cnt; i++) {
+		val ^= p[i];
+		val = (val << 4) ^ crc8_small_table[val >> 4];
+		val = (val << 4) ^ crc8_small_table[val >> 4];
+	}
+	return val;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/54fbe73d/util/crc/test/pkg.yml
----------------------------------------------------------------------
diff --git a/util/crc/test/pkg.yml b/util/crc/test/pkg.yml
new file mode 100644
index 0000000..dac3cb1
--- /dev/null
+++ b/util/crc/test/pkg.yml
@@ -0,0 +1,30 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+#
+pkg.name: crypto/encoding/test
+pkg.type: unittest
+pkg.description: "Crypto encoding unit tests."
+pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
+pkg.homepage: "http://mynewt.apache.org/"
+pkg.keywords:
+
+pkg.deps: 
+    - libs/testutil
+    - libs/util
+
+pkg.deps.SELFTEST:
+    - libs/console/stub

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/54fbe73d/util/crc/test/src/encoding_test.c
----------------------------------------------------------------------
diff --git a/util/crc/test/src/encoding_test.c b/util/crc/test/src/encoding_test.c
new file mode 100644
index 0000000..b21fee8
--- /dev/null
+++ b/util/crc/test/src/encoding_test.c
@@ -0,0 +1,46 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include <assert.h>
+#include <stddef.h>
+#include "syscfg/syscfg.h"
+#include "testutil/testutil.h"
+#include "encoding_test_priv.h"
+
+
+int
+hex_fmt_test_all(void)
+{
+    hex_fmt_test_suite();
+    return tu_case_failed;
+}
+
+#if MYNEWT_VAL(SELFTEST)
+
+int
+main(int argc, char **argv)
+{
+    tu_config.tc_print_results = 1;
+    tu_init();
+
+    hex_fmt_test_all();
+    return tu_any_failed;
+}
+
+#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/54fbe73d/util/crc/test/src/encoding_test_priv.h
----------------------------------------------------------------------
diff --git a/util/crc/test/src/encoding_test_priv.h b/util/crc/test/src/encoding_test_priv.h
new file mode 100644
index 0000000..fc2fcac
--- /dev/null
+++ b/util/crc/test/src/encoding_test_priv.h
@@ -0,0 +1,25 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 __ENCODING_TEST_PRIV_
+#define __ENCODING_TEST_PRIV_
+
+int hex_fmt_test_suite(void);
+
+#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/54fbe73d/util/crc/test/src/hex_test.c
----------------------------------------------------------------------
diff --git a/util/crc/test/src/hex_test.c b/util/crc/test/src/hex_test.c
new file mode 100644
index 0000000..8183425
--- /dev/null
+++ b/util/crc/test/src/hex_test.c
@@ -0,0 +1,125 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+#include <stdio.h>
+#include <string.h>
+
+#include "testutil/testutil.h"
+#include "util/hex.h"
+
+TEST_CASE(hex2str)
+{
+    int i;
+    char *ret;
+    char cmp_data[8];
+
+    struct {
+        char *in;
+        int inlen;
+        char *out;
+        int outlen;
+    } test_data[] = {
+        [0] = {
+            .in = "\x01",
+            .inlen = 1,
+            .out = "01",
+            .outlen = 2,
+        },
+        [1] = {
+            .in = "\xaf\xf2",
+            .inlen = 2,
+            .out = "aff2",
+            .outlen = 4,
+        }
+    };
+
+    for (i = 0; i < sizeof(test_data) / sizeof(test_data[0]); i++) {
+        ret = hex_format(test_data[i].in, test_data[i].inlen,
+          cmp_data, sizeof(cmp_data));
+        TEST_ASSERT(ret == cmp_data);
+        TEST_ASSERT(strlen(cmp_data) == test_data[i].outlen);
+        TEST_ASSERT(!strcmp(test_data[i].out, cmp_data));
+    }
+
+    /*
+     * Test not enough space. Must have space for '\0' at the end.
+     */
+    ret = hex_format("\x01\x02", 2, cmp_data, 1);
+    TEST_ASSERT(ret == NULL);
+
+    ret = hex_format("\x01\x02", 2, cmp_data, 2);
+    TEST_ASSERT(ret == NULL);
+}
+
+TEST_CASE(str2hex)
+{
+    int i;
+    char cmp_data[8];
+    int rc;
+
+    struct {
+        char *in;
+        int inlen;
+        char *out;
+        int outlen;
+    } test_data[] = {
+        [0] = {
+            .in = "01",
+            .inlen = 2,
+            .out = "\x01",
+            .outlen = 1,
+        },
+        [1] = {
+            .in = "AfF2",
+            .inlen = 4,
+            .out = "\xaf\xf2",
+            .outlen = 2,
+        }
+    };
+
+    for (i = 0; i < sizeof(test_data) / sizeof(test_data[0]); i++) {
+        rc = hex_parse(test_data[i].in, test_data[i].inlen,
+          cmp_data, sizeof(cmp_data));
+        TEST_ASSERT(rc == test_data[i].outlen);
+        TEST_ASSERT(!memcmp(test_data[i].out, cmp_data, rc));
+    }
+
+    /*
+     * Test invalid input
+     */
+    rc = hex_parse("HJ", 2, cmp_data, sizeof(cmp_data));
+    TEST_ASSERT(rc < 0);
+
+    rc = hex_parse("a", 1, cmp_data, sizeof(cmp_data));
+    TEST_ASSERT(rc < 0);
+
+    rc = hex_parse("0102", 4, cmp_data, 1);
+    TEST_ASSERT(rc < 0);
+
+    /*
+     * This should be valid.
+     */
+    rc = hex_parse("0102", 4, cmp_data, 2);
+    TEST_ASSERT(rc == 2);
+}
+
+TEST_SUITE(hex_fmt_test_suite)
+{
+    hex2str();
+    str2hex();
+}


[48/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/boot/boot_serial/test/pkg.yml
----------------------------------------------------------------------
diff --git a/boot/boot_serial/test/pkg.yml b/boot/boot_serial/test/pkg.yml
new file mode 100644
index 0000000..561c94b
--- /dev/null
+++ b/boot/boot_serial/test/pkg.yml
@@ -0,0 +1,33 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+#
+pkg.name: libs/boot_serial/test
+pkg.type: unittest
+pkg.description: "Boot serial unit tests."
+pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
+pkg.homepage: "http://mynewt.apache.org/"
+pkg.keywords:
+
+pkg.deps:
+    - libs/boot_serial
+    - libs/testutil
+
+pkg.deps.SELFTEST:
+    - libs/console/stub
+
+pkg.syscfg_vals.SELFTEST:
+    CONFIG_FCB: 1

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/boot/boot_serial/test/src/boot_test.c
----------------------------------------------------------------------
diff --git a/boot/boot_serial/test/src/boot_test.c b/boot/boot_serial/test/src/boot_test.c
new file mode 100644
index 0000000..a70f05e
--- /dev/null
+++ b/boot/boot_serial/test/src/boot_test.c
@@ -0,0 +1,231 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include <assert.h>
+#include <stddef.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <inttypes.h>
+#include "syscfg/syscfg.h"
+#include "encoding/base64.h"
+#include "encoding/crc16.h"
+#include "testutil/testutil.h"
+#include "hal/hal_flash.h"
+#include "hal/flash_map.h"
+
+#include "boot_serial_priv.h"
+
+void
+tx_msg(void *src, int len)
+{
+    char *msg;
+    char *enc;
+    int off;
+    uint16_t crc;
+
+    crc = htons(crc16_ccitt(CRC16_INITIAL_CRC, src, len));
+
+    /*
+     * Lazy, malloc a buffer, fill it and send it.
+     */
+    msg = malloc(len + 2 * sizeof(uint16_t));
+    assert(msg);
+
+    *(uint16_t *)msg = ntohs(len + sizeof(uint16_t));
+    off = sizeof(uint16_t);
+    memcpy(&msg[off], src, len);
+    off += len;
+    memcpy(&msg[off], &crc, sizeof(crc));
+    off += sizeof(uint16_t);
+
+    enc = malloc(BASE64_ENCODE_SIZE(off) + 1);
+    assert(enc);
+
+    off = base64_encode(msg, off, enc, 1);
+    assert(off > 0);
+
+    boot_serial_input(enc, off + 1);
+
+    free(enc);
+    free(msg);
+}
+
+TEST_CASE(boot_serial_setup)
+{
+
+}
+
+TEST_CASE(boot_serial_empty_msg)
+{
+    char buf[4];
+    struct nmgr_hdr hdr;
+
+    boot_serial_input(buf, 0);
+
+    tx_msg(buf, 0);
+
+    strcpy(buf, "--");
+    tx_msg(buf, 2);
+
+    memset(&hdr, 0, sizeof(hdr));
+    tx_msg(&hdr, sizeof(hdr));
+
+    hdr.nh_op = NMGR_OP_WRITE;
+
+    tx_msg(&hdr, sizeof(hdr));
+}
+
+TEST_CASE(boot_serial_empty_img_msg)
+{
+    char buf[sizeof(struct nmgr_hdr) + 32];
+    struct nmgr_hdr *hdr;
+
+    hdr = (struct nmgr_hdr *)buf;
+    memset(hdr, 0, sizeof(*hdr));
+    hdr->nh_op = NMGR_OP_WRITE;
+    hdr->nh_group = htons(NMGR_GROUP_ID_IMAGE);
+    hdr->nh_id = IMGMGR_NMGR_OP_UPLOAD;
+    hdr->nh_len = htons(2);
+    strcpy((char *)(hdr + 1), "{}");
+
+    tx_msg(buf, sizeof(*hdr) + 2);
+}
+
+TEST_CASE(boot_serial_img_msg)
+{
+    char img[16];
+    char enc_img[BASE64_ENCODE_SIZE(sizeof(img))];
+    char buf[sizeof(struct nmgr_hdr) + sizeof(enc_img) + 32];
+    int len;
+    int rc;
+    struct nmgr_hdr *hdr;
+    const struct flash_area *fap;
+
+    memset(img, 0xa5, sizeof(img));
+    len = base64_encode(img, sizeof(img), enc_img, 1);
+    assert(len > 0);
+
+    hdr = (struct nmgr_hdr *)buf;
+    memset(hdr, 0, sizeof(*hdr));
+    hdr->nh_op = NMGR_OP_WRITE;
+    hdr->nh_group = htons(NMGR_GROUP_ID_IMAGE);
+    hdr->nh_id = IMGMGR_NMGR_OP_UPLOAD;
+
+    len = sprintf((char *)(hdr + 1), "{\"off\":0,\"len\":16,\"data\":\"%s\"}",
+      enc_img);
+    hdr->nh_len = htons(len);
+
+    len = sizeof(*hdr) + len;
+
+    tx_msg(buf, len);
+
+    /*
+     * Validate contents inside image 0 slot
+     */
+    rc = flash_area_open(FLASH_AREA_IMAGE_0, &fap);
+    assert(rc == 0);
+
+    rc = flash_area_read(fap, 0, enc_img, sizeof(img));
+    assert(rc == 0);
+    assert(!memcmp(enc_img, img, sizeof(img)));
+}
+
+TEST_CASE(boot_serial_upload_bigger_image)
+{
+    char img[256];
+    char enc_img[64];
+    char buf[sizeof(struct nmgr_hdr) + 128];
+    int len;
+    int off;
+    int rc;
+    struct nmgr_hdr *hdr;
+    const struct flash_area *fap;
+    int i;
+
+    for (i = 0; i < sizeof(img); i++) {
+        img[i] = i;
+    }
+
+    for (off = 0; off < sizeof(img); off += 32) {
+        len = base64_encode(&img[off], 32, enc_img, 1);
+        assert(len > 0);
+
+        hdr = (struct nmgr_hdr *)buf;
+        memset(hdr, 0, sizeof(*hdr));
+        hdr->nh_op = NMGR_OP_WRITE;
+        hdr->nh_group = htons(NMGR_GROUP_ID_IMAGE);
+        hdr->nh_id = IMGMGR_NMGR_OP_UPLOAD;
+
+        if (off) {
+            len = sprintf((char *)(hdr + 1), "{\"off\":%d,\"data\":\"%s\"}",
+              off, enc_img);
+        } else {
+            len = sprintf((char *)(hdr + 1), "{\"off\": 0 ,\"len\":%ld, "
+              "\"data\":\"%s\"}", (long)sizeof(img), enc_img);
+        }
+        hdr->nh_len = htons(len);
+
+        len = sizeof(*hdr) + len;
+
+        tx_msg(buf, len);
+    }
+
+    /*
+     * Validate contents inside image 0 slot
+     */
+    rc = flash_area_open(FLASH_AREA_IMAGE_0, &fap);
+    assert(rc == 0);
+
+    for (off = 0; off < sizeof(img); off += sizeof(enc_img)) {
+        rc = flash_area_read(fap, off, enc_img, sizeof(enc_img));
+        assert(rc == 0);
+        assert(!memcmp(enc_img, &img[off], sizeof(enc_img)));
+    }
+}
+
+TEST_SUITE(boot_serial_suite)
+{
+    boot_serial_setup();
+    boot_serial_empty_msg();
+    boot_serial_empty_img_msg();
+    boot_serial_img_msg();
+    boot_serial_upload_bigger_image();
+}
+
+int
+boot_serial_test(void)
+{
+    boot_serial_suite();
+    return tu_any_failed;
+}
+
+#if MYNEWT_VAL(SELFTEST)
+int
+main(void)
+{
+    tu_config.tc_print_results = 1;
+    tu_init();
+
+    boot_serial_test();
+
+    return tu_any_failed;
+}
+
+#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/boot/bootutil/design.txt
----------------------------------------------------------------------
diff --git a/boot/bootutil/design.txt b/boot/bootutil/design.txt
new file mode 100644
index 0000000..a39759b
--- /dev/null
+++ b/boot/bootutil/design.txt
@@ -0,0 +1,413 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+#
+
+****** BOOTUTIL
+
+*** SUMMARY
+
+The bootutil library performs most of the functions of a boot loader.  In
+particular, the piece that is missing is the final step of actually jumping to
+the main image.  This last step should instead be implemented in an
+architecture-specific project.  Boot loader functionality is separated in this
+manner for the following two reasons:
+
+1. By keeping architecture-dependent code separate, the bootutil library can be
+   reused among several boot loaders.
+
+2. By excluding the last boot step from the library, the rest of the code can
+   be tested in a sim environment.
+
+There is a boot loader project specific to the olimex_stm32-e407 devboard
+called "boot."  This project provides an example of how the bootutil library
+should be used.
+
+*** LIMITATIONS
+
+The boot loader currently only supports images with the following
+characteristics:
+    * Built to run from flash.
+    * Build to run from a fixed location (i.e., position-independent).
+
+These limitations will likely be addressed soon.
+
+
+*** IMAGE FORMAT
+
+The following definitions describe the image header format.
+
+#define IMAGE_MAGIC                 0x96f3b83c
+
+struct image_version {
+    uint8_t iv_major;
+    uint8_t iv_minor;
+    uint16_t iv_revision;
+    uint32_t iv_build_num;
+};
+
+/** Image header.  All fields are in little endian byte order. */
+struct image_header {
+    uint32_t ih_magic;
+    uint32_t ih_crc32; /* Covers remainder of header and all of image body. */
+    uint32_t ih_hdr_size;
+    uint32_t ih_img_size; /* Does not include header. */
+    uint32_t ih_flags;
+    struct image_version ih_ver;
+};
+
+At this time, no flags have been defined.
+
+The ih_hdr_size field indicates the length of the header, and therefore the
+offset of the image itself.  This field provides for backwards compatibility in
+case of changes to the format of the image header.
+
+When security is added, security data will likely go in a footer at the end of
+the image.
+
+
+*** FLASH AREAS
+
+Bootutil uses the same concept of "flash areas" as the nffs file system.
+Briefly, an area is a region of disk with the following properties:
+    (1) An area can be fully erased without affecting any other areas.
+    (2) A write to one area does not restrict writes to other areas.
+
+The areas used for image data must not be used for anything else.  In
+particular, these areas must be kept separate from the nffs file system.
+
+
+*** IMAGE SLOTS
+
+A portion of the flash memory is partitioned into two image slots: a primary
+slot and a secondary slot.  The boot loader will only run an image from the
+primary slot, so images must be built such that they can run from that fixed
+location in flash.  If the boot loader needs to run the image resident in the
+secondary slot, it must swap the two images in flash prior to booting.
+
+In addition to the two image slots, the boot loader requires a scratch area to
+allow for reliable image swapping.
+
+All areas used by image data (including the scratch area) must be the same
+size.
+
+
+*** BOOT VECTOR
+
+Bootutil determines which image it should boot into by reading the contents of
+the boot vector.  The boot vector comprises the following files in the flash
+file system:
+
+#define BOOT_PATH_MAIN      "/boot/main"
+#define BOOT_PATH_TEST      "/boot/test"
+
+Each file, if present, must contain a 64-bit image version.  This version is
+simply a "binary dump" of an image_version struct.  The test file is used to
+indicate that an image is being "tested out," and should only be booted once.
+The main file indicates the "last known good" image which should be booted
+repeatedly.
+
+The boot loader uses the following procedure to determine which image to boot:
+
+1) If the test file is present and contains a valid image version:
+    * Delete the test file.
+    * Boot into the specified image.
+
+2) Else if the main file is present and contains a valid image version:
+    * Boot into the specified image.
+
+3) Else:
+    * Just boot into whichever image is in the primary slot.  If there is no
+      image in the primary slot, boot into the image in the secondary slot.
+
+If a vector file contains a version which doesn't correspond to an image
+actually present in flash, the boot loader deletes the file and procedes as
+though the file was not present.
+
+
+*** BOOT STATUS
+
+The boot status file allows the boot loader to recover in case it was reset
+while in the middle of an image swap operation.  Image swapping is discussed
+later in this document; the structure of the boot status file is presented
+here.  To ensure recovery is always possible, bootutil updates the status file
+at each step throughout the image swap process.  The boot status is contained
+in the following file:
+
+#define BOOT_PATH_STATUS    "/boot/status"
+
+The contents of the boot status file are defined below.
+
+struct boot_status {
+    uint32_t bs_img1_length;
+    uint32_t bs_img2_length;
+    /* Followed by sequence of boot status entries; file size indicates number
+     * of entries.
+     */
+};
+
+struct boot_status_entry {
+    uint8_t bse_image_num;
+    uint8_t bse_part_num;
+};
+
+#define BOOT_IMAGE_NUM_NONE     0xff
+
+There is a separate boot status entry for each flash area used by the boot
+loader (i.e., each area in the two slots, plus one for the scratch area).  The
+entries are placed in the file in the same order as their corresponding areas
+in flash.  Each entry indicates which image part is resident in the
+corresponding flash area.  If a flash area does not contain any image data, its
+corresponding entry will have a bse_image_num value of BOOT_IMAGE_NUM_NONE.
+
+Consider the following example:
+
+Five flash areas are dedicated to image data, as follows:
+
+    Area 0: slot 0, 0/1
+    Area 1: slot 0, 1/1
+    Area 2: slot 1, 0/1
+    Area 3: slot 1, 1/1
+    Area 4: scratch
+
+The following array of boot status entries is read from the status file:
+
+    [0] = {
+        .bse_image_num = 0,
+        .bse_part_num = 0,
+    },
+    [1] = { 
+        .bse_image_num = 0,
+        .bse_part_num = 1,
+    },
+    [2] = { 
+        .bse_image_num = 1,
+        .bse_part_num = 0,
+    },
+    [3] = { 
+        .bse_image_num = 1,
+        .bse_part_num = 1,
+    },
+    [4] = { 
+        .bse_image_num = 0xff,
+        .bse_part_num = 0xff,
+    },
+
+This status file indicates the following image placement:
+
+    Area 0: image 0, part 0
+    Area 1: image 0, part 1
+    Area 2: image 1, part 0
+    Area 3: image 1, part 1
+    Scratch area: empty
+
+Images don't have an instrinsic image number.  When a swap operation is
+started, the image initially in the primary slot is labelled image 0, and the
+image in the secondary slot is labelled image 1.  All swap operations end with
+image 1 in the primary slot, and image 0 in the secondary slot.
+
+The boot status header containing the image sizes is necessary so that bootutil
+can determine how many flash areas each image occupies.  Without this
+information, bootutil would need to swap the full contents of the image slots,
+including useless data after the end of each image.
+
+The status file is always deleted upon successful boot.
+
+
+*** IMAGE SWAPPING
+
+If the boot vector indicates that the image in the secondary slot should be
+run, the boot loader needs to copy it to the primary slot.  The image currently
+in the primary slot also needs to be retained in flash so that it can be used
+later.  Furthermore, both images need to be recoverable if the boot loader
+resets in the middle of the process.  The two images are swapped according to
+the following procedure:
+
+    1. Determine how many flash areas are required to hold the desired image.
+    2. For each required area in the primary slot ("destination area"):
+        a. Identify the flash area in the secondary slot which contains the
+           required image data ("source area").
+        b. Erase scratch area.
+        c. Copy destination area to scratch area.
+        d. Write updated boot status to the file system.
+        e. Erase destination area.
+        f. Copy source area to destination area.
+        g. Write updated boot status to the file system.
+        h. Erase source area.
+        i. Copy scratch area to source area.
+        j. Write updated boot status to the file system.
+    3. Determine how many flash areas are required to hold image 1.
+    4. For each required area in the secondary slot ("destination area"):
+        a. If the destination area already contains the required image data,
+           advance to the next image part.
+        b. Else, identify the flash area in the primary slot which contains the
+           required image data ("source area").
+        c. Repeat steps b through j from step 2.
+
+This procedure ensures that the contents of the boot status file are always
+accurate, so the boot loader can recover after an unexpected reset.
+
+Step 4 is necessary in case the two images do not occupy the same number of
+flash areas.
+
+
+*** RESET RECOVERY
+
+If the boot loader resets in the middle of a swap operation, the two images may
+be discontiguous in flash.  Bootutil recovers from this condition by using the
+boot status file to determine how the image parts are placed in flash.
+
+If the boot status file indicates that the images are not contiguous, bootutil
+completes the swap operation that was in progress when the system was reset.
+In other words, it applies the procedure defined in the previous section,
+moving image 1 into slot 0 and image 0 into slot 1.  If the boot status file
+indicates that an image part is present in the scratch area, this part is
+copied into the correct location by starting at step e or step h in the
+area-swap procedure, depending on whether the part belongs to image 0 or image
+1.
+
+After the swap operation has been completed, the boot loader proceeds as though
+it had just been started.
+
+
+*** API
+
+The API consists of a single function:
+
+/**
+ * Prepares the booting process.  Based on the information provided in the
+ * request object, this function moves images around in flash as appropriate,
+ * and tells you what address to boot from.
+ *
+ * @param req                   Contains information about the flash layout.
+ * @param rsp                   On success, indicates how booting should occur.
+ *
+ * @return                      0 on success; nonzero on failure.
+ */
+int boot_go(const struct boot_req *req, struct boot_rsp *rsp)
+
+The request and response structures are defined as follows:
+
+/** A request object instructing the boot loader how to proceed. */
+struct boot_req {
+    /**
+     * Array of area descriptors indicating the layout of internal flash; must
+     * be terminated with a 0-length element.
+     */
+    struct nffs_area_desc *br_area_descs;
+
+    /**
+     * Array of indices of elements in the br_area_descs array; indicates which
+     * areas hold image data.
+     */
+    uint8_t *br_image_areas;
+
+    /**
+     * Array of indices of elements in the br_area_descs array; indicates which
+     * areas represent the beginning of an image slot.  This should be a subset
+     * of the br_image_areas array.
+     */
+    uint8_t *br_slot_areas;
+
+    /**
+     * The number of image areas (i.e., the size of the br_image_areas array).
+     */
+    uint8_t br_num_image_areas;
+
+    /** The index of the area to use as the image scratch area. */
+    uint8_t br_scratch_area_idx;
+};
+
+/**
+ * A response object provided by the boot loader code; indicates where to jump
+ * to execute the main image.
+ */
+struct boot_rsp {
+    /** A pointer to the header of the image to be executed. */
+    const struct image_header *br_hdr;
+
+    /**
+     * The flash offset of the image to execute.  Indicates the position of
+     * the image header.
+     */
+    uint32_t br_image_addr;
+};
+
+
+*** EXAMPLE USAGE
+
+In this example, each image slot consists of three flash areas.
+
+/** Internal flash layout. */
+static struct nffs_area_desc boot_area_descs[] = {
+    [0] =  { 0x08000000, 16 * 1024 },
+    [1] =  { 0x08004000, 16 * 1024 },
+    [2] =  { 0x08008000, 16 * 1024 },
+    [3] =  { 0x0800c000, 16 * 1024 },
+    [4] =  { 0x08010000, 64 * 1024 },
+    [5] =  { 0x08020000, 128 * 1024 }, /* Image data; 0,0. */
+    [6] =  { 0x08040000, 128 * 1024 }, /* Image data; 0,1. */
+    [7] =  { 0x08060000, 128 * 1024 }, /* Image data; 0,2. */
+    [8] =  { 0x08080000, 128 * 1024 }, /* Image data; 1,0. */
+    [9] =  { 0x080a0000, 128 * 1024 }, /* Image data; 1,1. */
+    [10] = { 0x080c0000, 128 * 1024 }, /* Image data; 1,2. */
+    [11] = { 0x080e0000, 128 * 1024 }, /* Image scratch area. */
+    { 0, 0 },
+};
+
+/** Contains indices of the areas which can contain image data. */
+static uint8_t boot_img_areas[] = {
+    5, 6, 7, 8, 9, 10, 11,
+};
+
+/** Areas representing the beginning of image slots. */
+static uint8_t boot_slot_areas[] = {
+    5, 8,
+};
+
+#define BOOT_NUM_IMG_AREAS \
+    ((int)(sizeof boot_img_areas / sizeof boot_img_areas[0]))
+
+/** The scratch area to use during an image swap operation. */
+#define BOOT_AREA_IDX_SCRATCH 11
+
+int
+main(void)
+{
+    struct boot_rsp rsp;
+    int rc;
+
+    const struct boot_req req = {
+        .br_area_descs = boot_area_descs,
+        .br_image_areas = boot_img_areas,
+        .br_slot_areas = boot_slot_areas,
+        .br_num_image_areas = BOOT_NUM_IMG_AREAS,
+        .br_scratch_area_idx = BOOT_AREA_IDX_SCRATCH,
+    };
+
+    rc = boot_go(&req, &rsp);
+    assert(rc == 0);
+
+    /* Perform jump to address indicated by the response object. */
+
+    return 0;
+}
+
+
+*** DEPENDENCIES
+    * nffs (for the boot vector and boot status files).
+    * os (for os_malloc() and os_free()).

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/boot/bootutil/include/bootutil/bootutil_misc.h
----------------------------------------------------------------------
diff --git a/boot/bootutil/include/bootutil/bootutil_misc.h b/boot/bootutil/include/bootutil/bootutil_misc.h
new file mode 100644
index 0000000..2e3049d
--- /dev/null
+++ b/boot/bootutil/include/bootutil/bootutil_misc.h
@@ -0,0 +1,28 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 __BOOTUTIL_MISC_H_
+#define __BOOTUTIL_MISC_H_
+
+int boot_vect_read_test(int *slot);
+int boot_vect_read_main(int *slot);
+int boot_vect_write_test(int slot);
+int boot_vect_write_main(void);
+
+#endif /*  __BOOTUTIL_MISC_H_ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/boot/bootutil/include/bootutil/bootutil_test.h
----------------------------------------------------------------------
diff --git a/boot/bootutil/include/bootutil/bootutil_test.h b/boot/bootutil/include/bootutil/bootutil_test.h
new file mode 100644
index 0000000..55c8a67
--- /dev/null
+++ b/boot/bootutil/include/bootutil/bootutil_test.h
@@ -0,0 +1,25 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 H_BOOTUTIL_TEST_
+#define H_BOOTUTIL_TEST_
+
+int boot_test_all(void);
+
+#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/boot/bootutil/include/bootutil/image.h
----------------------------------------------------------------------
diff --git a/boot/bootutil/include/bootutil/image.h b/boot/bootutil/include/bootutil/image.h
new file mode 100644
index 0000000..0974d5b
--- /dev/null
+++ b/boot/bootutil/include/bootutil/image.h
@@ -0,0 +1,89 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 H_IMAGE_
+#define H_IMAGE_
+
+#include <inttypes.h>
+
+#define IMAGE_MAGIC                 0x96f3b83c
+#define IMAGE_MAGIC_NONE            0xffffffff
+
+/*
+ * Image header flags.
+ */
+#define IMAGE_F_PIC                   0x00000001
+#define IMAGE_F_SHA256                0x00000002	/* Image contains hash TLV */
+#define IMAGE_F_PKCS15_RSA2048_SHA256 0x00000004 /* PKCS15 w/RSA and SHA */
+#define IMAGE_F_ECDSA224_SHA256       0x00000008  /* ECDSA256 over SHA256 */
+#define IMAGE_F_NON_BOOTABLE          0x00000010
+#define IMAGE_HEADER_SIZE           32
+
+/*
+ * Image trailer TLV types.
+ */
+#define IMAGE_TLV_SHA256            1	/* SHA256 of image hdr and body */
+#define IMAGE_TLV_RSA2048           2	/* RSA2048 of hash output */
+#define IMAGE_TLV_ECDSA224          3   /* ECDSA of hash output */
+
+struct image_version {
+    uint8_t iv_major;
+    uint8_t iv_minor;
+    uint16_t iv_revision;
+    uint32_t iv_build_num;
+};
+
+#define IMAGE_SIZE(hdr)                                                 \
+    ((hdr)->ih_tlv_size + (hdr)->ih_hdr_size + (hdr)->ih_img_size)
+
+/** Image header.  All fields are in little endian byte order. */
+struct image_header {
+    uint32_t ih_magic;
+    uint16_t ih_tlv_size; /* Trailing TLVs */
+    uint8_t  ih_key_id;
+    uint8_t  _pad1;
+    uint16_t ih_hdr_size;
+    uint16_t _pad2;
+    uint32_t ih_img_size; /* Does not include header. */
+    uint32_t ih_flags;
+    struct image_version ih_ver;
+    uint32_t _pad3;
+};
+
+/** Image trailer TLV format. All fields in little endian. */
+struct image_tlv {
+    uint8_t  it_type;
+    uint8_t  _pad;
+    uint16_t it_len;
+};
+
+struct boot_image_location {
+    uint8_t bil_flash_id;
+    uint32_t bil_address;
+};
+
+
+_Static_assert(sizeof(struct image_header) == IMAGE_HEADER_SIZE,
+               "struct image_header not required size");
+
+int bootutil_img_validate(struct image_header *hdr, uint8_t flash_id,
+                        uint32_t addr, uint8_t *tmp_buf, uint32_t tmp_buf_sz,
+                        uint8_t *seed, int seed_len, uint8_t *out_hash);
+
+#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/boot/bootutil/include/bootutil/loader.h
----------------------------------------------------------------------
diff --git a/boot/bootutil/include/bootutil/loader.h b/boot/bootutil/include/bootutil/loader.h
new file mode 100644
index 0000000..75e0d01
--- /dev/null
+++ b/boot/bootutil/include/bootutil/loader.h
@@ -0,0 +1,84 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 H_LOADER_
+#define H_LOADER_
+
+#include <inttypes.h>
+struct image_header;
+
+/** A request object instructing the boot loader how to proceed. */
+struct boot_req {
+    /**
+     * Array of area descriptors indicating the layout of flash(es); must
+     * be terminated with a 0-length element.
+     */
+    struct flash_area *br_area_descs;
+
+    /**
+     * Array of indices of elements in the br_area_descs array; indicates which
+     * areas represent the beginning of an image slot.  These are indices
+     * to br_area_descs array.
+     */
+    uint8_t *br_slot_areas;
+
+    /**
+     * The number of image areas (i.e., the size of the br_image_areas array).
+     */
+    uint8_t br_num_image_areas;
+
+    /** The area to use as the image scratch area, index is
+	index to br_area_descs array, of the  */
+    uint8_t br_scratch_area_idx;
+
+    /** Size of the image slot */
+    uint32_t br_img_sz;
+};
+
+/**
+ * A response object provided by the boot loader code; indicates where to jump
+ * to execute the main image.
+ */
+struct boot_rsp {
+    /** A pointer to the header of the image to be executed. */
+    const struct image_header *br_hdr;
+
+    /**
+     * The flash offset of the image to execute.  Indicates the position of
+     * the image header.
+     */
+    uint8_t br_flash_id;
+    uint32_t br_image_addr;
+};
+
+/* you must have pre-allocated all the entries within this structure */
+int
+boot_build_request(struct boot_req *preq, int area_descriptor_max);
+
+int
+boot_go(const struct boot_req *req, struct boot_rsp *rsp);
+
+
+#define SPLIT_GO_OK                 (0)
+#define SPLIT_GO_NON_MATCHING       (-1)
+#define SPLIT_GO_ERR                (-2)
+int
+split_go(int loader_slot, int split_slot, void **entry);
+
+#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/boot/bootutil/include/bootutil/sign_key.h
----------------------------------------------------------------------
diff --git a/boot/bootutil/include/bootutil/sign_key.h b/boot/bootutil/include/bootutil/sign_key.h
new file mode 100644
index 0000000..5ccda90
--- /dev/null
+++ b/boot/bootutil/include/bootutil/sign_key.h
@@ -0,0 +1,33 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 __BOOTUTIL_SIGN_KEY_H_
+#define __BOOTUTIL_SIGN_KEY_H_
+
+#include <stdint.h>
+
+struct bootutil_key {
+    const uint8_t *key;
+    const unsigned int *len;
+};
+
+extern const struct bootutil_key bootutil_keys[];
+extern const int bootutil_key_cnt;
+
+#endif /* __BOOTUTIL_SIGN_KEY_H_ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/boot/bootutil/pkg.yml
----------------------------------------------------------------------
diff --git a/boot/bootutil/pkg.yml b/boot/bootutil/pkg.yml
new file mode 100644
index 0000000..d4827fd
--- /dev/null
+++ b/boot/bootutil/pkg.yml
@@ -0,0 +1,41 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+#
+
+pkg.name: boot/bootutil
+pkg.description: The bootutil library performs most of the functions of a boot loader.
+pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
+pkg.homepage: "http://mynewt.apache.org/"
+pkg.keywords:
+    - boot
+    - bootloader
+
+pkg.deps: 
+    - hw/hal
+    - crypto/mbedtls
+    - kernel/os 
+
+pkg.syscfg_defs:
+    BOOTUTIL_SIGN_RSA:
+        description: 'TBD'
+        value: '0'
+    BOOTUTIL_SIGN_EC:
+        description: 'TBD'
+        value: '0'
+pkg.cflags.IMAGE_KEYS_RSA: -DIMAGE_SIGNATURES_RSA
+pkg.cflags.IMAGE_KEYS_EC: -DIMAGE_SIGNATURES_EC

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/boot/bootutil/signed_images.md
----------------------------------------------------------------------
diff --git a/boot/bootutil/signed_images.md b/boot/bootutil/signed_images.md
new file mode 100644
index 0000000..39792ea
--- /dev/null
+++ b/boot/bootutil/signed_images.md
@@ -0,0 +1,91 @@
+<!--
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+#
+-->
+
+## Image signing
+
+This signs the image by computing hash over the image, and then
+signing that hash. Signature is computed by newt tool when it's
+creating the image. This signature is placed in the image trailer.
+
+The public key of this keypair must be included in the bootloader,
+as it verifies it before allowing the image to run.
+
+This facility allows you to use multiple signing keys. This would
+be useful when you want to prevent production units from booting
+development images, but want development units to be able to boot
+both production images and development images.
+
+## Creating signing keys
+First you need a keypair to use for signing. You can create
+one with openssl command line tool.
+
+openssl genrsa -out image_sign.pem 2048
+
+This created a file which contains both the private and public key,
+and will be used when signing images.
+
+Then you need to extract the public key from this to include it
+in the bootloader. Bootloader need to keep key parsing minimal,
+so it expects simple key format.
+
+openssl rsa -in image_sign.pem -pubout -out image_sign_pub.der -outform DER -RSAPublicKey_out
+
+Now the public key is in file called image_sign_pub.der.
+
+## Creating a key package
+
+xxd -i image_sign_pub.der image_sign_pub.c.import
+
+Then you need to create a package containing this key, or keys.
+In the pkg.yml for this package, you advertise feature IMAGE_KEYS_RSA or
+IMAGE_KEYS_EC.
+Once this is done, bootloader will expect keys to be filled in
+'bootutil_keys', and the number of keys to be in 'bootutil_key_cnt'.
+
+## Sample pkg.yml
+This gets bootutil to turn on image signature validation.
+
+    pkg.name: libs/mykeys
+    pkg.deps:
+        - libs/bootutil
+    pkg.features.bootloader:
+        - IMAGE_KEYS_RSA
+
+## Sample source file
+This exports the keys.
+
+    #include <bootutil/sign_key.h>
+
+    #include "image_sign_pub.c.import"
+
+    const struct bootutil_key bootutil_keys[] = {
+        [0] = {
+            .key = image_sign_pub_der,
+            .len = &image_sign_pub_der_len,
+        }
+    };
+
+    const int bootutil_key_cnt = sizeof(bootutil_keys) / sizeof(bootutil_keys[0]);
+
+## Building bootloader
+
+After you've created the key package, you must include it in the build
+for bootloader. So modify the pkg.yml for apps/boot to include it.

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/boot/bootutil/src/bootutil_misc.c
----------------------------------------------------------------------
diff --git a/boot/bootutil/src/bootutil_misc.c b/boot/bootutil/src/bootutil_misc.c
new file mode 100644
index 0000000..f64d2a4
--- /dev/null
+++ b/boot/bootutil/src/bootutil_misc.c
@@ -0,0 +1,319 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include <assert.h>
+#include <string.h>
+#include <inttypes.h>
+
+#include "syscfg/syscfg.h"
+#include "hal/hal_bsp.h"
+#include "hal/hal_flash.h"
+#include "hal/flash_map.h"
+#include "os/os.h"
+#include "bootutil/image.h"
+#include "bootutil/loader.h"
+#include "bootutil/bootutil_misc.h"
+#include "bootutil_priv.h"
+
+/*
+ * Read the image trailer from a given slot.
+ */
+static int
+boot_vect_read_img_trailer(int slot, struct boot_img_trailer *bit)
+{
+    int rc;
+    const struct flash_area *fap;
+    uint32_t off;
+
+    rc = flash_area_open(slot, &fap);
+    if (rc) {
+        return rc;
+    }
+    off = fap->fa_size - sizeof(struct boot_img_trailer);
+    rc = flash_area_read(fap, off, bit, sizeof(*bit));
+    flash_area_close(fap);
+
+    return rc;
+}
+
+/**
+ * Retrieves from the slot number of the test image (i.e.,
+ * the image that has not been proven stable, and which will only run once).
+ *
+ * @param slot              On success, the slot number of image to boot.
+ *
+ * @return                  0 on success; nonzero on failure.
+ */
+int
+boot_vect_read_test(int *slot)
+{
+    struct boot_img_trailer bit;
+    int i;
+    int rc;
+
+    for (i = FLASH_AREA_IMAGE_0; i <= FLASH_AREA_IMAGE_1; i++) {
+        if (i == bsp_imgr_current_slot()) {
+            continue;
+        }
+        rc = boot_vect_read_img_trailer(i, &bit);
+        if (rc) {
+            continue;
+        }
+        if (bit.bit_copy_start == BOOT_IMG_MAGIC) {
+            *slot = i;
+            return 0;
+        }
+    }
+    return -1;
+}
+
+/**
+ * Retrieves from the slot number of the main image. If this is
+ * different from test image slot, next restart will revert to main.
+ *
+ * @param out_ver           On success, the main version gets written here.
+ *
+ * @return                  0 on success; nonzero on failure.
+ */
+int
+boot_vect_read_main(int *slot)
+{
+    int rc;
+    struct boot_img_trailer bit;
+
+    rc = boot_vect_read_img_trailer(FLASH_AREA_IMAGE_0, &bit);
+    assert(rc == 0);
+
+    if (bit.bit_copy_start != BOOT_IMG_MAGIC || bit.bit_img_ok != 0xff) {
+        /*
+         * If there never was copy that took place, or if the current
+         * image has been marked good, we'll keep booting it.
+         */
+        *slot = FLASH_AREA_IMAGE_0;
+    } else {
+        *slot = FLASH_AREA_IMAGE_1;
+    }
+    return 0;
+}
+
+/**
+ * Write the test image version number from the boot vector.
+ *
+ * @return                  0 on success; nonzero on failure.
+ */
+int
+boot_vect_write_test(int slot)
+{
+    const struct flash_area *fap;
+    uint32_t off;
+    uint32_t magic;
+    int rc;
+
+    rc = flash_area_open(slot, &fap);
+    if (rc) {
+        return rc;
+    }
+
+    off = fap->fa_size - sizeof(struct boot_img_trailer);
+    magic = BOOT_IMG_MAGIC;
+
+    rc = flash_area_write(fap, off, &magic, sizeof(magic));
+    flash_area_close(fap);
+
+    return rc;
+}
+
+/**
+ * Deletes the main image version number from the boot vector.
+ * This must be called by the app to confirm that it is ok to keep booting
+ * to this image.
+ *
+ * @return                  0 on success; nonzero on failure.
+ */
+int
+boot_vect_write_main(void)
+{
+    const struct flash_area *fap;
+    uint32_t off;
+    int rc;
+    uint8_t val;
+
+    /*
+     * Write to slot 0.
+     */
+    rc = flash_area_open(FLASH_AREA_IMAGE_0, &fap);
+    if (rc) {
+        return rc;
+    }
+
+    off = fap->fa_size - sizeof(struct boot_img_trailer);
+    off += (sizeof(uint32_t) + sizeof(uint8_t));
+    rc = flash_area_read(fap, off, &val, sizeof(val));
+    if (!rc && val == 0xff) {
+        val = 0;
+        rc = flash_area_write(fap, off, &val, sizeof(val));
+    }
+    return rc;
+}
+
+/**
+ * Reads the header of image present in flash.  Header corresponding to
+ * empty image slot is filled with 0xff bytes.
+ *
+ * @param out_headers           Points to an array of image headers.  Each
+ *                                  element is filled with the header of the
+ *                                  corresponding image in flash.
+ * @param addresses             An array containing the flash addresses of each
+ *                                  image slot.
+ * @param num_addresses         The number of headers to read.  This should
+ *                                  also be equal to the lengths of the
+ *                                  out_headers and addresses arrays.
+ */
+int
+boot_read_image_header(struct boot_image_location *loc,
+                       struct image_header *out_hdr)
+{
+    int rc;
+
+    rc = hal_flash_read(loc->bil_flash_id, loc->bil_address, out_hdr,
+                        sizeof *out_hdr);
+    if (rc != 0) {
+        rc = BOOT_EFLASH;
+    } else if (out_hdr->ih_magic != IMAGE_MAGIC) {
+        rc = BOOT_EBADIMAGE;
+    }
+
+    if (rc) {
+        memset(out_hdr, 0xff, sizeof(*out_hdr));
+    }
+    return rc;
+}
+
+/*
+ * How far has the copy progressed?
+ */
+static void
+boot_read_status_bytes(struct boot_status *bs, uint8_t flash_id, uint32_t off)
+{
+    uint8_t status;
+
+    assert(bs->elem_sz);
+    off -= bs->elem_sz * 2;
+    while (1) {
+        hal_flash_read(flash_id, off, &status, sizeof(status));
+        if (status == 0xff) {
+            break;
+        }
+        off -= bs->elem_sz;
+        if (bs->state == 2) {
+            bs->idx++;
+            bs->state = 0;
+        } else {
+            bs->state++;
+        }
+    }
+}
+
+/**
+ * Reads the boot status from the flash.  The boot status contains
+ * the current state of an interrupted image copy operation.  If the boot
+ * status is not present, or it indicates that previous copy finished,
+ * there is no operation in progress.
+ */
+int
+boot_read_status(struct boot_status *bs)
+{
+    struct boot_img_trailer bit;
+    uint8_t flash_id;
+    uint32_t off;
+
+    /*
+     * Check if boot_img_trailer is in scratch, or at the end of slot0.
+     */
+    boot_slot_magic(0, &bit);
+    if (bit.bit_copy_start == BOOT_IMG_MAGIC && bit.bit_copy_done == 0xff) {
+        boot_magic_loc(0, &flash_id, &off);
+        boot_read_status_bytes(bs, flash_id, off);
+        return 1;
+    }
+    boot_scratch_magic(&bit);
+    if (bit.bit_copy_start == BOOT_IMG_MAGIC && bit.bit_copy_done == 0xff) {
+        boot_scratch_loc(&flash_id, &off);
+        boot_read_status_bytes(bs, flash_id, off);
+        return 1;
+    }
+    return 0;
+}
+
+
+/**
+ * Writes the supplied boot status to the flash file system.  The boot status
+ * contains the current state of an in-progress image copy operation.
+ *
+ * @param bs                    The boot status to write.
+ *
+ * @return                      0 on success; nonzero on failure.
+ */
+int
+boot_write_status(struct boot_status *bs)
+{
+    uint32_t off;
+    uint8_t flash_id;
+    uint8_t val;
+
+    if (bs->idx == 0) {
+        /*
+         * Write to scratch
+         */
+        boot_scratch_loc(&flash_id, &off);
+    } else {
+        /*
+         * Write to slot 0;
+         */
+        boot_magic_loc(0, &flash_id, &off);
+    }
+    off -= ((3 * bs->elem_sz) * bs->idx + bs->elem_sz * (bs->state + 1));
+
+    val = bs->state;
+    hal_flash_write(flash_id, off, &val, sizeof(val));
+
+    return 0;
+}
+
+/**
+ * Finalizes the copy-in-progress status on the flash.  The boot status
+ * contains the current state of an in-progress image copy operation.  By
+ * clearing this, it is implied that there is no copy operation in
+ * progress.
+ */
+void
+boot_clear_status(void)
+{
+    uint32_t off;
+    uint8_t val = 0;
+    uint8_t flash_id;
+
+    /*
+     * Write to slot 0; boot_img_trailer is the 8 bytes within image slot.
+     * Here we say that copy operation was finished.
+     */
+    boot_magic_loc(0, &flash_id, &off);
+    off += sizeof(uint32_t);
+    hal_flash_write(flash_id, off, &val, sizeof(val));
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/boot/bootutil/src/bootutil_priv.h
----------------------------------------------------------------------
diff --git a/boot/bootutil/src/bootutil_priv.h b/boot/bootutil/src/bootutil_priv.h
new file mode 100644
index 0000000..e5b231c
--- /dev/null
+++ b/boot/bootutil/src/bootutil_priv.h
@@ -0,0 +1,75 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 H_BOOTUTIL_PRIV_
+#define H_BOOTUTIL_PRIV_
+
+#include "bootutil/image.h"
+
+#define BOOT_EFLASH     1
+#define BOOT_EFILE      2
+#define BOOT_EBADIMAGE  3
+#define BOOT_EBADVECT   4
+#define BOOT_EBADSTATUS 5
+#define BOOT_ENOMEM     6
+#define BOOT_EBADARGS   7
+
+#define BOOT_TMPBUF_SZ  256
+
+
+
+/*
+ * Maintain state of copy progress.
+ */
+struct boot_status {
+    uint32_t idx;       /* Which area we're operating on */
+    uint8_t elem_sz;    /* Size of the status element to write in bytes */
+    uint8_t state;      /* Which part of the swapping process are we at */
+};
+
+/*
+ * End-of-image slot data structure.
+ */
+#define BOOT_IMG_MAGIC  0x12344321
+struct boot_img_trailer {
+    uint32_t bit_copy_start;
+    uint8_t  bit_copy_done;
+    uint8_t  bit_img_ok;
+    uint16_t _pad;
+};
+
+int bootutil_verify_sig(uint8_t *hash, uint32_t hlen, uint8_t *sig, int slen,
+    uint8_t key_id);
+
+int boot_read_image_header(struct boot_image_location *loc,
+  struct image_header *out_hdr);
+int boot_write_status(struct boot_status *bs);
+int boot_read_status(struct boot_status *bs);
+void boot_clear_status(void);
+
+void boot_magic_loc(int slot_num, uint8_t *flash_id, uint32_t *off);
+void boot_scratch_loc(uint8_t *flash_id, uint32_t *off);
+void boot_slot_magic(int slot_num, struct boot_img_trailer *bit);
+void boot_scratch_magic(struct boot_img_trailer *bit);
+
+struct boot_req;
+void boot_req_set(struct boot_req *req);
+
+#endif
+

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/boot/bootutil/src/image_ec.c
----------------------------------------------------------------------
diff --git a/boot/bootutil/src/image_ec.c b/boot/bootutil/src/image_ec.c
new file mode 100644
index 0000000..f3adfcf
--- /dev/null
+++ b/boot/bootutil/src/image_ec.c
@@ -0,0 +1,121 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include "syscfg/syscfg.h"
+
+#if MYNEWT_VAL(BOOTUTIL_SIGN_EC)
+#include "bootutil/sign_key.h"
+
+#include "mbedtls/sha256.h"
+#include "mbedtls/ecdsa.h"
+#include "mbedtls/oid.h"
+#include "mbedtls/asn1.h"
+
+#include "bootutil_priv.h"
+
+/*
+ * Declaring these like this adds NULL termination.
+ */
+static const uint8_t ec_pubkey_oid[] = MBEDTLS_OID_EC_ALG_UNRESTRICTED;
+static const uint8_t ec_secp224r1_oid[] = MBEDTLS_OID_EC_GRP_SECP224R1;
+
+/*
+ * Parse the public key used for signing. Simple RSA format.
+ */
+static int
+bootutil_parse_eckey(mbedtls_ecdsa_context *ctx, uint8_t **p, uint8_t *end)
+{
+    size_t len;
+    mbedtls_asn1_buf alg;
+    mbedtls_asn1_buf param;
+
+    if (mbedtls_asn1_get_tag(p, end, &len,
+        MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) {
+        return -1;
+    }
+    end = *p + len;
+
+    if (mbedtls_asn1_get_alg(p, end, &alg, &param)) {
+        return -2;
+    }
+    if (alg.len != sizeof(ec_pubkey_oid) - 1 ||
+      memcmp(alg.p, ec_pubkey_oid, sizeof(ec_pubkey_oid) - 1)) {
+        return -3;
+    }
+    if (param.len != sizeof(ec_secp224r1_oid) - 1||
+      memcmp(param.p, ec_secp224r1_oid, sizeof(ec_secp224r1_oid) - 1)) {
+        return -4;
+    }
+
+    if (mbedtls_ecp_group_load_secp224r1(&ctx->grp)) {
+        return -5;
+    }
+
+    if (mbedtls_asn1_get_bitstring_null(p, end, &len)) {
+        return -6;
+    }
+    if (*p + len != end) {
+        return -7;
+    }
+
+    if (mbedtls_ecp_point_read_binary(&ctx->grp, &ctx->Q, *p, end - *p)) {
+        return -8;
+    }
+
+    if (mbedtls_ecp_check_pubkey(&ctx->grp, &ctx->Q)) {
+        return -9;
+    }
+    return 0;
+}
+
+static int
+bootutil_cmp_sig(mbedtls_ecdsa_context *ctx, uint8_t *hash, uint32_t hlen,
+  uint8_t *sig, int slen)
+{
+    return mbedtls_ecdsa_read_signature(ctx, hash, hlen, sig, slen);
+}
+
+int
+bootutil_verify_sig(uint8_t *hash, uint32_t hlen, uint8_t *sig, int slen,
+  uint8_t key_id)
+{
+    int rc;
+    uint8_t *cp;
+    uint8_t *end;
+    mbedtls_ecdsa_context ctx;
+
+    mbedtls_ecdsa_init(&ctx);
+
+    cp = (uint8_t *)bootutil_keys[key_id].key;
+    end = cp + *bootutil_keys[key_id].len;
+
+    rc = bootutil_parse_eckey(&ctx, &cp, end);
+    if (rc) {
+        return -1;
+    }
+
+    while (sig[slen - 1] == '\0') {
+        slen--;
+    }
+    rc = bootutil_cmp_sig(&ctx, hash, hlen, sig, slen);
+    mbedtls_ecdsa_free(&ctx);
+
+    return rc;
+}
+#endif /* MYNEWT_VAL(BOOTUTIL_SIGN_EC) */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/boot/bootutil/src/image_rsa.c
----------------------------------------------------------------------
diff --git a/boot/bootutil/src/image_rsa.c b/boot/bootutil/src/image_rsa.c
new file mode 100644
index 0000000..e556092
--- /dev/null
+++ b/boot/bootutil/src/image_rsa.c
@@ -0,0 +1,144 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include "syscfg/syscfg.h"
+
+#if MYNEWT_VAL(BOOTUTIL_SIGN_RSA)
+#include "bootutil/sign_key.h"
+
+#include "mbedtls/rsa.h"
+#include "mbedtls/asn1.h"
+
+#include "bootutil_priv.h"
+
+static const uint8_t sha256_oid[] = {
+    0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86,
+    0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05,
+    0x00, 0x04, 0x20
+};
+
+/*
+ * Parse the public key used for signing. Simple RSA format.
+ */
+static int
+bootutil_parse_rsakey(mbedtls_rsa_context *ctx, uint8_t **p, uint8_t *end)
+{
+    int rc;
+    size_t len;
+
+    if ((rc = mbedtls_asn1_get_tag(p, end, &len,
+          MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
+        return -1;
+    }
+
+    if (*p + len != end) {
+        return -2;
+    }
+
+    if ((rc = mbedtls_asn1_get_mpi(p, end, &ctx->N)) != 0 ||
+      (rc = mbedtls_asn1_get_mpi(p, end, &ctx->E)) != 0) {
+        return -3;
+    }
+
+    if (*p != end) {
+        return -4;
+    }
+
+    if ((rc = mbedtls_rsa_check_pubkey(ctx)) != 0) {
+        return -5;
+    }
+
+    ctx->len = mbedtls_mpi_size(&ctx->N);
+
+    return 0;
+}
+
+/*
+ * PKCS1.5 using RSA2048 computed over SHA256.
+ */
+static int
+bootutil_cmp_rsasig(mbedtls_rsa_context *ctx, uint8_t *hash, uint32_t hlen,
+  uint8_t *sig)
+{
+    uint8_t buf[MBEDTLS_MPI_MAX_SIZE];
+    uint8_t *p;
+
+    if (ctx->len != 256) {
+        return -1;
+    }
+
+    if (mbedtls_rsa_public(ctx, sig, buf)) {
+        return -1;
+    }
+
+    p = buf;
+
+    if (*p++ != 0 || *p++ != MBEDTLS_RSA_SIGN) {
+        return -1;
+    }
+
+    while (*p != 0) {
+        if (p >= buf + ctx->len - 1 || *p != 0xFF) {
+            return -1;
+        }
+        p++;
+    }
+    p++;
+
+    if ((p - buf) + sizeof(sha256_oid) + hlen != ctx->len) {
+        return -1;
+    }
+
+    if (memcmp(p, sha256_oid, sizeof(sha256_oid))) {
+        return -1;
+    }
+    p += sizeof(sha256_oid);
+
+    if (memcmp(p, hash, hlen)) {
+        return -1;
+    }
+
+    return 0;
+}
+
+int
+bootutil_verify_sig(uint8_t *hash, uint32_t hlen, uint8_t *sig, int slen,
+  uint8_t key_id)
+{
+    mbedtls_rsa_context ctx;
+    int rc;
+    uint8_t *cp;
+    uint8_t *end;
+
+    mbedtls_rsa_init(&ctx, 0, 0);
+
+    cp = (uint8_t *)bootutil_keys[key_id].key;
+    end = cp + *bootutil_keys[key_id].len;
+
+    rc = bootutil_parse_rsakey(&ctx, &cp, end);
+    if (rc || slen != ctx.len) {
+        mbedtls_rsa_free(&ctx);
+        return rc;
+    }
+    rc = bootutil_cmp_rsasig(&ctx, hash, hlen, sig);
+    mbedtls_rsa_free(&ctx);
+
+    return rc;
+}
+#endif /* MYNEWT_VAL(BOOTUTIL_SIGN_RSA) */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/boot/bootutil/src/image_validate.c
----------------------------------------------------------------------
diff --git a/boot/bootutil/src/image_validate.c b/boot/bootutil/src/image_validate.c
new file mode 100644
index 0000000..3793948
--- /dev/null
+++ b/boot/bootutil/src/image_validate.c
@@ -0,0 +1,198 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include <assert.h>
+#include <stddef.h>
+#include <inttypes.h>
+#include <string.h>
+
+#include "syscfg/syscfg.h"
+#include "hal/hal_flash.h"
+#include "bootutil/image.h"
+#include "bootutil/sign_key.h"
+
+#include "mbedtls/sha256.h"
+#include "mbedtls/rsa.h"
+#include "mbedtls/ecdsa.h"
+#include "mbedtls/asn1.h"
+
+#include "bootutil_priv.h"
+
+/*
+ * Compute SHA256 over the image.
+ */
+static int
+bootutil_img_hash(struct image_header *hdr, uint8_t flash_id, uint32_t addr,
+  uint8_t *tmp_buf, uint32_t tmp_buf_sz, uint8_t *hash_result, uint8_t *seed, int seed_len)
+{
+    mbedtls_sha256_context sha256_ctx;
+    uint32_t blk_sz;
+    uint32_t size;
+    uint32_t off;
+    int rc;
+
+    mbedtls_sha256_init(&sha256_ctx);
+    mbedtls_sha256_starts(&sha256_ctx, 0);
+
+    /* in some cases (split image) the hash is seeded with data from
+     * the loader image */
+    if(seed && (seed_len > 0)) {
+        mbedtls_sha256_update(&sha256_ctx, seed, seed_len);
+    }
+
+    size = hdr->ih_img_size + hdr->ih_hdr_size;
+
+    /*
+     * Hash is computed over image header and image itself. No TLV is
+     * included ATM.
+     */
+    size = hdr->ih_img_size + hdr->ih_hdr_size;
+    for (off = 0; off < size; off += blk_sz) {
+        blk_sz = size - off;
+        if (blk_sz > tmp_buf_sz) {
+            blk_sz = tmp_buf_sz;
+        }
+        rc = hal_flash_read(flash_id, addr + off, tmp_buf, blk_sz);
+        if (rc) {
+            return rc;
+        }
+        mbedtls_sha256_update(&sha256_ctx, tmp_buf, blk_sz);
+    }
+    mbedtls_sha256_finish(&sha256_ctx, hash_result);
+
+    return 0;
+}
+
+/*
+ * Verify the integrity of the image.
+ * Return non-zero if image could not be validated/does not validate.
+ */
+int
+bootutil_img_validate(struct image_header *hdr, uint8_t flash_id, uint32_t addr,
+  uint8_t *tmp_buf, uint32_t tmp_buf_sz, uint8_t *seed, int seed_len, uint8_t *out_hash)
+{
+    uint32_t off;
+    uint32_t size;
+    uint32_t sha_off = 0;
+#if MYNEWT_VAL(BOOTUTIL_SIGN_RSA) || MYNEWT_VAL(BOOTUTIL_SIGN_EC)
+    uint32_t sig_off = 0;
+    uint32_t sig_len = 0;
+#endif
+    struct image_tlv tlv;
+    uint8_t buf[256];
+    uint8_t hash[32];
+    int rc;
+
+#if MYNEWT_VAL(BOOTUTIL_SIGN_RSA)
+    if ((hdr->ih_flags & IMAGE_F_PKCS15_RSA2048_SHA256) == 0) {
+        return -1;
+    }
+#endif
+#if MYNEWT_VAL(BOOTUTIL_SIGN_EC)
+    if ((hdr->ih_flags & IMAGE_F_ECDSA224_SHA256) == 0) {
+        return -1;
+    }
+#endif
+    if ((hdr->ih_flags & IMAGE_F_SHA256) == 0) {
+        return -1;
+    }
+
+    rc = bootutil_img_hash(hdr, flash_id, addr, tmp_buf, tmp_buf_sz, hash, seed, seed_len);
+    if (rc) {
+        return rc;
+    }
+
+    if(out_hash) {
+        memcpy(out_hash, hash, 32);
+    }
+
+    /*
+     * After image there's TLVs.
+     */
+    off = hdr->ih_img_size + hdr->ih_hdr_size;
+    size = off + hdr->ih_tlv_size;
+
+    for (; off < size; off += sizeof(tlv) + tlv.it_len) {
+        rc = hal_flash_read(flash_id, addr + off, &tlv, sizeof(tlv));
+        if (rc) {
+            return rc;
+        }
+        if (tlv.it_type == IMAGE_TLV_SHA256) {
+            if (tlv.it_len != sizeof(hash)) {
+                return -1;
+            }
+            sha_off = addr + off + sizeof(tlv);
+        }
+#if MYNEWT_VAL(BOOTUTIL_SIGN_RSA)
+        if (tlv.it_type == IMAGE_TLV_RSA2048) {
+            if (tlv.it_len != 256) { /* 2048 bits */
+                return -1;
+            }
+            sig_off = addr + off + sizeof(tlv);
+            sig_len = tlv.it_len;
+        }
+#endif
+#if MYNEWT_VAL(BOOTUTIL_SIGN_EC)
+        if (tlv.it_type == IMAGE_TLV_ECDSA224) {
+            if (tlv.it_len < 64) { /* oids + 2 * 28 bytes */
+                return -1;
+            }
+            sig_off = addr + off + sizeof(tlv);
+            sig_len = tlv.it_len;
+        }
+#endif
+    }
+    if (hdr->ih_flags & IMAGE_F_SHA256) {
+        if (!sha_off) {
+            /*
+             * Header said there should be hash TLV, no TLV found.
+             */
+            return -1;
+        }
+        rc = hal_flash_read(flash_id, sha_off, buf, sizeof(hash));
+        if (rc) {
+            return rc;
+        }
+        if (memcmp(hash, buf, sizeof(hash))) {
+            return -1;
+        }
+    }
+#if MYNEWT_VAL(BOOTUTIL_SIGN_RSA) || MYNEWT_VAL(BOOTUTIL_SIGN_EC)
+    if (!sig_off) {
+        /*
+         * Header said there should be PKCS1.v5 signature, no TLV
+         * found.
+         */
+        return -1;
+    }
+    rc = hal_flash_read(flash_id, sig_off, buf, sig_len);
+    if (rc) {
+        return -1;
+    }
+
+    if (hdr->ih_key_id >= bootutil_key_cnt) {
+        return -1;
+    }
+    rc = bootutil_verify_sig(hash, sizeof(hash), buf, sig_len, hdr->ih_key_id);
+    if (rc) {
+        return -1;
+    }
+#endif
+    return 0;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/boot/bootutil/src/loader.c
----------------------------------------------------------------------
diff --git a/boot/bootutil/src/loader.c b/boot/bootutil/src/loader.c
new file mode 100644
index 0000000..e2d4cfa
--- /dev/null
+++ b/boot/bootutil/src/loader.c
@@ -0,0 +1,652 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include <assert.h>
+#include <stddef.h>
+#include <inttypes.h>
+#include <stdlib.h>
+#include <string.h>
+#include <hal/flash_map.h>
+#include <hal/hal_flash.h>
+#include <os/os_malloc.h>
+#include "bootutil/loader.h"
+#include "bootutil/image.h"
+#include "bootutil/bootutil_misc.h"
+#include "bootutil_priv.h"
+
+/** Number of image slots in flash; currently limited to two. */
+#define BOOT_NUM_SLOTS              2
+
+/** The request object provided by the client. */
+static const struct boot_req *boot_req;
+
+/** Info about image slots. */
+static struct boot_img {
+    struct image_header hdr;
+    struct boot_image_location loc;
+    uint32_t area;
+} boot_img[BOOT_NUM_SLOTS];
+
+static struct boot_status boot_state;
+
+static int boot_erase_area(int area_idx, uint32_t sz);
+static uint32_t boot_copy_sz(int max_idx, int *cnt);
+
+
+int
+boot_build_request(struct boot_req *preq, int area_descriptor_max)
+{
+    int cnt;
+    int total;
+    int rc;
+    const struct flash_area *fap;
+    struct flash_area *descs = preq->br_area_descs;
+    uint8_t *img_starts = preq->br_slot_areas;
+
+    cnt = area_descriptor_max;
+    rc = flash_area_to_sectors(FLASH_AREA_IMAGE_0, &cnt, descs);
+    img_starts[0] = 0;
+    total = cnt;
+
+    flash_area_open(FLASH_AREA_IMAGE_0, &fap);
+    preq->br_img_sz = fap->fa_size;
+
+    cnt = area_descriptor_max - total;
+    if( cnt < 0) {
+        return -1;
+    }
+
+    rc = flash_area_to_sectors(FLASH_AREA_IMAGE_1, &cnt, &descs[total]);
+    if(rc != 0) {
+        return -2;
+    }
+    img_starts[1] = total;
+    total += cnt;
+
+    cnt = area_descriptor_max - total;
+    if( cnt < 0) {
+        return -3;
+    }
+
+    rc = flash_area_to_sectors(FLASH_AREA_IMAGE_SCRATCH, &cnt, &descs[total]);
+    if(rc != 0) {
+        return -4;
+    }
+
+    preq->br_scratch_area_idx = total;
+    total += cnt;
+    preq->br_num_image_areas = total;
+    return 0;
+}
+
+void
+boot_req_set(struct boot_req *req)
+{
+    boot_req = req;
+}
+
+/**
+ * Calculates the flash offset of the specified image slot.
+ *
+ * @param slot_num              The number of the slot to calculate.
+ * @param loc                   The flash location of the slot.
+ *
+ */
+static void
+boot_slot_addr(int slot_num, struct boot_image_location *loc)
+{
+    const struct flash_area *area_desc;
+    uint8_t area_idx;
+
+    area_idx = boot_req->br_slot_areas[slot_num];
+    area_desc = boot_req->br_area_descs + area_idx;
+    loc->bil_flash_id = area_desc->fa_flash_id;
+    loc->bil_address = area_desc->fa_off;
+}
+
+/*
+ * Status about copy-in-progress is either in slot0 (target slot) or
+ * in scratch area. It is in scratch area if the process is currently
+ * moving the last sector within image.
+ *
+ * If the copy-in-progress status is within the image slot, it will
+ * be at the end of the area.
+ * If the sector containing the boot copy status is in scratch, it's
+ * offset from beginning of scratch depends on how much of the image
+ * fits inside the scratch area.
+ *
+ * We start copy from the end of image, so boot-copy-status is in
+ * scratch when the first area is being moved. Otherwise it will be
+ * in slot 0.
+ */
+void
+boot_magic_loc(int slot_num, uint8_t *flash_id, uint32_t *off)
+{
+    struct boot_img *b;
+
+    b = &boot_img[slot_num];
+    *flash_id = b->loc.bil_flash_id;
+    *off = b->area + b->loc.bil_address - sizeof(struct boot_img_trailer);
+}
+
+void
+boot_scratch_loc(uint8_t *flash_id, uint32_t *off)
+{
+    struct flash_area *scratch;
+    int cnt;
+
+    scratch = &boot_req->br_area_descs[boot_req->br_scratch_area_idx];
+    *flash_id = scratch->fa_flash_id;
+
+    /*
+     * Calculate where the boot status would be, if it was copied to scratch.
+     */
+    *off = boot_copy_sz(boot_req->br_slot_areas[1], &cnt);
+    *off += (scratch->fa_off - sizeof(struct boot_img_trailer));
+}
+
+void
+boot_slot_magic(int slot_num, struct boot_img_trailer *bit)
+{
+    uint32_t off;
+    uint8_t flash_id;
+
+    boot_magic_loc(slot_num, &flash_id, &off);
+    memset(bit, 0xff, sizeof(*bit));
+    hal_flash_read(flash_id, off, bit, sizeof(*bit));
+}
+
+void
+boot_scratch_magic(struct boot_img_trailer *bit)
+{
+    uint32_t off;
+    uint8_t flash_id;
+
+    boot_scratch_loc(&flash_id, &off);
+    memset(bit, 0xff, sizeof(*bit));
+    hal_flash_read(flash_id, off, bit, sizeof(*bit));
+}
+
+/*
+ * Gather info about image in a given slot.
+ */
+void
+boot_image_info(void)
+{
+    int i;
+    struct boot_img *b;
+    struct flash_area *scratch;
+
+    for (i = 0; i < BOOT_NUM_SLOTS; i++) {
+        b = &boot_img[i];
+        boot_slot_addr(i, &b->loc);
+        boot_read_image_header(&b->loc, &b->hdr);
+        b->area = boot_req->br_img_sz;
+    }
+
+    /*
+     * Figure out what size to write update status update as.
+     * The size depends on what the minimum write size is for scratch
+     * area, active image slot. We need to use the bigger of those 2
+     * values.
+     */
+    boot_state.elem_sz = hal_flash_align(boot_img[0].loc.bil_flash_id);
+
+    scratch = &boot_req->br_area_descs[boot_req->br_scratch_area_idx];
+    i = hal_flash_align(scratch->fa_flash_id);
+    if (i > boot_state.elem_sz) {
+        boot_state.elem_sz = i;
+    }
+}
+
+static int
+boot_image_bootable(struct image_header *hdr) {
+    return ((hdr->ih_flags & IMAGE_F_NON_BOOTABLE) == 0);
+}
+
+/*
+ * Validate image hash/signature in a slot.
+ */
+static int
+boot_image_check(struct image_header *hdr, struct boot_image_location *loc)
+{
+    static void *tmpbuf;
+
+    if (!tmpbuf) {
+        tmpbuf = malloc(BOOT_TMPBUF_SZ);
+        if (!tmpbuf) {
+            return BOOT_ENOMEM;
+        }
+    }
+    if (bootutil_img_validate(hdr, loc->bil_flash_id, loc->bil_address,
+        tmpbuf, BOOT_TMPBUF_SZ, NULL, 0, NULL)) {
+        return BOOT_EBADIMAGE;
+    }
+    return 0;
+}
+
+
+static int
+split_image_check(struct image_header *app_hdr, struct boot_image_location *app_loc,
+                  struct image_header *loader_hdr, struct boot_image_location *loader_loc)
+{
+    static void *tmpbuf;
+    uint8_t loader_hash[32];
+
+    if (!tmpbuf) {
+        tmpbuf = malloc(BOOT_TMPBUF_SZ);
+        if (!tmpbuf) {
+            return BOOT_ENOMEM;
+        }
+    }
+    if (bootutil_img_validate(loader_hdr, loader_loc->bil_flash_id, loader_loc->bil_address,
+        tmpbuf, BOOT_TMPBUF_SZ, NULL, 0, loader_hash)) {
+        return BOOT_EBADIMAGE;
+    }
+
+    if (bootutil_img_validate(app_hdr, app_loc->bil_flash_id, app_loc->bil_address,
+        tmpbuf, BOOT_TMPBUF_SZ, loader_hash, 32, NULL)) {
+        return BOOT_EBADIMAGE;
+    }
+    return 0;
+}
+
+/**
+ * Selects a slot number to boot from.
+ *
+ * @return                      The slot number to boot from on success;
+ *                              -1 if an appropriate slot could not be
+ *                              determined.
+ */
+static int
+boot_select_image_slot(void)
+{
+    /*
+     * Check for swap magic. Check the integrity of the suggested image.
+     */
+    int rc;
+    int i;
+    struct boot_img *b;
+    struct boot_img_trailer bit;
+
+    boot_slot_magic(0, &bit);
+    if (bit.bit_copy_start == BOOT_IMG_MAGIC && bit.bit_copy_done != 0xff &&
+      bit.bit_img_ok == 0xff) {
+        /*
+         * Copied the image successfully, but image was not confirmed as good.
+         * We need to go back to another image.
+         */
+        boot_vect_write_test(FLASH_AREA_IMAGE_1);
+    }
+    for (i = 1; i < BOOT_NUM_SLOTS; i++) {
+        b = &boot_img[i];
+        boot_slot_magic(i, &bit);
+        if (bit.bit_copy_start == BOOT_IMG_MAGIC) {
+            if (b->hdr.ih_magic == IMAGE_MAGIC_NONE) {
+                continue;
+            }
+            if (!boot_image_bootable(&b->hdr)) {
+                continue;
+            }
+            rc = boot_image_check(&b->hdr, &b->loc);
+            if (rc) {
+                /*
+                 * Image fails integrity check. Erase it.
+                 */
+                boot_erase_area(boot_req->br_slot_areas[i], b->area);
+            } else {
+                return i;
+            }
+        }
+    }
+    return 0;
+}
+
+static int
+boot_status_sz(void)
+{
+    return sizeof(struct boot_img_trailer) + 32 * sizeof(uint32_t);
+}
+
+/*
+ * How many sectors starting from sector[idx] can fit inside scratch.
+ *
+ */
+static uint32_t
+boot_copy_sz(int max_idx, int *cnt)
+{
+    int i;
+    uint32_t sz;
+    static uint32_t scratch_sz = 0;
+
+    if (!scratch_sz) {
+        for (i = boot_req->br_scratch_area_idx;
+             i < boot_req->br_num_image_areas;
+             i++) {
+            scratch_sz += boot_req->br_area_descs[i].fa_size;
+        }
+    }
+    sz = 0;
+    *cnt = 0;
+    for (i = max_idx - 1; i >= 0; i--) {
+        if (sz + boot_req->br_area_descs[i].fa_size > scratch_sz) {
+            break;
+        }
+        sz += boot_req->br_area_descs[i].fa_size;
+        *cnt = *cnt + 1;
+    }
+    return sz;
+}
+
+/**
+ * Erase one area.  The destination area must
+ * be erased prior to this function being called.
+ *
+ * @param area_idx            The index of the area.
+ * @param sz                  The number of bytes to erase.
+ *
+ * @return                      0 on success; nonzero on failure.
+ */
+static int
+boot_erase_area(int area_idx, uint32_t sz)
+{
+    const struct flash_area *area_desc;
+    int rc;
+
+    area_desc = boot_req->br_area_descs + area_idx;
+    rc = hal_flash_erase(area_desc->fa_flash_id, area_desc->fa_off, sz);
+    if (rc != 0) {
+        return BOOT_EFLASH;
+    }
+    return 0;
+}
+
+/**
+ * Copies the contents of one area to another.  The destination area must
+ * be erased prior to this function being called.
+ *
+ * @param from_area_idx       The index of the source area.
+ * @param to_area_idx         The index of the destination area.
+ * @param sz                  The number of bytes to move.
+ *
+ * @return                      0 on success; nonzero on failure.
+ */
+static int
+boot_copy_area(int from_area_idx, int to_area_idx, uint32_t sz)
+{
+    const struct flash_area *from_area_desc;
+    const struct flash_area *to_area_desc;
+    uint32_t from_addr;
+    uint32_t to_addr;
+    uint32_t off;
+    int chunk_sz;
+    int rc;
+
+    static uint8_t buf[1024];
+
+    from_area_desc = boot_req->br_area_descs + from_area_idx;
+    to_area_desc = boot_req->br_area_descs + to_area_idx;
+
+    assert(to_area_desc->fa_size >= from_area_desc->fa_size);
+
+    off = 0;
+    while (off < sz) {
+        if (sz - off > sizeof buf) {
+            chunk_sz = sizeof buf;
+        } else {
+            chunk_sz = sz - off;
+        }
+
+        from_addr = from_area_desc->fa_off + off;
+        rc = hal_flash_read(from_area_desc->fa_flash_id, from_addr, buf,
+                            chunk_sz);
+        if (rc != 0) {
+            return rc;
+        }
+
+        to_addr = to_area_desc->fa_off + off;
+        rc = hal_flash_write(to_area_desc->fa_flash_id, to_addr, buf,
+                             chunk_sz);
+        if (rc != 0) {
+            return rc;
+        }
+
+        off += chunk_sz;
+    }
+
+    return 0;
+}
+
+/**
+ * Swaps the contents of two flash areas belonging to images.
+ *
+ * @param area_idx            The index of first slot to exchange. This area
+ *                                  must be part of the first image slot.
+ * @param sz                  The number of bytes swap.
+ *
+ * @param end_area            Boolean telling whether this includes this
+ *                                  area has last slots.
+ *
+ * @return                      0 on success; nonzero on failure.
+ */
+static int
+boot_swap_areas(int idx, uint32_t sz, int end_area)
+{
+    int area_idx_1;
+    int area_idx_2;
+    int rc;
+
+    area_idx_1 = boot_req->br_slot_areas[0] + idx;
+    area_idx_2 = boot_req->br_slot_areas[1] + idx;
+    assert(area_idx_1 != area_idx_2);
+    assert(area_idx_1 != boot_req->br_scratch_area_idx);
+    assert(area_idx_2 != boot_req->br_scratch_area_idx);
+
+    if (boot_state.state == 0) {
+        rc = boot_erase_area(boot_req->br_scratch_area_idx, sz);
+        if (rc != 0) {
+            return rc;
+        }
+
+        rc = boot_copy_area(area_idx_2, boot_req->br_scratch_area_idx, sz);
+        if (rc != 0) {
+            return rc;
+        }
+
+        boot_state.state = 1;
+        (void)boot_write_status(&boot_state);
+    }
+    if (boot_state.state == 1) {
+        rc = boot_erase_area(area_idx_2, sz);
+        if (rc != 0) {
+            return rc;
+        }
+
+        rc = boot_copy_area(area_idx_1, area_idx_2,
+          end_area ? (sz - boot_status_sz()) : sz);
+        if (rc != 0) {
+            return rc;
+        }
+
+        boot_state.state = 2;
+        (void)boot_write_status(&boot_state);
+    }
+    if (boot_state.state == 2) {
+        rc = boot_erase_area(area_idx_1, sz);
+        if (rc != 0) {
+            return rc;
+        }
+
+        rc = boot_copy_area(boot_req->br_scratch_area_idx, area_idx_1, sz);
+        if (rc != 0) {
+            return rc;
+        }
+
+        boot_state.idx++;
+        boot_state.state = 0;
+        (void)boot_write_status(&boot_state);
+    }
+    return 0;
+}
+
+/**
+ * Swaps the two images in flash.  If a prior copy operation was interrupted
+ * by a system reset, this function completes that operation.
+ *
+ * @return                      0 on success; nonzero on failure.
+ */
+static int
+boot_copy_image(void)
+{
+    uint32_t sz;
+    int i;
+    int end_area = 1;
+    int cnt;
+    int cur_idx;
+
+    for (i = boot_req->br_slot_areas[1], cur_idx = 0; i > 0; cur_idx++) {
+        sz = boot_copy_sz(i, &cnt);
+        i -= cnt;
+        if (cur_idx >= boot_state.idx) {
+            boot_swap_areas(i, sz, end_area);
+        }
+        end_area = 0;
+    }
+    boot_clear_status();
+
+    return 0;
+}
+
+/**
+ * Prepares the booting process.  Based on the information provided in the
+ * request object, this function moves images around in flash as appropriate,
+ * and tells you what address to boot from.
+ *
+ * @param req                   Contains information about the flash layout.
+ * @param rsp                   On success, indicates how booting should occur.
+ *
+ * @return                      0 on success; nonzero on failure.
+ */
+int
+boot_go(const struct boot_req *req, struct boot_rsp *rsp)
+{
+    int slot;
+    int rc;
+
+    /* Set the global boot request object.  The remainder of the boot process
+     * will reference the global.
+     */
+    boot_req = req;
+
+    /* Attempt to read an image header from each slot. */
+    boot_image_info();
+
+    /* Read the boot status to determine if an image copy operation was
+     * interrupted (i.e., the system was reset before the boot loader could
+     * finish its task last time).
+     */
+    if (boot_read_status(&boot_state)) {
+        /* We are resuming an interrupted image copy. */
+        rc = boot_copy_image();
+        if (rc != 0) {
+            /* We failed to put the images back together; there is really no
+             * solution here.
+             */
+            return rc;
+        }
+    }
+
+    /*
+     * Check if we should initiate copy, or revert back to earlier image.
+     *
+     */
+    slot = boot_select_image_slot();
+    if (slot == -1) {
+        return BOOT_EBADIMAGE;
+    }
+
+    if (slot) {
+        boot_state.idx = 0;
+        boot_state.state = 0;
+        rc = boot_copy_image();
+        if (rc) {
+            return rc;
+        }
+    }
+
+    /* Always boot from the primary slot. */
+    rsp->br_flash_id = boot_img[0].loc.bil_flash_id;
+    rsp->br_image_addr = boot_img[0].loc.bil_address;
+    rsp->br_hdr = &boot_img[slot].hdr;
+
+    return 0;
+}
+
+#define SPLIT_AREA_DESC_MAX     (255)
+
+int
+split_go(int loader_slot, int split_slot, void **entry)
+{
+    int rc;
+    /** Areas representing the beginning of image slots. */
+    uint8_t img_starts[2];
+    struct flash_area *descs;
+    uint32_t entry_val;
+    struct boot_req req = {
+        .br_slot_areas = img_starts,
+    };
+
+    descs = calloc(SPLIT_AREA_DESC_MAX, sizeof(struct flash_area));
+    if (descs == NULL) {
+        return SPLIT_GO_ERR;
+    }
+
+    req.br_area_descs = descs;
+
+    rc = boot_build_request(&req, SPLIT_AREA_DESC_MAX);
+    if (rc != 0) {
+        rc = SPLIT_GO_ERR;
+        goto split_app_go_end;
+    }
+
+    boot_req = &req;
+
+    boot_image_info();
+
+    /* Don't check the bootable image flag because we could really
+      * call a bootable or non-bootable image.  Just validate that
+      * the image check passes which is distinct from the normal check */
+    rc = split_image_check(&boot_img[split_slot].hdr,
+                           &boot_img[split_slot].loc,
+                           &boot_img[loader_slot].hdr,
+                           &boot_img[loader_slot].loc);
+    if (rc != 0) {
+        rc = SPLIT_GO_NON_MATCHING;
+        goto split_app_go_end;
+    }
+
+    entry_val = (uint32_t) boot_img[split_slot].loc.bil_address +
+                         (uint32_t)  boot_img[split_slot].hdr.ih_hdr_size;
+    *entry = (void*) entry_val;
+    rc = SPLIT_GO_OK;
+
+split_app_go_end:
+    free(descs);
+    return rc;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/boot/bootutil/test/pkg.yml
----------------------------------------------------------------------
diff --git a/boot/bootutil/test/pkg.yml b/boot/bootutil/test/pkg.yml
new file mode 100644
index 0000000..f602e31
--- /dev/null
+++ b/boot/bootutil/test/pkg.yml
@@ -0,0 +1,30 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+#
+pkg.name: boot/bootutil/test
+pkg.type: unittest
+pkg.description: "Bootutil unit tests."
+pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
+pkg.homepage: "http://mynewt.apache.org/"
+pkg.keywords:
+
+pkg.deps: 
+    - boot/bootutil
+    - test/testutil
+
+pkg.deps.SELFTEST:
+    - sys/console/stub


[43/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/encoding/tinycbor/src/cbortojson.c
----------------------------------------------------------------------
diff --git a/encoding/tinycbor/src/cbortojson.c b/encoding/tinycbor/src/cbortojson.c
new file mode 100644
index 0000000..953f2aa
--- /dev/null
+++ b/encoding/tinycbor/src/cbortojson.c
@@ -0,0 +1,686 @@
+/****************************************************************************
+**
+** Copyright (C) 2016 Intel Corporation
+**
+** Permission is hereby granted, free of charge, to any person obtaining a copy
+** of this software and associated documentation files (the "Software"), to deal
+** in the Software without restriction, including without limitation the rights
+** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+** copies of the Software, and to permit persons to whom the Software is
+** furnished to do so, subject to the following conditions:
+**
+** The above copyright notice and this permission notice shall be included in
+** all copies or substantial portions of the Software.
+**
+** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+** THE SOFTWARE.
+**
+****************************************************************************/
+
+#define _BSD_SOURCE 1
+#define _DEFAULT_SOURCE 1
+#define _GNU_SOURCE 1
+#define _POSIX_C_SOURCE 200809L
+#ifndef __STDC_LIMIT_MACROS
+#  define __STDC_LIMIT_MACROS 1
+#endif
+
+#include "cbor.h"
+#include "cborjson.h"
+#include "compilersupport_p.h"
+#include "math_support_p.h"
+
+#include <float.h>
+#include <inttypes.h>
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+
+/**
+ * \defgroup CborToJson Converting CBOR to JSON
+ * \brief Group of functions used to convert CBOR to JSON.
+ *
+ * This group contains two functions that are can be used to convert one
+ * CborValue object to an equivalent JSON representation. This module attempts
+ * to follow the recommendations from RFC 7049 section 4.1 "Converting from
+ * CBOR to JSON", though it has a few differences. They are noted below.
+ *
+ * These functions produce a "minified" JSON output, with no spacing,
+ * indentation or line breaks. If those are necessary, they need to be applied
+ * in a post-processing phase.
+ *
+ * Note that JSON cannot support all CBOR types with fidelity, so the
+ * conversion is usually lossy. For that reason, TinyCBOR supports adding a set
+ * of metadata JSON values that can be used by a JSON-to-CBOR converter to
+ * restore the original data types.
+ *
+ * The TinyCBOR library does not provide a way to convert from JSON
+ * representation back to encoded form. However, it provides a tool called
+ * \c json2cbor which can be used for that purpose. That tool supports the
+ * metadata format that these functions may produce.
+ *
+ * Either of the functions in this section will attempt to convert exactly one
+ * CborValue object to JSON. Those functions may return any error documented
+ * for the functions for CborParsing. In addition, if the C standard library
+ * stream functions return with error, the text conversion will return with
+ * error CborErrorIO.
+ *
+ * These functions also perform UTF-8 validation in CBOR text strings. If they
+ * encounter a sequence of bytes that not permitted in UTF-8, they will return
+ * CborErrorInvalidUtf8TextString. That includes encoding of surrogate points
+ * in UTF-8.
+ *
+ * \warning The metadata produced by these functions is not guaranteed to
+ * remain stable. A future update of TinyCBOR may produce different output for
+ * the same input and parsers may be unable to handle them.
+ *
+ * \sa CborParsing, CborPretty, cbor_parser_init()
+ */
+
+/**
+ * \addtogroup CborToJson
+ * @{
+ * <h2 class="groupheader">Conversion limitations</h2>
+ *
+ * When converting from CBOR to JSON, there may be information loss. This
+ * section lists the possible scenarios.
+ *
+ * \par Number precision:
+ * ALL JSON numbers, due to its JavaScript heritage, are IEEE 754
+ * double-precision floating point. This means JSON is not capable of
+ * representing integers numbers outside the range [-(2<sup>53</sup>)+1,
+ * 2<sup>53</sup>-1] and is not capable of representing NaN or infinite. If the
+ * CBOR data contains a number outside the valid range, the conversion will
+ * lose precision. If the input was NaN or infinite, the result of the
+ * conversion will be "null". In addition, the distinction between half-,
+ * single- and double-precision is lost.
+ *
+ * \par
+ * If enabled, the original value and original type are stored in the metadata.
+ *
+ * \par Non-native types:
+ * CBOR's type system is richer than JSON's, which means some data values
+ * cannot be represented when converted to JSON. The conversion silently turns
+ * them into strings: CBOR simple types become "simple(nn)" where \c nn is the
+ * simple type's value, with the exception of CBOR undefined, which becomes
+ * "undefined", while CBOR byte strings are converted to an Base16, Base64, or
+ * Base64url encoding
+ *
+ * \par
+ * If enabled, the original type is stored in the metadata.
+ *
+ * \par Presence of tags:
+ * JSON has no support for tagged values, so by default tags are dropped when
+ * converting to JSON. However, if the CborConvertObeyByteStringTags option is
+ * active (default), then certain known tags are honored and are used to format
+ * the conversion of the tagged byte string to JSON.
+ *
+ * \par
+ * If the CborConvertTagsToObjects option is active, then the tag and the
+ * tagged value are converted to to a JSON object. Otherwise, if enabled, the
+ * last (innermost) tag is stored in the metadata.
+ *
+ * \par Non-string keys in maps:
+ * JSON requires all Object keys to be strings, while CBOR does not. By
+ * default, if a non-string key is found, the conversion fails with error
+ * CborErrorJsonObjectKeyNotString. If the CborConvertStringifyMapKeys option
+ * is active, then the conversion attempts to create a string representation
+ * using CborPretty. Note that the \c json2cbor tool is not able to parse this
+ * back to the original form.
+ *
+ * \par Duplicate keys in maps:
+ * Neither JSON nor CBOR allow duplicated keys, but current TinyCBOR does not
+ * validate that this is the case. If there are duplicated keys in the input,
+ * they will be repeated in the output, which may JSON tools may flag as
+ * invalid. In addition to that, if the CborConvertStringifyMapKeys option is
+ * active, it is possible that a non-string key in a CBOR map will be converted
+ * to a string form that is identical to another key.
+ *
+ * \par
+ * When metadata support is active, the conversion will add extra key-value
+ * pairs to the JSON output so it can store the metadata. It is possible that
+ * the keys for the metadata clash with existing keys in the JSON map.
+ */
+
+extern FILE *open_memstream(char **bufptr, size_t *sizeptr);
+
+enum ConversionStatusFlags {
+    TypeWasNotNative            = 0x100,    /* anything but strings, boolean, null, arrays and maps */
+    TypeWasTagged               = 0x200,
+    NumberPrecisionWasLost      = 0x400,
+    NumberWasNaN                = 0x800,
+    NumberWasInfinite           = 0x1000,
+    NumberWasNegative           = 0x2000,   /* always used with NumberWasInifite or NumberWasTooBig */
+
+    FinalTypeMask               = 0xff
+};
+
+typedef struct ConversionStatus {
+    CborTag lastTag;
+    uint64_t originalNumber;
+    int flags;
+} ConversionStatus;
+
+static CborError value_to_json(FILE *out, CborValue *it, int flags, CborType type, ConversionStatus *status);
+
+static CborError dump_bytestring_base16(char **result, CborValue *it)
+{
+    static const char characters[] = "0123456789abcdef";
+    size_t i;
+    size_t n = 0;
+    uint8_t *buffer;
+    CborError err = cbor_value_calculate_string_length(it, &n);
+    if (err)
+        return err;
+
+    /* a Base16 (hex) output is twice as big as our buffer */
+    buffer = (uint8_t *)malloc(n * 2 + 1);
+    *result = (char *)buffer;
+
+    /* let cbor_value_copy_byte_string know we have an extra byte for the terminating NUL */
+    ++n;
+    err = cbor_value_copy_byte_string(it, buffer + n - 1, &n, it);
+    assert(err == CborNoError);
+
+    for (i = 0; i < n; ++i) {
+        uint8_t byte = buffer[n + i];
+        buffer[2*i]     = characters[byte >> 4];
+        buffer[2*i + 1] = characters[byte & 0xf];
+    }
+    return CborNoError;
+}
+
+static CborError generic_dump_base64(char **result, CborValue *it, const char alphabet[65])
+{
+    size_t n = 0, i;
+    uint8_t *buffer, *out, *in;
+    CborError err = cbor_value_calculate_string_length(it, &n);
+    if (err)
+        return err;
+
+    /* a Base64 output (untruncated) has 4 bytes for every 3 in the input */
+    size_t len = (n + 5) / 3 * 4;
+    out = buffer = (uint8_t *)malloc(len + 1);
+    *result = (char *)buffer;
+
+    /* we read our byte string at the tail end of the buffer
+     * so we can do an in-place conversion while iterating forwards */
+    in = buffer + len - n;
+
+    /* let cbor_value_copy_byte_string know we have an extra byte for the terminating NUL */
+    ++n;
+    err = cbor_value_copy_byte_string(it, in, &n, it);
+    assert(err == CborNoError);
+
+    uint_least32_t val = 0;
+    for (i = 0; n - i >= 3; i += 3) {
+        /* read 3 bytes x 8 bits = 24 bits */
+        if (false) {
+#ifdef __GNUC__
+        } else if (i) {
+            __builtin_memcpy(&val, in + i - 1, sizeof(val));
+            val = cbor_ntohl(val);
+#endif
+        } else {
+            val = (in[i] << 16) | (in[i + 1] << 8) | in[i + 2];
+        }
+
+        /* write 4 chars x 6 bits = 24 bits */
+        *out++ = alphabet[(val >> 18) & 0x3f];
+        *out++ = alphabet[(val >> 12) & 0x3f];
+        *out++ = alphabet[(val >> 6) & 0x3f];
+        *out++ = alphabet[val & 0x3f];
+    }
+
+    /* maybe 1 or 2 bytes left */
+    if (n - i) {
+        /* we can read in[i + 1] even if it's past the end of the string because
+         * we know (by construction) that it's a NUL byte */
+#ifdef __GNUC__
+        uint16_t val16;
+        __builtin_memcpy(&val16, in + i, sizeof(val16));
+        val = cbor_ntohs(val16);
+#else
+        val = (in[i] << 8) | in[i + 1];
+#endif
+        val <<= 8;
+
+        /* the 65th character in the alphabet is our filler: either '=' or '\0' */
+        out[4] = '\0';
+        out[3] = alphabet[64];
+        if (n - i == 2) {
+            /* write the third char in 3 chars x 6 bits = 18 bits */
+            out[2] = alphabet[(val >> 6) & 0x3f];
+        } else {
+            out[2] = alphabet[64];  /* filler */
+        }
+        out[1] = alphabet[(val >> 12) & 0x3f];
+        out[0] = alphabet[(val >> 18) & 0x3f];
+    } else {
+        out[0] = '\0';
+    }
+
+    return CborNoError;
+}
+
+static CborError dump_bytestring_base64(char **result, CborValue *it)
+{
+    static const char alphabet[] = "ABCDEFGH" "IJKLMNOP" "QRSTUVWX" "YZabcdef"
+                                   "ghijklmn" "opqrstuv" "wxyz0123" "456789+/" "=";
+    return generic_dump_base64(result, it, alphabet);
+}
+
+static CborError dump_bytestring_base64url(char **result, CborValue *it)
+{
+    static const char alphabet[] = "ABCDEFGH" "IJKLMNOP" "QRSTUVWX" "YZabcdef"
+                                   "ghijklmn" "opqrstuv" "wxyz0123" "456789-_";
+    return generic_dump_base64(result, it, alphabet);
+}
+
+static CborError add_value_metadata(FILE *out, CborType type, const ConversionStatus *status)
+{
+    int flags = status->flags;
+    if (flags & TypeWasTagged) {
+        /* extract the tagged type, which may be JSON native */
+        type = flags & FinalTypeMask;
+        flags &= ~(FinalTypeMask | TypeWasTagged);
+
+        if (fprintf(out, "\"tag\":\"%" PRIu64 "\"%s", status->lastTag,
+                    flags & ~TypeWasTagged ? "," : "") < 0)
+            return CborErrorIO;
+    }
+
+    if (!flags)
+        return CborNoError;
+
+    /* print at least the type */
+    if (fprintf(out, "\"t\":%d", type) < 0)
+        return CborErrorIO;
+
+    if (flags & NumberWasNaN)
+        if (fprintf(out, ",\"v\":\"nan\"") < 0)
+            return CborErrorIO;
+    if (flags & NumberWasInfinite)
+        if (fprintf(out, ",\"v\":\"%sinf\"", flags & NumberWasNegative ? "-" : "") < 0)
+            return CborErrorIO;
+    if (flags & NumberPrecisionWasLost)
+        if (fprintf(out, ",\"v\":\"%c%" PRIx64 "\"", flags & NumberWasNegative ? '-' : '+',
+                    status->originalNumber) < 0)
+            return CborErrorIO;
+    if (type == CborSimpleType)
+        if (fprintf(out, ",\"v\":%d", (int)status->originalNumber) < 0)
+            return CborErrorIO;
+    return CborNoError;
+}
+
+static CborError find_tagged_type(CborValue *it, CborTag *tag, CborType *type)
+{
+    CborError err = CborNoError;
+    *type = cbor_value_get_type(it);
+    while (*type == CborTagType) {
+        cbor_value_get_tag(it, tag);    /* can't fail */
+        err = cbor_value_advance_fixed(it);
+        if (err)
+            return err;
+
+        *type = cbor_value_get_type(it);
+    }
+    return err;
+}
+
+static CborError tagged_value_to_json(FILE *out, CborValue *it, int flags, ConversionStatus *status)
+{
+    CborTag tag;
+    CborError err;
+
+    if (flags & CborConvertTagsToObjects) {
+        cbor_value_get_tag(it, &tag);       /* can't fail */
+        err = cbor_value_advance_fixed(it);
+        if (err)
+            return err;
+
+        if (fprintf(out, "{\"tag%" PRIu64 "\":", tag) < 0)
+            return CborErrorIO;
+
+        CborType type = cbor_value_get_type(it);
+        err = value_to_json(out, it, flags, type, status);
+        if (err)
+            return err;
+        if (flags & CborConvertAddMetadata && status->flags) {
+            if (fprintf(out, ",\"tag%" PRIu64 "$cbor\":{", tag) < 0 ||
+                    add_value_metadata(out, type, status) != CborNoError ||
+                    fputc('}', out) < 0)
+                return CborErrorIO;
+        }
+        if (fputc('}', out) < 0)
+            return CborErrorIO;
+        status->flags = TypeWasNotNative | CborTagType;
+        return CborNoError;
+    }
+
+    CborType type;
+    err = find_tagged_type(it, &status->lastTag, &type);
+    if (err)
+        return err;
+    tag = status->lastTag;
+
+    /* special handling of byte strings? */
+    if (type == CborByteStringType && (flags & CborConvertByteStringsToBase64Url) == 0 &&
+            (tag == CborNegativeBignumTag || tag == CborExpectedBase16Tag || tag == CborExpectedBase64Tag)) {
+        char *str;
+        char *pre = "";
+
+        if (tag == CborNegativeBignumTag) {
+            pre = "~";
+            err = dump_bytestring_base64url(&str, it);
+        } else if (tag == CborExpectedBase64Tag) {
+            err = dump_bytestring_base64(&str, it);
+        } else { /* tag == CborExpectedBase16Tag */
+            err = dump_bytestring_base16(&str, it);
+        }
+        if (err)
+            return err;
+        err = fprintf(out, "\"%s%s\"", pre, str) < 0 ? CborErrorIO : CborNoError;
+        free(str);
+        status->flags = TypeWasNotNative | TypeWasTagged | CborByteStringType;
+        return err;
+    }
+
+    /* no special handling */
+    err = value_to_json(out, it, flags, type, status);
+    status->flags |= TypeWasTagged | type;
+    return err;
+}
+
+static CborError stringify_map_key(char **key, CborValue *it, int flags, CborType type)
+{
+    (void)flags;    /* unused */
+    (void)type;     /* unused */
+#ifdef WITHOUT_OPEN_MEMSTREAM
+    (void)key;      /* unused */
+    (void)it;       /* unused */
+    return CborErrorJsonNotImplemented;
+#else
+    size_t size;
+
+    FILE *memstream = open_memstream(key, &size);
+    if (memstream == NULL)
+        return CborErrorOutOfMemory;        /* could also be EMFILE, but it's unlikely */
+    CborError err = cbor_value_to_pretty_advance(memstream, it);
+
+    if (unlikely(fclose(memstream) < 0 || *key == NULL))
+        return CborErrorInternalError;
+    return err;
+#endif
+}
+
+static CborError array_to_json(FILE *out, CborValue *it, int flags, ConversionStatus *status)
+{
+    const char *comma = "";
+    while (!cbor_value_at_end(it)) {
+        if (fprintf(out, "%s", comma) < 0)
+            return CborErrorIO;
+        comma = ",";
+
+        CborError err = value_to_json(out, it, flags, cbor_value_get_type(it), status);
+        if (err)
+            return err;
+    }
+    return CborNoError;
+}
+
+static CborError map_to_json(FILE *out, CborValue *it, int flags, ConversionStatus *status)
+{
+    const char *comma = "";
+    CborError err;
+    while (!cbor_value_at_end(it)) {
+        char *key;
+        if (fprintf(out, "%s", comma) < 0)
+            return CborErrorIO;
+        comma = ",";
+
+        CborType keyType = cbor_value_get_type(it);
+        if (likely(keyType == CborTextStringType)) {
+            size_t n = 0;
+            err = cbor_value_dup_text_string(it, &key, &n, it);
+        } else if (flags & CborConvertStringifyMapKeys) {
+            err = stringify_map_key(&key, it, flags, keyType);
+        } else {
+            return CborErrorJsonObjectKeyNotString;
+        }
+        if (err)
+            return err;
+
+        /* first, print the key */
+        if (fprintf(out, "\"%s\":", key) < 0)
+            return CborErrorIO;
+
+        /* then, print the value */
+        CborType valueType = cbor_value_get_type(it);
+        err = value_to_json(out, it, flags, valueType, status);
+
+        /* finally, print any metadata we may have */
+        if (flags & CborConvertAddMetadata) {
+            if (!err && keyType != CborTextStringType) {
+                if (fprintf(out, ",\"%s$keycbordump\":true", key) < 0)
+                    err = CborErrorIO;
+            }
+            if (!err && status->flags) {
+                if (fprintf(out, ",\"%s$cbor\":{", key) < 0 ||
+                        add_value_metadata(out, valueType, status) != CborNoError ||
+                        fputc('}', out) < 0)
+                    err = CborErrorIO;
+            }
+        }
+
+        free(key);
+        if (err)
+            return err;
+    }
+    return CborNoError;
+}
+
+static CborError value_to_json(FILE *out, CborValue *it, int flags, CborType type, ConversionStatus *status)
+{
+    CborError err;
+    status->flags = 0;
+
+    switch (type) {
+    case CborArrayType:
+    case CborMapType: {
+        /* recursive type */
+        CborValue recursed;
+        err = cbor_value_enter_container(it, &recursed);
+        if (err) {
+            it->ptr = recursed.ptr;
+            return err;       /* parse error */
+        }
+        if (fputc(type == CborArrayType ? '[' : '{', out) < 0)
+            return CborErrorIO;
+
+        err = (type == CborArrayType) ?
+                  array_to_json(out, &recursed, flags, status) :
+                  map_to_json(out, &recursed, flags, status);
+        if (err) {
+            it->ptr = recursed.ptr;
+            return err;       /* parse error */
+        }
+
+        if (fputc(type == CborArrayType ? ']' : '}', out) < 0)
+            return CborErrorIO;
+        err = cbor_value_leave_container(it, &recursed);
+        if (err)
+            return err;       /* parse error */
+
+        status->flags = 0;    /* reset, there are never conversion errors for us */
+        return CborNoError;
+    }
+
+    case CborIntegerType: {
+        double num;     /* JS numbers are IEEE double precision */
+        uint64_t val;
+        cbor_value_get_raw_integer(it, &val);    /* can't fail */
+        num = (double)val;
+
+        if (cbor_value_is_negative_integer(it)) {
+            num = -num - 1;                     /* convert to negative */
+            if ((uint64_t)(-num - 1) != val) {
+                status->flags = NumberPrecisionWasLost | NumberWasNegative;
+                status->originalNumber = val;
+            }
+        } else {
+            if ((uint64_t)num != val) {
+                status->flags = NumberPrecisionWasLost;
+                status->originalNumber = val;
+            }
+        }
+        if (fprintf(out, "%.0f", num) < 0)  /* this number has no fraction, so no decimal points please */
+            return CborErrorIO;
+        break;
+    }
+
+    case CborByteStringType:
+    case CborTextStringType: {
+        char *str;
+        if (type == CborByteStringType) {
+            err = dump_bytestring_base64url(&str, it);
+            status->flags = TypeWasNotNative;
+        } else {
+            size_t n = 0;
+            err = cbor_value_dup_text_string(it, &str, &n, it);
+        }
+        if (err)
+            return err;
+        err = (fprintf(out, "\"%s\"", str) < 0) ? CborErrorIO : CborNoError;
+        free(str);
+        return err;
+    }
+
+    case CborTagType:
+        return tagged_value_to_json(out, it, flags, status);
+
+    case CborSimpleType: {
+        uint8_t simple_type;
+        cbor_value_get_simple_type(it, &simple_type);  /* can't fail */
+        status->flags = TypeWasNotNative;
+        status->originalNumber = simple_type;
+        if (fprintf(out, "\"simple(%" PRIu8 ")\"", simple_type) < 0)
+            return CborErrorIO;
+        break;
+    }
+
+    case CborNullType:
+        if (fprintf(out, "null") < 0)
+            return CborErrorIO;
+        break;
+
+    case CborUndefinedType:
+        status->flags = TypeWasNotNative;
+        if (fprintf(out, "\"undefined\"") < 0)
+            return CborErrorIO;
+        break;
+
+    case CborBooleanType: {
+        bool val;
+        cbor_value_get_boolean(it, &val);       /* can't fail */
+        if (fprintf(out, val ? "true" : "false") < 0)
+            return CborErrorIO;
+        break;
+    }
+
+    case CborDoubleType: {
+        double val;
+        if (false) {
+            float f;
+    case CborFloatType:
+            status->flags = TypeWasNotNative;
+            cbor_value_get_float(it, &f);
+            val = f;
+        } else if (false) {
+            uint16_t f16;
+    case CborHalfFloatType:
+            status->flags = TypeWasNotNative;
+            cbor_value_get_half_float(it, &f16);
+            val = decode_half(f16);
+        } else {
+            cbor_value_get_double(it, &val);
+        }
+
+        int r = fpclassify(val);
+        if (r == FP_NAN || r == FP_INFINITE) {
+            if (fprintf(out, "null") < 0)
+                return CborErrorIO;
+            status->flags |= r == FP_NAN ? NumberWasNaN :
+                                           NumberWasInfinite | (val < 0 ? NumberWasNegative : 0);
+        } else {
+            uint64_t ival = (uint64_t)fabs(val);
+            if ((double)ival == fabs(val)) {
+                /* print as integer so we get the full precision */
+                r = fprintf(out, "%s%" PRIu64, val < 0 ? "-" : "", ival);
+                status->flags |= TypeWasNotNative;   /* mark this integer number as a double */
+            } else {
+                /* this number is definitely not a 64-bit integer */
+                r = fprintf(out, "%." DBL_DECIMAL_DIG_STR "g", val);
+            }
+            if (r < 0)
+                return CborErrorIO;
+        }
+        break;
+    }
+
+    case CborInvalidType:
+        return CborErrorUnknownType;
+    }
+
+    return cbor_value_advance_fixed(it);
+}
+
+/**
+ * \enum CborToJsonFlags
+ * The CborToJsonFlags enum contains flags that control the conversion of CBOR to JSON.
+ *
+ * \value CborConvertAddMetadata        Adds metadata to facilitate restoration of the original CBOR data.
+ * \value CborConvertTagsToObjects      Converts CBOR tags to JSON objects
+ * \value CborConvertIgnoreTags         (default) Ignore CBOR tags, except for byte strings
+ * \value CborConvertObeyByteStringTags (default) Honor formatting of CBOR byte strings if so tagged
+ * \value CborConvertByteStringsToBase64Url Force the conversion of all CBOR byte strings to Base64url encoding, despite any tags
+ * \value CborConvertRequireMapStringKeys (default) Require CBOR map keys to be strings, failing the conversion if they are not
+ * \value CborConvertStringifyMapKeys   Convert non-string keys in CBOR maps to a string form
+ * \value CborConvertDefaultFlags       Default conversion flags.
+ */
+
+/**
+ * \fn CborError cbor_value_to_json(FILE *out, const CborValue *value, int flags)
+ *
+ * Converts the current CBOR type pointed by \a value to JSON and writes that
+ * to the \a out stream. If an error occurs, this function returns an error
+ * code similar to CborParsing. The \a flags parameter indicates one of the
+ * flags from CborToJsonFlags that control the conversion.
+ *
+ * \sa cbor_value_to_json_advance(), cbor_value_to_pretty()
+ */
+
+/**
+ * Converts the current CBOR type pointed by \a value to JSON and writes that
+ * to the \a out stream. If an error occurs, this function returns an error
+ * code similar to CborParsing. The \a flags parameter indicates one of the
+ * flags from CborToJsonFlags that control the conversion.
+ *
+ * If no error ocurred, this function advances \a value to the next element.
+ *
+ * \sa cbor_value_to_json(), cbor_value_to_pretty_advance()
+ */
+CborError cbor_value_to_json_advance(FILE *out, CborValue *value, int flags)
+{
+    ConversionStatus status;
+    return value_to_json(out, value, flags, cbor_value_get_type(value), &status);
+}
+
+/** @} */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/encoding/tinycbor/src/open_memstream.c
----------------------------------------------------------------------
diff --git a/encoding/tinycbor/src/open_memstream.c b/encoding/tinycbor/src/open_memstream.c
new file mode 100644
index 0000000..eaa53e5
--- /dev/null
+++ b/encoding/tinycbor/src/open_memstream.c
@@ -0,0 +1,117 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 Intel Corporation
+**
+** Permission is hereby granted, free of charge, to any person obtaining a copy
+** of this software and associated documentation files (the "Software"), to deal
+** in the Software without restriction, including without limitation the rights
+** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+** copies of the Software, and to permit persons to whom the Software is
+** furnished to do so, subject to the following conditions:
+**
+** The above copyright notice and this permission notice shall be included in
+** all copies or substantial portions of the Software.
+**
+** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+** THE SOFTWARE.
+**
+****************************************************************************/
+
+#define _BSD_SOURCE 1
+#define _DEFAULT_SOURCE 1
+#define _GNU_SOURCE 1
+
+#ifndef WITHOUT_OPEN_MEMSTREAM
+
+#include <sys/types.h>
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#if defined(__unix__) || defined(__APPLE__)
+#  include <unistd.h>
+#endif
+#ifdef __APPLE__
+typedef int RetType;
+typedef int LenType;
+#elif __GLIBC__
+typedef ssize_t RetType;
+typedef size_t LenType;
+#else
+#  error "Cannot implement open_memstream!"
+#endif
+
+#include "compilersupport_p.h"
+
+struct Buffer
+{
+    char **ptr;
+    size_t *len;
+    size_t alloc;
+};
+
+static RetType write_to_buffer(void *cookie, const char *data, LenType len)
+{
+    struct Buffer *b = (struct Buffer *)cookie;
+    char *ptr = *b->ptr;
+    size_t newsize;
+
+    errno = EFBIG;
+    if (unlikely(add_check_overflow(*b->len, len, &newsize)))
+        return -1;
+
+    if (newsize > b->alloc) {
+        // make room
+        size_t newalloc = newsize + newsize / 2 + 1;    // give 50% more room
+        ptr = realloc(ptr, newalloc);
+        if (ptr == NULL)
+            return -1;
+        b->alloc = newalloc;
+        *b->ptr = ptr;
+    }
+
+    memcpy(ptr + *b->len, data, len);
+    *b->len = newsize;
+    return len;
+}
+
+static int close_buffer(void *cookie)
+{
+    struct Buffer *b = (struct Buffer *)cookie;
+    if (*b->ptr)
+        (*b->ptr)[*b->len] = '\0';
+    free(b);
+    return 0;
+}
+
+FILE *open_memstream(char **bufptr, size_t *lenptr)
+{
+    struct Buffer *b = (struct Buffer *)malloc(sizeof(struct Buffer));
+    if (b == NULL)
+        return NULL;
+    b->alloc = 0;
+    b->len = lenptr;
+    b->ptr = bufptr;
+    *bufptr = NULL;
+    *lenptr = 0;
+
+#ifdef __APPLE__
+    return funopen(b, NULL, write_to_buffer, NULL, close_buffer);
+#elif __GLIBC__
+    static const cookie_io_functions_t vtable = {
+        NULL,
+        write_to_buffer,
+        NULL,
+        close_buffer
+    };
+    return fopencookie(b, "w", vtable);
+#endif
+}
+
+#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/fs/fcb/README.md
----------------------------------------------------------------------
diff --git a/fs/fcb/README.md b/fs/fcb/README.md
new file mode 100644
index 0000000..5d13ccd
--- /dev/null
+++ b/fs/fcb/README.md
@@ -0,0 +1,58 @@
+<!--
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+#
+-->
+
+# Flash circular buffer
+
+# Overview
+
+Storage of elements in flash in FIFO fashion. Elements are appended to the of the area until storage space is exhausted. Then the oldest sector should be erased and that can be used in storing new entries.
+
+# API
+
+fcb_init()
+  - initialize fcb for a given array of flash sectors
+
+fcb_append()
+  - reserve space to store an element
+fcb_append_finish()
+  - storage of the element is finished; can calculate CRC for it
+
+fcb_walk(cb, sector)
+  - call cb for every element in the buffer. Or for every element in
+    a particular flash sector, if sector is specified
+fcb_getnext(elem)
+  - return element following elem
+
+fcb_rotate()
+  - erase oldest used sector, and make it current
+
+# Usage
+
+To add an element to circular buffer:
+1. call fcb_append() to get location; if this fails due to lack of space,
+   call fcb_rotate()
+2. use flash_area_write() to write contents
+3. call fcb_append_finish() when done
+
+To read contents of the circular buffer:
+1. call fcb_walk() with callback
+2. within callback: copy in data from the element using flash_area_read(),
+   call fcb_rotate() when all elements from a given sector have been read

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/fs/fcb/include/fcb/fcb.h
----------------------------------------------------------------------
diff --git a/fs/fcb/include/fcb/fcb.h b/fs/fcb/include/fcb/fcb.h
new file mode 100644
index 0000000..a6b3f88
--- /dev/null
+++ b/fs/fcb/include/fcb/fcb.h
@@ -0,0 +1,134 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 __SYS_FCB_H_
+#define __SYS_FCB_H_
+
+/*
+ * Flash circular buffer.
+ */
+#include <inttypes.h>
+#include <limits.h>
+
+#include <hal/flash_map.h>
+
+#include <os/os_mutex.h>
+
+#define FCB_MAX_LEN	(CHAR_MAX | CHAR_MAX << 7) /* Max length of element */
+
+/*
+ * Entry location is pointer to area (within fcb->f_sectors), and offset
+ * within that area.
+ */
+struct fcb_entry {
+    struct flash_area *fe_area;	/* ptr to area within fcb->f_sectors */
+    uint32_t fe_elem_off;	/* start of entry */
+    uint32_t fe_data_off;	/* start of data */
+    uint16_t fe_data_len;	/* size of data area */
+};
+
+struct fcb {
+    /* Caller of fcb_init fills this in */
+    uint32_t f_magic;		/* As placed on the disk */
+    uint8_t f_version;  	/* Current version number of the data */
+    uint8_t f_sector_cnt;	/* Number of elements in sector array */
+    uint8_t f_scratch_cnt;	/* How many sectors should be kept empty */
+    struct flash_area *f_sectors; /* Array of sectors, must be contiguous */
+
+    /* Flash circular buffer internal state */
+    struct os_mutex f_mtx;	/* Locking for accessing the FCB data */
+    struct flash_area *f_oldest;
+    struct fcb_entry f_active;
+    uint16_t f_active_id;
+    uint8_t f_align;		/* writes to flash have to aligned to this */
+};
+
+/*
+ * Error codes.
+ */
+#define FCB_OK		0
+#define FCB_ERR_ARGS	-1
+#define FCB_ERR_FLASH	-2
+#define FCB_ERR_NOVAR   -3
+#define FCB_ERR_NOSPACE	-4
+#define FCB_ERR_NOMEM	-5
+#define FCB_ERR_CRC	-6
+#define FCB_ERR_MAGIC   -7
+
+int fcb_init(struct fcb *fcb);
+
+/*
+ * fcb_log is needed as the number of entries in a log
+ */
+struct fcb_log {
+    struct fcb fl_fcb;
+    uint8_t fl_entries;
+};
+
+int log_fcb_init(struct fcb_log *fcblog, struct fcb *fcb, uint16_t entries);
+
+/*
+ * fcb_append() appends an entry to circular buffer. When writing the
+ * contents for the entry, use loc->fl_area and loc->fl_data_off with
+ * flash_area_write(). When you're finished, call fcb_append_finish() with
+ * loc as argument.
+ */
+int fcb_append(struct fcb *, uint16_t len, struct fcb_entry *loc);
+int fcb_append_finish(struct fcb *, struct fcb_entry *append_loc);
+
+/*
+ * Walk over all log entries in FCB, or entries in a given flash_area.
+ * cb gets called for every entry. If cb wants to stop the walk, it should
+ * return non-zero value.
+ *
+ * Entry data can be read using flash_area_read(), using
+ * loc->fe_area, loc->fe_data_off, and loc->fe_data_len as arguments.
+ */
+typedef int (*fcb_walk_cb)(struct fcb_entry *loc, void *arg);
+int fcb_walk(struct fcb *, struct flash_area *, fcb_walk_cb cb, void *cb_arg);
+int fcb_getnext(struct fcb *, struct fcb_entry *loc);
+
+/*
+ * Erases the data from oldest sector.
+ */
+int fcb_rotate(struct fcb *);
+
+/*
+ * Start using the scratch block.
+ */
+int fcb_append_to_scratch(struct fcb *);
+
+/*
+ * How many sectors are unused.
+ */
+int fcb_free_sector_cnt(struct fcb *fcb);
+
+/*
+ * Whether FCB has any data.
+ */
+int fcb_is_empty(struct fcb *fcb);
+
+int
+fcb_offset_last_n(struct fcb *fcb, uint8_t entries, uint32_t *last_n_off);
+
+/*
+ * Clears FCB passed to it
+ */
+int fcb_clear(struct fcb *fcb);
+
+#endif /* __SYS_FLASHVAR_H_ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/fs/fcb/pkg.yml
----------------------------------------------------------------------
diff --git a/fs/fcb/pkg.yml b/fs/fcb/pkg.yml
new file mode 100644
index 0000000..9b90bb9
--- /dev/null
+++ b/fs/fcb/pkg.yml
@@ -0,0 +1,29 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+#
+
+pkg.name: fs/fcb
+pkg.description: Flash circular buffer.
+pkg.keywords:
+    - flash
+    - storage
+    - log
+
+pkg.deps:
+    - kernel/os
+    - encoding/crc

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/fs/fcb/src/fcb.c
----------------------------------------------------------------------
diff --git a/fs/fcb/src/fcb.c b/fs/fcb/src/fcb.c
new file mode 100644
index 0000000..fb85508
--- /dev/null
+++ b/fs/fcb/src/fcb.c
@@ -0,0 +1,258 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+#include <limits.h>
+#include <stdlib.h>
+
+#include "fcb/fcb.h"
+#include "fcb_priv.h"
+#include "string.h"
+
+int
+fcb_init(struct fcb *fcb)
+{
+    struct flash_area *fap;
+    int rc;
+    int i;
+    int max_align = 1;
+    int align;
+    int oldest = -1, newest = -1;
+    struct flash_area *oldest_fap = NULL, *newest_fap = NULL;
+    struct fcb_disk_area fda;
+
+    if (!fcb->f_sectors || fcb->f_sector_cnt - fcb->f_scratch_cnt < 1) {
+        return FCB_ERR_ARGS;
+    }
+
+    /* Fill last used, first used */
+    for (i = 0; i < fcb->f_sector_cnt; i++) {
+        fap = &fcb->f_sectors[i];
+        align = flash_area_align(fap);
+        if (align > max_align) {
+            max_align = flash_area_align(fap);
+        }
+        rc = fcb_sector_hdr_read(fcb, fap, &fda);
+        if (rc <= 0) {
+            continue;
+        }
+        if (oldest < 0) {
+            oldest = newest = fda.fd_id;
+            oldest_fap = newest_fap = fap;
+            continue;
+        }
+        if (FCB_ID_GT(fda.fd_id, newest)) {
+            newest = fda.fd_id;
+            newest_fap = fap;
+        } else if (FCB_ID_GT(oldest, fda.fd_id)) {
+            oldest = fda.fd_id;
+            oldest_fap = fap;
+        }
+    }
+    if (oldest < 0) {
+        /*
+         * No initialized areas.
+         */
+        oldest_fap = newest_fap = &fcb->f_sectors[0];
+        rc = fcb_sector_hdr_init(fcb, oldest_fap, 0);
+        if (rc) {
+            return rc;
+        }
+        newest = oldest = 0;
+    }
+    fcb->f_align = max_align;
+    fcb->f_oldest = oldest_fap;
+    fcb->f_active.fe_area = newest_fap;
+    fcb->f_active.fe_elem_off = sizeof(struct fcb_disk_area);
+    fcb->f_active_id = newest;
+
+    while (1) {
+        rc = fcb_getnext_in_area(fcb, &fcb->f_active);
+        if (rc == FCB_ERR_NOVAR) {
+            rc = FCB_OK;
+            break;
+        }
+        if (rc != 0) {
+            break;
+        }
+    }
+    os_mutex_init(&fcb->f_mtx);
+    return rc;
+}
+
+int
+fcb_free_sector_cnt(struct fcb *fcb)
+{
+    int i;
+    struct flash_area *fa;
+
+    fa = fcb->f_active.fe_area;
+    for (i = 0; i < fcb->f_sector_cnt; i++) {
+        fa = fcb_getnext_area(fcb, fa);
+        if (fa == fcb->f_oldest) {
+            break;
+        }
+    }
+    return i;
+}
+
+int
+fcb_is_empty(struct fcb *fcb)
+{
+    return (fcb->f_active.fe_area == fcb->f_oldest &&
+      fcb->f_active.fe_elem_off == sizeof(struct fcb_disk_area));
+}
+
+/**
+ * Length of an element is encoded in 1 or 2 bytes.
+ * 1 byte for lengths < 128 bytes, and 2 bytes for < 16384.
+ */
+int
+fcb_put_len(uint8_t *buf, uint16_t len)
+{
+    if (len < CHAR_MAX) {
+        buf[0] = len;
+        return 1;
+    } else if (len < FCB_MAX_LEN) {
+        buf[0] = (len & 0x7f) | 0x80;
+        buf[1] = len >> 7;
+        return 2;
+    } else {
+        return FCB_ERR_ARGS;
+    }
+}
+
+int
+fcb_get_len(uint8_t *buf, uint16_t *len)
+{
+    int rc;
+
+    if (buf[0] & 0x80) {
+        if (buf[0] == 0xff && buf[1] == 0xff) {
+            return FCB_ERR_NOVAR;
+        }
+        *len = (buf[0] & 0x7f) | (buf[1] << 7);
+        rc = 2;
+    } else {
+        *len = buf[0];
+        rc = 1;
+    }
+    return rc;
+}
+
+/**
+ * Initialize erased sector for use.
+ */
+int
+fcb_sector_hdr_init(struct fcb *fcb, struct flash_area *fap, uint16_t id)
+{
+    struct fcb_disk_area fda;
+    int rc;
+
+    fda.fd_magic = fcb->f_magic;
+    fda.fd_ver = fcb->f_version;
+    fda._pad = 0xff;
+    fda.fd_id = id;
+
+    rc = flash_area_write(fap, 0, &fda, sizeof(fda));
+    if (rc) {
+        return FCB_ERR_FLASH;
+    }
+    return 0;
+}
+
+/**
+ * Checks whether FCB sector contains data or not.
+ * Returns <0 in error.
+ * Returns 0 if sector is unused;
+ * Returns 1 if sector has data.
+ */
+int
+fcb_sector_hdr_read(struct fcb *fcb, struct flash_area *fap,
+  struct fcb_disk_area *fdap)
+{
+    struct fcb_disk_area fda;
+    int rc;
+
+    if (!fdap) {
+        fdap = &fda;
+    }
+    rc = flash_area_read(fap, 0, fdap, sizeof(*fdap));
+    if (rc) {
+        return FCB_ERR_FLASH;
+    }
+    if (fdap->fd_magic == 0xffffffff) {
+        return 0;
+    }
+    if (fdap->fd_magic != fcb->f_magic) {
+        return FCB_ERR_MAGIC;
+    }
+    return 1;
+}
+
+/**
+ * Finds n-th element offset
+ * @param0 ptr to fcb
+ * @param1 n number of entries to calculate offset before
+ * @param2 ptr to the offset before to be returned
+ * @return 0 on success; non-zero on failure
+ */
+int
+fcb_offset_last_n(struct fcb *fcb, uint8_t entries, uint32_t *last_n_off)
+{
+    struct fcb_entry loc;
+    struct fcb_entry start;
+    int i;
+
+    i = 0;
+    memset(&loc, 0, sizeof(loc));
+    while (!fcb_getnext(fcb, &loc)) {
+        if (i == 0) {
+            /* Start from the beginning of fcb entries */
+            *last_n_off = loc.fe_elem_off;
+            start = loc;
+        }
+        /* Update last_n_off after n entries and keep updating */
+        if (i >= (entries - 1)) {
+            fcb_getnext(fcb, &start);
+            *last_n_off = start.fe_elem_off;
+        }
+        i++;
+    }
+
+    return 0;
+}
+
+/**
+ * Clear fcb
+ * @param fcb
+ * @return 0 on success; non-zero on failure
+ */
+int
+fcb_clear(struct fcb *fcb)
+{
+    int rc;
+
+    rc = 0;
+    while (!fcb_is_empty(fcb)) {
+        rc = fcb_rotate(fcb);
+        if (rc) {
+            break;
+        }
+    }
+    return rc;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/fs/fcb/src/fcb_append.c
----------------------------------------------------------------------
diff --git a/fs/fcb/src/fcb_append.c b/fs/fcb/src/fcb_append.c
new file mode 100644
index 0000000..c7f5ddc
--- /dev/null
+++ b/fs/fcb/src/fcb_append.c
@@ -0,0 +1,143 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+#include <stddef.h>
+
+#include "fcb/fcb.h"
+#include "fcb_priv.h"
+
+static struct flash_area *
+fcb_new_area(struct fcb *fcb, int cnt)
+{
+    struct flash_area *fa;
+    struct flash_area *rfa;
+    int i;
+
+    rfa = NULL;
+    i = 0;
+    fa = fcb->f_active.fe_area;
+    do {
+        fa = fcb_getnext_area(fcb, fa);
+        if (!rfa) {
+            rfa = fa;
+        }
+        if (fa == fcb->f_oldest) {
+            return NULL;
+        }
+    } while (i++ < cnt);
+    return rfa;
+}
+
+/*
+ * Take one of the scratch blocks into use, if at all possible.
+ */
+int
+fcb_append_to_scratch(struct fcb *fcb)
+{
+    struct flash_area *fa;
+    int rc;
+
+    fa = fcb_new_area(fcb, 0);
+    if (!fa) {
+        return FCB_ERR_NOSPACE;
+    }
+    rc = fcb_sector_hdr_init(fcb, fa, fcb->f_active_id + 1);
+    if (rc) {
+        return rc;
+    }
+    fcb->f_active.fe_area = fa;
+    fcb->f_active.fe_elem_off = sizeof(struct fcb_disk_area);
+    fcb->f_active_id++;
+    return FCB_OK;
+}
+
+int
+fcb_append(struct fcb *fcb, uint16_t len, struct fcb_entry *append_loc)
+{
+    struct fcb_entry *active;
+    struct flash_area *fa;
+    uint8_t tmp_str[2];
+    int cnt;
+    int rc;
+
+    cnt = fcb_put_len(tmp_str, len);
+    if (cnt < 0) {
+        return cnt;
+    }
+    cnt = fcb_len_in_flash(fcb, cnt);
+    len = fcb_len_in_flash(fcb, len) + fcb_len_in_flash(fcb, FCB_CRC_SZ);
+
+    rc = os_mutex_pend(&fcb->f_mtx, OS_WAIT_FOREVER);
+    if (rc && rc != OS_NOT_STARTED) {
+        return FCB_ERR_ARGS;
+    }
+    active = &fcb->f_active;
+    if (active->fe_elem_off + len + cnt > active->fe_area->fa_size) {
+        fa = fcb_new_area(fcb, fcb->f_scratch_cnt);
+        if (!fa || (fa->fa_size <
+            sizeof(struct fcb_disk_area) + len + cnt)) {
+            rc = FCB_ERR_NOSPACE;
+            goto err;
+        }
+        rc = fcb_sector_hdr_init(fcb, fa, fcb->f_active_id + 1);
+        if (rc) {
+            goto err;
+        }
+        fcb->f_active.fe_area = fa;
+        fcb->f_active.fe_elem_off = sizeof(struct fcb_disk_area);
+        fcb->f_active_id++;
+    }
+
+    rc = flash_area_write(active->fe_area, active->fe_elem_off, tmp_str, cnt);
+    if (rc) {
+        rc = FCB_ERR_FLASH;
+        goto err;
+    }
+    append_loc->fe_area = active->fe_area;
+    append_loc->fe_elem_off = active->fe_elem_off;
+    append_loc->fe_data_off = active->fe_elem_off + cnt;
+
+    active->fe_elem_off = append_loc->fe_data_off + len;
+
+    os_mutex_release(&fcb->f_mtx);
+
+    return FCB_OK;
+err:
+    os_mutex_release(&fcb->f_mtx);
+    return rc;
+}
+
+int
+fcb_append_finish(struct fcb *fcb, struct fcb_entry *loc)
+{
+    int rc;
+    uint8_t crc8;
+    uint32_t off;
+
+    rc = fcb_elem_crc8(fcb, loc, &crc8);
+    if (rc) {
+        return rc;
+    }
+    off = loc->fe_data_off + fcb_len_in_flash(fcb, loc->fe_data_len);
+
+    rc = flash_area_write(loc->fe_area, off, &crc8, sizeof(crc8));
+    if (rc) {
+        return FCB_ERR_FLASH;
+    }
+    return 0;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/fs/fcb/src/fcb_elem_info.c
----------------------------------------------------------------------
diff --git a/fs/fcb/src/fcb_elem_info.c b/fs/fcb/src/fcb_elem_info.c
new file mode 100644
index 0000000..7e088ea
--- /dev/null
+++ b/fs/fcb/src/fcb_elem_info.c
@@ -0,0 +1,101 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include <crc/crc8.h>
+
+#include "fcb/fcb.h"
+#include "fcb_priv.h"
+
+/*
+ * Given offset in flash area, fill in rest of the fcb_entry, and crc8 over
+ * the data.
+ */
+int
+fcb_elem_crc8(struct fcb *fcb, struct fcb_entry *loc, uint8_t *c8p)
+{
+    uint8_t tmp_str[FCB_TMP_BUF_SZ];
+    int cnt;
+    int blk_sz;
+    uint8_t crc8;
+    uint16_t len;
+    uint32_t off;
+    uint32_t end;
+    int rc;
+
+    if (loc->fe_elem_off + 2 > loc->fe_area->fa_size) {
+        return FCB_ERR_NOVAR;
+    }
+    rc = flash_area_read(loc->fe_area, loc->fe_elem_off, tmp_str, 2);
+    if (rc) {
+        return FCB_ERR_FLASH;
+    }
+
+    cnt = fcb_get_len(tmp_str, &len);
+    if (cnt < 0) {
+        return cnt;
+    }
+    loc->fe_data_off = loc->fe_elem_off + fcb_len_in_flash(fcb, cnt);
+    loc->fe_data_len = len;
+
+    crc8 = crc8_init();
+    crc8 = crc8_calc(crc8, tmp_str, cnt);
+
+    off = loc->fe_data_off;
+    end = loc->fe_data_off + len;
+    for (; off < end; off += blk_sz) {
+        blk_sz = end - off;
+        if (blk_sz > sizeof(tmp_str)) {
+            blk_sz = sizeof(tmp_str);
+        }
+
+        rc = flash_area_read(loc->fe_area, off, tmp_str, blk_sz);
+        if (rc) {
+            return FCB_ERR_FLASH;
+        }
+        crc8 = crc8_calc(crc8, tmp_str, blk_sz);
+    }
+    *c8p = crc8;
+
+    return 0;
+}
+
+int
+fcb_elem_info(struct fcb *fcb, struct fcb_entry *loc)
+{
+    int rc;
+    uint8_t crc8;
+    uint8_t fl_crc8;
+    uint32_t off;
+
+    rc = fcb_elem_crc8(fcb, loc, &crc8);
+    if (rc) {
+        return rc;
+    }
+    off = loc->fe_data_off + fcb_len_in_flash(fcb, loc->fe_data_len);
+
+    rc = flash_area_read(loc->fe_area, off, &fl_crc8, sizeof(fl_crc8));
+    if (rc) {
+        return FCB_ERR_FLASH;
+    }
+
+    if (fl_crc8 != crc8) {
+        return FCB_ERR_CRC;
+    }
+    return 0;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/fs/fcb/src/fcb_getnext.c
----------------------------------------------------------------------
diff --git a/fs/fcb/src/fcb_getnext.c b/fs/fcb/src/fcb_getnext.c
new file mode 100644
index 0000000..be92979
--- /dev/null
+++ b/fs/fcb/src/fcb_getnext.c
@@ -0,0 +1,132 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+#include <stddef.h>
+
+#include "fcb/fcb.h"
+#include "fcb_priv.h"
+
+int
+fcb_getnext_in_area(struct fcb *fcb, struct fcb_entry *loc)
+{
+    int rc;
+
+    rc = fcb_elem_info(fcb, loc);
+    if (rc == 0 || rc == FCB_ERR_CRC) {
+        do {
+            loc->fe_elem_off = loc->fe_data_off +
+              fcb_len_in_flash(fcb, loc->fe_data_len) +
+              fcb_len_in_flash(fcb, FCB_CRC_SZ);
+            rc = fcb_elem_info(fcb, loc);
+            if (rc != FCB_ERR_CRC) {
+                break;
+            }
+        } while (rc == FCB_ERR_CRC);
+    }
+    return rc;
+}
+
+struct flash_area *
+fcb_getnext_area(struct fcb *fcb, struct flash_area *fap)
+{
+    fap++;
+    if (fap >= &fcb->f_sectors[fcb->f_sector_cnt]) {
+        fap = &fcb->f_sectors[0];
+    }
+    return fap;
+}
+
+int
+fcb_getnext_nolock(struct fcb *fcb, struct fcb_entry *loc)
+{
+    int rc;
+
+    if (loc->fe_area == NULL) {
+        /*
+         * Find the first one we have in flash.
+         */
+        loc->fe_area = fcb->f_oldest;
+    }
+    if (loc->fe_elem_off == 0) {
+        /*
+         * If offset is zero, we serve the first entry from the area.
+         */
+        loc->fe_elem_off = sizeof(struct fcb_disk_area);
+        rc = fcb_elem_info(fcb, loc);
+        switch (rc) {
+        case 0:
+            return 0;
+        case FCB_ERR_CRC:
+            break;
+        default:
+            goto next_sector;
+        }
+    } else {
+        rc = fcb_getnext_in_area(fcb, loc);
+        if (rc == 0) {
+            return 0;
+        }
+        if (rc == FCB_ERR_NOVAR) {
+            goto next_sector;
+        }
+    }
+    while (rc == FCB_ERR_CRC) {
+        rc = fcb_getnext_in_area(fcb, loc);
+        if (rc == 0) {
+            return 0;
+        }
+
+        if (rc != FCB_ERR_CRC) {
+            /*
+             * Moving to next sector.
+             */
+next_sector:
+            if (loc->fe_area == fcb->f_active.fe_area) {
+                return FCB_ERR_NOVAR;
+            }
+            loc->fe_area = fcb_getnext_area(fcb, loc->fe_area);
+            loc->fe_elem_off = sizeof(struct fcb_disk_area);
+            rc = fcb_elem_info(fcb, loc);
+            switch (rc) {
+            case 0:
+                return 0;
+            case FCB_ERR_CRC:
+                break;
+            default:
+                goto next_sector;
+            }
+        }
+    }
+
+    return 0;
+}
+
+int
+fcb_getnext(struct fcb *fcb, struct fcb_entry *loc)
+{
+    int rc;
+
+    rc = os_mutex_pend(&fcb->f_mtx, OS_WAIT_FOREVER);
+    if (rc && rc != OS_NOT_STARTED) {
+        return FCB_ERR_ARGS;
+    }
+    rc = fcb_getnext_nolock(fcb, loc);
+    os_mutex_release(&fcb->f_mtx);
+
+    return rc;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/fs/fcb/src/fcb_priv.h
----------------------------------------------------------------------
diff --git a/fs/fcb/src/fcb_priv.h b/fs/fcb/src/fcb_priv.h
new file mode 100644
index 0000000..b7a9e0b
--- /dev/null
+++ b/fs/fcb/src/fcb_priv.h
@@ -0,0 +1,57 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 __SYS_FCB_PRIV_H_
+#define __SYS_FCB_PRIV_H_
+
+#define FCB_CRC_SZ	sizeof(uint8_t)
+#define FCB_TMP_BUF_SZ	32
+
+#define FCB_ID_GT(a, b) (((int16_t)(a) - (int16_t)(b)) > 0)
+
+struct fcb_disk_area {
+    uint32_t fd_magic;
+    uint8_t  fd_ver;
+    uint8_t  _pad;
+    uint16_t fd_id;
+};
+
+int fcb_put_len(uint8_t *buf, uint16_t len);
+int fcb_get_len(uint8_t *buf, uint16_t *len);
+
+static inline int
+fcb_len_in_flash(struct fcb *fcb, uint16_t len)
+{
+    if (fcb->f_align <= 1) {
+        return len;
+    }
+    return (len + (fcb->f_align - 1)) & ~(fcb->f_align - 1);
+}
+
+int fcb_getnext_in_area(struct fcb *fcb, struct fcb_entry *loc);
+struct flash_area *fcb_getnext_area(struct fcb *fcb, struct flash_area *fap);
+int fcb_getnext_nolock(struct fcb *fcb, struct fcb_entry *loc);
+
+int fcb_elem_info(struct fcb *, struct fcb_entry *);
+int fcb_elem_crc8(struct fcb *, struct fcb_entry *loc, uint8_t *crc8p);
+
+int fcb_sector_hdr_init(struct fcb *, struct flash_area *fap, uint16_t id);
+int fcb_sector_hdr_read(struct fcb *, struct flash_area *fap,
+  struct fcb_disk_area *fdap);
+
+#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/fs/fcb/src/fcb_rotate.c
----------------------------------------------------------------------
diff --git a/fs/fcb/src/fcb_rotate.c b/fs/fcb/src/fcb_rotate.c
new file mode 100644
index 0000000..7b6df58
--- /dev/null
+++ b/fs/fcb/src/fcb_rotate.c
@@ -0,0 +1,56 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include "fcb/fcb.h"
+#include "fcb_priv.h"
+
+int
+fcb_rotate(struct fcb *fcb)
+{
+    struct flash_area *fap;
+    int rc = 0;
+
+    rc = os_mutex_pend(&fcb->f_mtx, OS_WAIT_FOREVER);
+    if (rc && rc != OS_NOT_STARTED) {
+        return FCB_ERR_ARGS;
+    }
+
+    rc = flash_area_erase(fcb->f_oldest, 0, fcb->f_oldest->fa_size);
+    if (rc) {
+        rc = FCB_ERR_FLASH;
+        goto out;
+    }
+    if (fcb->f_oldest == fcb->f_active.fe_area) {
+        /*
+         * Need to create a new active area, as we're wiping the current.
+         */
+        fap = fcb_getnext_area(fcb, fcb->f_oldest);
+        rc = fcb_sector_hdr_init(fcb, fap, fcb->f_active_id + 1);
+        if (rc) {
+            goto out;
+        }
+        fcb->f_active.fe_area = fap;
+        fcb->f_active.fe_elem_off = sizeof(struct fcb_disk_area);
+        fcb->f_active_id++;
+    }
+    fcb->f_oldest = fcb_getnext_area(fcb, fcb->f_oldest);
+out:
+    os_mutex_release(&fcb->f_mtx);
+    return rc;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/fs/fcb/src/fcb_walk.c
----------------------------------------------------------------------
diff --git a/fs/fcb/src/fcb_walk.c b/fs/fcb/src/fcb_walk.c
new file mode 100644
index 0000000..e557262
--- /dev/null
+++ b/fs/fcb/src/fcb_walk.c
@@ -0,0 +1,53 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include "fcb/fcb.h"
+#include "fcb_priv.h"
+
+/*
+ * Call 'cb' for every element in flash circular buffer. If fap is specified,
+ * only elements with that flash_area are reported.
+ */
+int
+fcb_walk(struct fcb *fcb, struct flash_area *fap, fcb_walk_cb cb, void *cb_arg)
+{
+    struct fcb_entry loc;
+    int rc;
+
+    loc.fe_area = fap;
+    loc.fe_elem_off = 0;
+
+    rc = os_mutex_pend(&fcb->f_mtx, OS_WAIT_FOREVER);
+    if (rc && rc != OS_NOT_STARTED) {
+        return FCB_ERR_ARGS;
+    }
+    while ((rc = fcb_getnext_nolock(fcb, &loc)) != FCB_ERR_NOVAR) {
+        os_mutex_release(&fcb->f_mtx);
+        if (fap && loc.fe_area != fap) {
+            return 0;
+        }
+        rc = cb(&loc, cb_arg);
+        if (rc) {
+            return rc;
+        }
+        os_mutex_pend(&fcb->f_mtx, OS_WAIT_FOREVER);
+    }
+    os_mutex_release(&fcb->f_mtx);
+    return 0;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/fs/fcb/test/pkg.yml
----------------------------------------------------------------------
diff --git a/fs/fcb/test/pkg.yml b/fs/fcb/test/pkg.yml
new file mode 100644
index 0000000..920cfa3
--- /dev/null
+++ b/fs/fcb/test/pkg.yml
@@ -0,0 +1,30 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+#
+pkg.name: fs/fcb/test
+pkg.type: unittest
+pkg.description: "FCB unit tests."
+pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
+pkg.homepage: "http://mynewt.apache.org/"
+pkg.keywords:
+
+pkg.deps: 
+    - test/testutil
+    - fs/fcb
+
+pkg.deps.SELFTEST:
+    - sys/console/stub

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/fs/fcb/test/src/fcb_test.c
----------------------------------------------------------------------
diff --git a/fs/fcb/test/src/fcb_test.c b/fs/fcb/test/src/fcb_test.c
new file mode 100644
index 0000000..b172eb0
--- /dev/null
+++ b/fs/fcb/test/src/fcb_test.c
@@ -0,0 +1,672 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include <stdio.h>
+#include <string.h>
+
+#include "syscfg/syscfg.h"
+#include "os/os.h"
+#include "testutil/testutil.h"
+
+#include "fcb/fcb.h"
+#include "fcb/../../src/fcb_priv.h"
+
+static struct fcb test_fcb;
+
+static struct flash_area test_fcb_area[] = {
+    [0] = {
+        .fa_flash_id = 0,
+        .fa_off = 0,
+        .fa_size = 0x4000, /* 16K */
+    },
+    [1] = {
+        .fa_flash_id = 0,
+        .fa_off = 0x4000,
+        .fa_size = 0x4000
+    },
+    [2] = {
+        .fa_flash_id = 0,
+        .fa_off = 0x8000,
+        .fa_size = 0x4000
+    },
+    [3] = {
+        .fa_flash_id = 0,
+        .fa_off = 0xc000,
+        .fa_size = 0x4000
+    }
+};
+
+static void
+fcb_test_wipe(void)
+{
+    int i;
+    int rc;
+    struct flash_area *fap;
+
+    for (i = 0; i < sizeof(test_fcb_area) / sizeof(test_fcb_area[0]); i++) {
+        fap = &test_fcb_area[i];
+        rc = flash_area_erase(fap, 0, fap->fa_size);
+        TEST_ASSERT(rc == 0);
+    }
+}
+
+TEST_CASE(fcb_test_len)
+{
+    uint8_t buf[3];
+    uint16_t len;
+    uint16_t len2;
+    int rc;
+
+    for (len = 0; len < FCB_MAX_LEN; len++) {
+        rc = fcb_put_len(buf, len);
+        TEST_ASSERT(rc == 1 || rc == 2);
+
+        rc = fcb_get_len(buf, &len2);
+        TEST_ASSERT(rc == 1 || rc == 2);
+
+        TEST_ASSERT(len == len2);
+    }
+}
+
+TEST_CASE(fcb_test_init)
+{
+    int rc;
+    struct fcb *fcb;
+
+    fcb = &test_fcb;
+    memset(fcb, 0, sizeof(*fcb));
+
+    rc = fcb_init(fcb);
+    TEST_ASSERT(rc == FCB_ERR_ARGS);
+
+    fcb->f_sectors = test_fcb_area;
+
+    rc = fcb_init(fcb);
+    TEST_ASSERT(rc == FCB_ERR_ARGS);
+
+    fcb->f_sector_cnt = 2;
+    rc = fcb_init(fcb);
+    TEST_ASSERT(rc == 0);
+}
+
+static int
+fcb_test_empty_walk_cb(struct fcb_entry *loc, void *arg)
+{
+    TEST_ASSERT(0);
+    return 0;
+}
+
+TEST_CASE(fcb_test_empty_walk)
+{
+    int rc;
+    struct fcb *fcb;
+
+    fcb_test_wipe();
+    fcb = &test_fcb;
+    memset(fcb, 0, sizeof(*fcb));
+
+    fcb->f_sector_cnt = 2;
+    fcb->f_sectors = test_fcb_area;
+
+    rc = fcb_init(fcb);
+    TEST_ASSERT(rc == 0);
+
+    rc = fcb_walk(fcb, 0, fcb_test_empty_walk_cb, NULL);
+    TEST_ASSERT(rc == 0);
+}
+
+static uint8_t
+fcb_test_append_data(int msg_len, int off)
+{
+    return (msg_len ^ off);
+}
+
+static int
+fcb_test_data_walk_cb(struct fcb_entry *loc, void *arg)
+{
+    uint16_t len;
+    uint8_t test_data[128];
+    int rc;
+    int i;
+    int *var_cnt = (int *)arg;
+
+    len = loc->fe_data_len;
+
+    TEST_ASSERT(len == *var_cnt);
+
+    rc = flash_area_read(loc->fe_area, loc->fe_data_off, test_data, len);
+    TEST_ASSERT(rc == 0);
+
+    for (i = 0; i < len; i++) {
+        TEST_ASSERT(test_data[i] == fcb_test_append_data(len, i));
+    }
+    (*var_cnt)++;
+    return 0;
+}
+
+TEST_CASE(fcb_test_append)
+{
+    int rc;
+    struct fcb *fcb;
+    struct fcb_entry loc;
+    uint8_t test_data[128];
+    int i;
+    int j;
+    int var_cnt;
+
+    fcb_test_wipe();
+    fcb = &test_fcb;
+    memset(fcb, 0, sizeof(*fcb));
+    fcb->f_sector_cnt = 2;
+    fcb->f_sectors = test_fcb_area;
+
+    rc = fcb_init(fcb);
+    TEST_ASSERT(rc == 0);
+
+    for (i = 0; i < sizeof(test_data); i++) {
+        for (j = 0; j < i; j++) {
+            test_data[j] = fcb_test_append_data(i, j);
+        }
+        rc = fcb_append(fcb, i, &loc);
+        TEST_ASSERT_FATAL(rc == 0);
+        rc = flash_area_write(loc.fe_area, loc.fe_data_off, test_data, i);
+        TEST_ASSERT(rc == 0);
+        rc = fcb_append_finish(fcb, &loc);
+        TEST_ASSERT(rc == 0);
+    }
+
+    var_cnt = 0;
+    rc = fcb_walk(fcb, 0, fcb_test_data_walk_cb, &var_cnt);
+    TEST_ASSERT(rc == 0);
+    TEST_ASSERT(var_cnt == sizeof(test_data));
+}
+
+TEST_CASE(fcb_test_append_too_big)
+{
+    struct fcb *fcb;
+    int rc;
+    int len;
+    struct fcb_entry elem_loc;
+
+    fcb_test_wipe();
+    fcb = &test_fcb;
+    memset(fcb, 0, sizeof(*fcb));
+    fcb->f_sector_cnt = 2;
+    fcb->f_sectors = test_fcb_area;
+
+    rc = fcb_init(fcb);
+    TEST_ASSERT(rc == 0);
+
+    /*
+     * Max element which fits inside sector is
+     * sector size - (disk header + crc + 1-2 bytes of length).
+     */
+    len = fcb->f_active.fe_area->fa_size;
+
+    rc = fcb_append(fcb, len, &elem_loc);
+    TEST_ASSERT(rc != 0);
+
+    len--;
+    rc = fcb_append(fcb, len, &elem_loc);
+    TEST_ASSERT(rc != 0);
+
+    len -= sizeof(struct fcb_disk_area);
+    rc = fcb_append(fcb, len, &elem_loc);
+    TEST_ASSERT(rc != 0);
+
+    len = fcb->f_active.fe_area->fa_size -
+      (sizeof(struct fcb_disk_area) + 1 + 2);
+    rc = fcb_append(fcb, len, &elem_loc);
+    TEST_ASSERT(rc == 0);
+
+    rc = fcb_append_finish(fcb, &elem_loc);
+    TEST_ASSERT(rc == 0);
+
+    rc = fcb_elem_info(fcb, &elem_loc);
+    TEST_ASSERT(rc == 0);
+    TEST_ASSERT(elem_loc.fe_data_len == len);
+}
+
+struct append_arg {
+    int *elem_cnts;
+};
+
+static int
+fcb_test_cnt_elems_cb(struct fcb_entry *loc, void *arg)
+{
+    struct append_arg *aa = (struct append_arg *)arg;
+    int idx;
+
+    idx = loc->fe_area - &test_fcb_area[0];
+    aa->elem_cnts[idx]++;
+    return 0;
+}
+
+TEST_CASE(fcb_test_append_fill)
+{
+    struct fcb *fcb;
+    int rc;
+    int i;
+    struct fcb_entry loc;
+    uint8_t test_data[128];
+    int elem_cnts[2] = {0, 0};
+    int aa_together_cnts[2];
+    struct append_arg aa_together = {
+        .elem_cnts = aa_together_cnts
+    };
+    int aa_separate_cnts[2];
+    struct append_arg aa_separate = {
+        .elem_cnts = aa_separate_cnts
+    };
+
+    fcb_test_wipe();
+    fcb = &test_fcb;
+    memset(fcb, 0, sizeof(*fcb));
+    fcb->f_sector_cnt = 2;
+    fcb->f_sectors = test_fcb_area;
+
+    rc = fcb_init(fcb);
+    TEST_ASSERT(rc == 0);
+
+    for (i = 0; i < sizeof(test_data); i++) {
+        test_data[i] = fcb_test_append_data(sizeof(test_data), i);
+    }
+
+    while (1) {
+        rc = fcb_append(fcb, sizeof(test_data), &loc);
+        if (rc == FCB_ERR_NOSPACE) {
+            break;
+        }
+        if (loc.fe_area == &test_fcb_area[0]) {
+            elem_cnts[0]++;
+        } else if (loc.fe_area == &test_fcb_area[1]) {
+            elem_cnts[1]++;
+        } else {
+            TEST_ASSERT(0);
+        }
+
+        rc = flash_area_write(loc.fe_area, loc.fe_data_off, test_data,
+          sizeof(test_data));
+        TEST_ASSERT(rc == 0);
+
+        rc = fcb_append_finish(fcb, &loc);
+        TEST_ASSERT(rc == 0);
+    }
+    TEST_ASSERT(elem_cnts[0] > 0);
+    TEST_ASSERT(elem_cnts[0] == elem_cnts[1]);
+
+    memset(&aa_together_cnts, 0, sizeof(aa_together_cnts));
+    rc = fcb_walk(fcb, NULL, fcb_test_cnt_elems_cb, &aa_together);
+    TEST_ASSERT(rc == 0);
+    TEST_ASSERT(aa_together.elem_cnts[0] == elem_cnts[0]);
+    TEST_ASSERT(aa_together.elem_cnts[1] == elem_cnts[1]);
+
+    memset(&aa_separate_cnts, 0, sizeof(aa_separate_cnts));
+    rc = fcb_walk(fcb, &test_fcb_area[0], fcb_test_cnt_elems_cb,
+      &aa_separate);
+    TEST_ASSERT(rc == 0);
+    rc = fcb_walk(fcb, &test_fcb_area[1], fcb_test_cnt_elems_cb,
+      &aa_separate);
+    TEST_ASSERT(rc == 0);
+    TEST_ASSERT(aa_separate.elem_cnts[0] == elem_cnts[0]);
+    TEST_ASSERT(aa_separate.elem_cnts[1] == elem_cnts[1]);
+
+}
+
+TEST_CASE(fcb_test_reset)
+{
+    struct fcb *fcb;
+    int rc;
+    int i;
+    struct fcb_entry loc;
+    uint8_t test_data[128];
+    int var_cnt;
+
+    fcb_test_wipe();
+    fcb = &test_fcb;
+    memset(fcb, 0, sizeof(*fcb));
+    fcb->f_sector_cnt = 2;
+    fcb->f_sectors = test_fcb_area;
+
+    rc = fcb_init(fcb);
+    TEST_ASSERT(rc == 0);
+
+    var_cnt = 0;
+    rc = fcb_walk(fcb, 0, fcb_test_data_walk_cb, &var_cnt);
+    TEST_ASSERT(rc == 0);
+    TEST_ASSERT(var_cnt == 0);
+
+    rc = fcb_append(fcb, 32, &loc);
+    TEST_ASSERT(rc == 0);
+
+    /*
+     * No ready ones yet. CRC should not match.
+     */
+    var_cnt = 0;
+    rc = fcb_walk(fcb, 0, fcb_test_data_walk_cb, &var_cnt);
+    TEST_ASSERT(rc == 0);
+    TEST_ASSERT(var_cnt == 0);
+
+    for (i = 0; i < sizeof(test_data); i++) {
+        test_data[i] = fcb_test_append_data(32, i);
+    }
+    rc = flash_area_write(loc.fe_area, loc.fe_data_off, test_data, 32);
+    TEST_ASSERT(rc == 0);
+
+    rc = fcb_append_finish(fcb, &loc);
+    TEST_ASSERT(rc == 0);
+
+    /*
+     * one entry
+     */
+    var_cnt = 32;
+    rc = fcb_walk(fcb, 0, fcb_test_data_walk_cb, &var_cnt);
+    TEST_ASSERT(rc == 0);
+    TEST_ASSERT(var_cnt == 33);
+
+    /*
+     * Pretend reset
+     */
+    memset(fcb, 0, sizeof(*fcb));
+    fcb->f_sector_cnt = 2;
+    fcb->f_sectors = test_fcb_area;
+
+    rc = fcb_init(fcb);
+    TEST_ASSERT(rc == 0);
+
+    var_cnt = 32;
+    rc = fcb_walk(fcb, 0, fcb_test_data_walk_cb, &var_cnt);
+    TEST_ASSERT(rc == 0);
+    TEST_ASSERT(var_cnt == 33);
+
+    rc = fcb_append(fcb, 33, &loc);
+    TEST_ASSERT(rc == 0);
+
+    for (i = 0; i < sizeof(test_data); i++) {
+        test_data[i] = fcb_test_append_data(33, i);
+    }
+    rc = flash_area_write(loc.fe_area, loc.fe_data_off, test_data, 33);
+    TEST_ASSERT(rc == 0);
+
+    rc = fcb_append_finish(fcb, &loc);
+    TEST_ASSERT(rc == 0);
+
+    var_cnt = 32;
+    rc = fcb_walk(fcb, 0, fcb_test_data_walk_cb, &var_cnt);
+    TEST_ASSERT(rc == 0);
+    TEST_ASSERT(var_cnt == 34);
+
+    /*
+     * Add partial one, make sure that we survive reset then.
+     */
+    rc = fcb_append(fcb, 34, &loc);
+    TEST_ASSERT(rc == 0);
+
+    memset(fcb, 0, sizeof(*fcb));
+    fcb->f_sector_cnt = 2;
+    fcb->f_sectors = test_fcb_area;
+
+    rc = fcb_init(fcb);
+    TEST_ASSERT(rc == 0);
+
+    /*
+     * Walk should skip that.
+     */
+    var_cnt = 32;
+    rc = fcb_walk(fcb, 0, fcb_test_data_walk_cb, &var_cnt);
+    TEST_ASSERT(rc == 0);
+    TEST_ASSERT(var_cnt == 34);
+
+    /* Add a 3rd one, should go behind corrupt entry */
+    rc = fcb_append(fcb, 34, &loc);
+    TEST_ASSERT(rc == 0);
+
+    for (i = 0; i < sizeof(test_data); i++) {
+        test_data[i] = fcb_test_append_data(34, i);
+    }
+    rc = flash_area_write(loc.fe_area, loc.fe_data_off, test_data, 34);
+    TEST_ASSERT(rc == 0);
+
+    rc = fcb_append_finish(fcb, &loc);
+    TEST_ASSERT(rc == 0);
+
+    /*
+     * Walk should skip corrupt entry, but report the next one.
+     */
+    var_cnt = 32;
+    rc = fcb_walk(fcb, 0, fcb_test_data_walk_cb, &var_cnt);
+    TEST_ASSERT(rc == 0);
+    TEST_ASSERT(var_cnt == 35);
+}
+
+TEST_CASE(fcb_test_rotate)
+{
+    struct fcb *fcb;
+    int rc;
+    int old_id;
+    struct fcb_entry loc;
+    uint8_t test_data[128];
+    int elem_cnts[2] = {0, 0};
+    int cnts[2];
+    struct append_arg aa_arg = {
+        .elem_cnts = cnts
+    };
+
+    fcb_test_wipe();
+    fcb = &test_fcb;
+    memset(fcb, 0, sizeof(*fcb));
+    fcb->f_sector_cnt = 2;
+    fcb->f_sectors = test_fcb_area;
+
+    rc = fcb_init(fcb);
+    TEST_ASSERT(rc == 0);
+
+    old_id = fcb->f_active_id;
+    rc = fcb_rotate(fcb);
+    TEST_ASSERT(rc == 0);
+    TEST_ASSERT(fcb->f_active_id == old_id + 1);
+
+    /*
+     * Now fill up the
+     */
+    while (1) {
+        rc = fcb_append(fcb, sizeof(test_data), &loc);
+        if (rc == FCB_ERR_NOSPACE) {
+            break;
+        }
+        if (loc.fe_area == &test_fcb_area[0]) {
+            elem_cnts[0]++;
+        } else if (loc.fe_area == &test_fcb_area[1]) {
+            elem_cnts[1]++;
+        } else {
+            TEST_ASSERT(0);
+        }
+
+        rc = flash_area_write(loc.fe_area, loc.fe_data_off, test_data,
+          sizeof(test_data));
+        TEST_ASSERT(rc == 0);
+
+        rc = fcb_append_finish(fcb, &loc);
+        TEST_ASSERT(rc == 0);
+    }
+    TEST_ASSERT(elem_cnts[0] > 0 && elem_cnts[0] == elem_cnts[1]);
+
+    old_id = fcb->f_active_id;
+    rc = fcb_rotate(fcb);
+    TEST_ASSERT(rc == 0);
+    TEST_ASSERT(fcb->f_active_id == old_id); /* no new area created */
+
+    memset(cnts, 0, sizeof(cnts));
+    rc = fcb_walk(fcb, NULL, fcb_test_cnt_elems_cb, &aa_arg);
+    TEST_ASSERT(rc == 0);
+    TEST_ASSERT(aa_arg.elem_cnts[0] == elem_cnts[0] ||
+      aa_arg.elem_cnts[1] == elem_cnts[1]);
+    TEST_ASSERT(aa_arg.elem_cnts[0] == 0 || aa_arg.elem_cnts[1] == 0);
+
+    /*
+     * One sector is full. The other one should have one entry in it.
+     */
+    rc = fcb_append(fcb, sizeof(test_data), &loc);
+    TEST_ASSERT(rc == 0);
+
+    rc = flash_area_write(loc.fe_area, loc.fe_data_off, test_data,
+      sizeof(test_data));
+    TEST_ASSERT(rc == 0);
+
+    rc = fcb_append_finish(fcb, &loc);
+    TEST_ASSERT(rc == 0);
+
+    old_id = fcb->f_active_id;
+    rc = fcb_rotate(fcb);
+    TEST_ASSERT(rc == 0);
+    TEST_ASSERT(fcb->f_active_id == old_id);
+
+    memset(cnts, 0, sizeof(cnts));
+    rc = fcb_walk(fcb, NULL, fcb_test_cnt_elems_cb, &aa_arg);
+    TEST_ASSERT(rc == 0);
+    TEST_ASSERT(aa_arg.elem_cnts[0] == 1 || aa_arg.elem_cnts[1] == 1);
+    TEST_ASSERT(aa_arg.elem_cnts[0] == 0 || aa_arg.elem_cnts[1] == 0);
+}
+
+TEST_CASE(fcb_test_multiple_scratch)
+{
+    struct fcb *fcb;
+    int rc;
+    struct fcb_entry loc;
+    uint8_t test_data[128];
+    int elem_cnts[4];
+    int idx;
+    int cnts[4];
+    struct append_arg aa_arg = {
+        .elem_cnts = cnts
+    };
+
+    fcb_test_wipe();
+    fcb = &test_fcb;
+    memset(fcb, 0, sizeof(*fcb));
+    fcb->f_sector_cnt = 4;
+    fcb->f_scratch_cnt = 1;
+    fcb->f_sectors = test_fcb_area;
+
+    rc = fcb_init(fcb);
+    TEST_ASSERT(rc == 0);
+
+    /*
+     * Now fill up everything. We should be able to get 3 of the sectors
+     * full.
+     */
+    memset(elem_cnts, 0, sizeof(elem_cnts));
+    while (1) {
+        rc = fcb_append(fcb, sizeof(test_data), &loc);
+        if (rc == FCB_ERR_NOSPACE) {
+            break;
+        }
+        idx = loc.fe_area - &test_fcb_area[0];
+        elem_cnts[idx]++;
+
+        rc = flash_area_write(loc.fe_area, loc.fe_data_off, test_data,
+          sizeof(test_data));
+        TEST_ASSERT(rc == 0);
+
+        rc = fcb_append_finish(fcb, &loc);
+        TEST_ASSERT(rc == 0);
+    }
+
+    TEST_ASSERT(elem_cnts[0] > 0);
+    TEST_ASSERT(elem_cnts[0] == elem_cnts[1] && elem_cnts[0] == elem_cnts[2]);
+    TEST_ASSERT(elem_cnts[3] == 0);
+
+    /*
+     * Ask to use scratch block, then fill it up.
+     */
+    rc = fcb_append_to_scratch(fcb);
+    TEST_ASSERT(rc == 0);
+
+    while (1) {
+        rc = fcb_append(fcb, sizeof(test_data), &loc);
+        if (rc == FCB_ERR_NOSPACE) {
+            break;
+        }
+        idx = loc.fe_area - &test_fcb_area[0];
+        elem_cnts[idx]++;
+
+        rc = flash_area_write(loc.fe_area, loc.fe_data_off, test_data,
+          sizeof(test_data));
+        TEST_ASSERT(rc == 0);
+
+        rc = fcb_append_finish(fcb, &loc);
+        TEST_ASSERT(rc == 0);
+    }
+    TEST_ASSERT(elem_cnts[3] == elem_cnts[0]);
+
+    /*
+     * Rotate
+     */
+    rc = fcb_rotate(fcb);
+    TEST_ASSERT(rc == 0);
+
+    memset(&cnts, 0, sizeof(cnts));
+    rc = fcb_walk(fcb, NULL, fcb_test_cnt_elems_cb, &aa_arg);
+    TEST_ASSERT(rc == 0);
+
+    TEST_ASSERT(cnts[0] == 0);
+    TEST_ASSERT(cnts[1] > 0);
+    TEST_ASSERT(cnts[1] == cnts[2] && cnts[1] == cnts[3]);
+
+    rc = fcb_append_to_scratch(fcb);
+    TEST_ASSERT(rc == 0);
+    rc = fcb_append_to_scratch(fcb);
+    TEST_ASSERT(rc != 0);
+}
+
+TEST_SUITE(fcb_test_all)
+{
+    fcb_test_len();
+
+    fcb_test_init();
+
+    fcb_test_empty_walk();
+
+    fcb_test_append();
+
+    fcb_test_append_too_big();
+
+    fcb_test_append_fill();
+
+    fcb_test_reset();
+
+    fcb_test_rotate();
+
+    fcb_test_multiple_scratch();
+}
+
+#if MYNEWT_VAL(SELFTEST)
+
+int
+main(int argc, char **argv)
+{
+    tu_config.tc_print_results = 1;
+    tu_init();
+
+    fcb_test_all();
+
+    return tu_any_failed;
+}
+#endif
+

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/fs/nffs/pkg.yml
----------------------------------------------------------------------
diff --git a/fs/nffs/pkg.yml b/fs/nffs/pkg.yml
index 1a3f11d..19d91be 100644
--- a/fs/nffs/pkg.yml
+++ b/fs/nffs/pkg.yml
@@ -28,9 +28,10 @@ pkg.keywords:
 
 pkg.deps:
     - fs/fs
+    - encoding/crc
     - hw/hal
-    - libs/os
-    - libs/testutil
+    - kernel/os
+    - test/testutil
     - sys/log
     - sys/stats
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/fs/nffs/src/nffs_priv.h
----------------------------------------------------------------------
diff --git a/fs/nffs/src/nffs_priv.h b/fs/nffs/src/nffs_priv.h
index 1872633..27c284b 100644
--- a/fs/nffs/src/nffs_priv.h
+++ b/fs/nffs/src/nffs_priv.h
@@ -6,7 +6,7 @@
  * to you 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,
@@ -26,7 +26,7 @@
 #include "os/os_mempool.h"
 #include "nffs/nffs.h"
 #include "fs/fs.h"
-#include "util/crc16.h"
+#include "crc/crc16.h"
 #include "stats/stats.h"
 
 #define NFFS_HASH_SIZE               256

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/fs/nffs/test/pkg.yml
----------------------------------------------------------------------
diff --git a/fs/nffs/test/pkg.yml b/fs/nffs/test/pkg.yml
index f7a66f6..750247b 100644
--- a/fs/nffs/test/pkg.yml
+++ b/fs/nffs/test/pkg.yml
@@ -24,7 +24,7 @@ pkg.keywords:
 
 pkg.deps: 
     - fs/nffs
-    - libs/testutil
+    - test/testutil
 
 pkg.deps.SELFTEST:
-    - libs/console/stub
+    - sys/console/stub

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/hw/bsp/arduino_primo_nrf52/pkg.yml
----------------------------------------------------------------------
diff --git a/hw/bsp/arduino_primo_nrf52/pkg.yml b/hw/bsp/arduino_primo_nrf52/pkg.yml
index c000e94..4c58540 100644
--- a/hw/bsp/arduino_primo_nrf52/pkg.yml
+++ b/hw/bsp/arduino_primo_nrf52/pkg.yml
@@ -41,7 +41,7 @@ pkg.cflags:
 
 pkg.deps:
     - hw/mcu/nordic/nrf52xxx
-    - libs/baselibc
+    - libc/baselibc
 
 pkg.deps.BLE_DEVICE:
     - hw/drivers/nimble/nrf52

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/hw/bsp/bmd300eval/pkg.yml
----------------------------------------------------------------------
diff --git a/hw/bsp/bmd300eval/pkg.yml b/hw/bsp/bmd300eval/pkg.yml
index d58bd63..93fa47e 100644
--- a/hw/bsp/bmd300eval/pkg.yml
+++ b/hw/bsp/bmd300eval/pkg.yml
@@ -40,7 +40,7 @@ pkg.cflags:
 
 pkg.deps:
     - hw/mcu/nordic/nrf52xxx
-    - libs/baselibc
+    - libc/baselibc
 
 pkg.deps.BLE_DEVICE:
     - hw/drivers/nimble/nrf52

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/hw/bsp/nrf51-arduino_101/pkg.yml
----------------------------------------------------------------------
diff --git a/hw/bsp/nrf51-arduino_101/pkg.yml b/hw/bsp/nrf51-arduino_101/pkg.yml
index cbe5db9..37bd2bb 100644
--- a/hw/bsp/nrf51-arduino_101/pkg.yml
+++ b/hw/bsp/nrf51-arduino_101/pkg.yml
@@ -38,7 +38,7 @@ pkg.cflags:
 
 pkg.deps:
     - hw/mcu/nordic/nrf51xxx
-    - libs/baselibc
+    - libc/baselibc
 
 pkg.deps.BLE_DEVICE:
     - hw/drivers/nimble/nrf51

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/hw/bsp/nrf51-blenano/pkg.yml
----------------------------------------------------------------------
diff --git a/hw/bsp/nrf51-blenano/pkg.yml b/hw/bsp/nrf51-blenano/pkg.yml
index ac54b16..87b1dbc 100644
--- a/hw/bsp/nrf51-blenano/pkg.yml
+++ b/hw/bsp/nrf51-blenano/pkg.yml
@@ -40,7 +40,7 @@ pkg.cflags:
 
 pkg.deps:
     - hw/mcu/nordic/nrf51xxx
-    - libs/baselibc
+    - libc/baselibc
 
 pkg.deps.BLE_DEVICE:
     - hw/drivers/nimble/nrf51

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/hw/bsp/nrf51dk-16kbram/pkg.yml
----------------------------------------------------------------------
diff --git a/hw/bsp/nrf51dk-16kbram/pkg.yml b/hw/bsp/nrf51dk-16kbram/pkg.yml
index 164e710..ef80ad5 100644
--- a/hw/bsp/nrf51dk-16kbram/pkg.yml
+++ b/hw/bsp/nrf51dk-16kbram/pkg.yml
@@ -39,7 +39,7 @@ pkg.cflags:
 
 pkg.deps:
     - hw/mcu/nordic/nrf51xxx
-    - libs/baselibc
+    - libc/baselibc
 
 pkg.deps.BLE_DEVICE:
     - hw/drivers/nimble/nrf51

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/hw/bsp/nrf51dk/pkg.yml
----------------------------------------------------------------------
diff --git a/hw/bsp/nrf51dk/pkg.yml b/hw/bsp/nrf51dk/pkg.yml
index 8df1bac..e9e741d 100644
--- a/hw/bsp/nrf51dk/pkg.yml
+++ b/hw/bsp/nrf51dk/pkg.yml
@@ -39,7 +39,7 @@ pkg.cflags:
 
 pkg.deps:
     - hw/mcu/nordic/nrf51xxx
-    - libs/baselibc
+    - libc/baselibc
 
 pkg.deps.BLE_DEVICE:
     - hw/drivers/nimble/nrf51

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/hw/bsp/nrf52dk/pkg.yml
----------------------------------------------------------------------
diff --git a/hw/bsp/nrf52dk/pkg.yml b/hw/bsp/nrf52dk/pkg.yml
index 69e520a..ee9095b 100644
--- a/hw/bsp/nrf52dk/pkg.yml
+++ b/hw/bsp/nrf52dk/pkg.yml
@@ -40,7 +40,7 @@ pkg.cflags:
 
 pkg.deps:
     - hw/mcu/nordic/nrf52xxx
-    - libs/baselibc
+    - libc/baselibc
 
 pkg.deps.BLE_DEVICE:
     - hw/drivers/nimble/nrf52

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/hw/bsp/nrf52pdk/pkg.yml
----------------------------------------------------------------------
diff --git a/hw/bsp/nrf52pdk/pkg.yml b/hw/bsp/nrf52pdk/pkg.yml
index c9c55f5..47c411c 100644
--- a/hw/bsp/nrf52pdk/pkg.yml
+++ b/hw/bsp/nrf52pdk/pkg.yml
@@ -39,7 +39,7 @@ pkg.cflags:
 
 pkg.deps:
     - hw/mcu/nordic/nrf52xxx
-    - libs/baselibc
+    - libc/baselibc
 
 pkg.deps.BLE_DEVICE:
     - hw/drivers/nimble/nrf52

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/hw/bsp/nucleo-f401re/pkg.yml
----------------------------------------------------------------------
diff --git a/hw/bsp/nucleo-f401re/pkg.yml b/hw/bsp/nucleo-f401re/pkg.yml
index b579be1..bb36d88 100644
--- a/hw/bsp/nucleo-f401re/pkg.yml
+++ b/hw/bsp/nucleo-f401re/pkg.yml
@@ -36,4 +36,4 @@ pkg.debugscript: "nucleo-f401re_debug.sh"
 pkg.cflags: -DSTM32F401xE
 pkg.deps:
     - hw/mcu/stm/stm32f4xx
-    - libs/baselibc
+    - libc/baselibc

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/hw/bsp/olimex_stm32-e407_devboard/pkg.yml
----------------------------------------------------------------------
diff --git a/hw/bsp/olimex_stm32-e407_devboard/pkg.yml b/hw/bsp/olimex_stm32-e407_devboard/pkg.yml
index a8c5b6e..6d34817 100644
--- a/hw/bsp/olimex_stm32-e407_devboard/pkg.yml
+++ b/hw/bsp/olimex_stm32-e407_devboard/pkg.yml
@@ -40,7 +40,7 @@ pkg.cflags:
     - '-DHAL_DMA_MODULE_ENABLED'
 pkg.deps:
     - hw/mcu/stm/stm32f4xx
-    - libs/baselibc
+    - libc/baselibc
 
 pkg.deps.ADC_1:
     - hw/drivers/adc/adc_stm32f4

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/hw/bsp/stm32f4discovery/pkg.yml
----------------------------------------------------------------------
diff --git a/hw/bsp/stm32f4discovery/pkg.yml b/hw/bsp/stm32f4discovery/pkg.yml
index 04e74d3..b6b6e36 100644
--- a/hw/bsp/stm32f4discovery/pkg.yml
+++ b/hw/bsp/stm32f4discovery/pkg.yml
@@ -36,4 +36,4 @@ pkg.debugscript: "stm32f4discovery_debug.sh"
 pkg.cflags: -DSTM32F407xx
 pkg.deps:
     - hw/mcu/stm/stm32f4xx
-    - libs/baselibc
+    - libc/baselibc

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/hw/cmsis-core/pkg.yml
----------------------------------------------------------------------
diff --git a/hw/cmsis-core/pkg.yml b/hw/cmsis-core/pkg.yml
new file mode 100644
index 0000000..0903256
--- /dev/null
+++ b/hw/cmsis-core/pkg.yml
@@ -0,0 +1,27 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+#
+
+pkg.name: hw/cmsis-core
+pkg.description: CMSIS-CORE abstraction layer for Cortex-M processors.
+pkg.author: "Keil"
+pkg.homepage: "http://www.keil.com/pack/doc/CMSIS/Core/html/index.html"
+pkg.keywords:
+    - cmsis
+    - core
+pkg.type: sdk



[42/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/hw/cmsis-core/src/cmsis_nvic.c
----------------------------------------------------------------------
diff --git a/hw/cmsis-core/src/cmsis_nvic.c b/hw/cmsis-core/src/cmsis_nvic.c
new file mode 100644
index 0000000..a350791
--- /dev/null
+++ b/hw/cmsis-core/src/cmsis_nvic.c
@@ -0,0 +1,73 @@
+/* mbed Microcontroller Library - cmsis_nvic for XXXX
+ * Copyright (c) 2009-2011 ARM Limited. All rights reserved.
+ *
+ * CMSIS-style functionality to support dynamic vectors
+ */
+#include "bsp/cmsis_nvic.h"
+
+#ifndef __CORTEX_M
+    #error "Macro __CORTEX_M not defined; must define cortex-m type!"
+#endif
+
+#if (__CORTEX_M == 0) 
+    #ifndef __VTOR_PRESENT
+    /* no VTOR is defined so we assume we can't relocate the vector table */
+    #define __VTOR_PRESENT  (0)
+#endif
+#endif
+
+extern char __isr_vector[];
+extern char __vector_tbl_reloc__[];
+
+void
+NVIC_Relocate(void)
+{
+    uint32_t *current_location;
+    uint32_t *new_location;
+    int i;
+
+    /*
+     * Relocate the vector table from its current position to the position
+     * designated in the linker script.
+     */
+    current_location = (uint32_t *)&__isr_vector;
+    new_location = (uint32_t *)&__vector_tbl_reloc__;
+
+    if (new_location != current_location) {
+        for (i = 0; i < NVIC_NUM_VECTORS; i++) {
+            new_location[i] = current_location[i];
+        }
+    }
+
+    /* Set VTOR except for M0 */
+#if ((__CORTEX_M == 0) && (__VTOR_PRESENT == 0))
+#else
+    SCB->VTOR = (uint32_t)&__vector_tbl_reloc__;
+#endif
+}
+
+void
+NVIC_SetVector(IRQn_Type IRQn, uint32_t vector)
+{
+    uint32_t *vectors;
+#if ((__CORTEX_M == 0) && (__VTOR_PRESENT == 0))
+    vectors = (uint32_t *)&__vector_tbl_reloc__;
+#else
+    vectors = (uint32_t *)SCB->VTOR;
+#endif
+    vectors[IRQn + NVIC_USER_IRQ_OFFSET] = vector;
+    __DMB();
+}
+
+uint32_t
+NVIC_GetVector(IRQn_Type IRQn)
+{
+    uint32_t *vectors;
+#if (__CORTEX_M == 0)
+    vectors = (uint32_t *)&__vector_tbl_reloc__;
+#else
+    vectors = (uint32_t*)SCB->VTOR;
+#endif
+    return vectors[IRQn + NVIC_USER_IRQ_OFFSET];
+}
+

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/hw/cmsis-core/src/ext/core_ca9.h
----------------------------------------------------------------------
diff --git a/hw/cmsis-core/src/ext/core_ca9.h b/hw/cmsis-core/src/ext/core_ca9.h
new file mode 100644
index 0000000..bae5f65
--- /dev/null
+++ b/hw/cmsis-core/src/ext/core_ca9.h
@@ -0,0 +1,271 @@
+/**************************************************************************//**
+ * @file     core_ca9.h
+ * @brief    CMSIS Cortex-A9 Core Peripheral Access Layer Header File
+ * @version
+ * @date     25 March 2013
+ *
+ * @note
+ *
+ ******************************************************************************/
+/* Copyright (c) 2009 - 2012 ARM LIMITED
+
+   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 ARM 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 COPYRIGHT HOLDERS AND CONTRIBUTORS BE
+   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+   POSSIBILITY OF SUCH DAMAGE.
+   ---------------------------------------------------------------------------*/
+
+
+#if defined ( __ICCARM__ )
+ #pragma system_include  /* treat file as system include file for MISRA check */
+#endif
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+#ifndef __CORE_CA9_H_GENERIC
+#define __CORE_CA9_H_GENERIC
+
+
+/** \page CMSIS_MISRA_Exceptions  MISRA-C:2004 Compliance Exceptions
+  CMSIS violates the following MISRA-C:2004 rules:
+
+   \li Required Rule 8.5, object/function definition in header file.<br>
+     Function definitions in header files are used to allow 'inlining'.
+
+   \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.<br>
+     Unions are used for effective representation of core registers.
+
+   \li Advisory Rule 19.7, Function-like macro defined.<br>
+     Function-like macros are used to allow more efficient code.
+ */
+
+
+/*******************************************************************************
+ *                 CMSIS definitions
+ ******************************************************************************/
+/** \ingroup Cortex_A9
+  @{
+ */
+
+/*  CMSIS CA9 definitions */
+#define __CA9_CMSIS_VERSION_MAIN  (0x03)                                   /*!< [31:16] CMSIS HAL main version   */
+#define __CA9_CMSIS_VERSION_SUB   (0x10)                                   /*!< [15:0]  CMSIS HAL sub version    */
+#define __CA9_CMSIS_VERSION       ((__CA9_CMSIS_VERSION_MAIN << 16) | \
+                                    __CA9_CMSIS_VERSION_SUB          )     /*!< CMSIS HAL version number         */
+
+#define __CORTEX_A                (0x09)                                   /*!< Cortex-A Core                    */
+
+
+#if   defined ( __CC_ARM )
+  #define __ASM            __asm                                      /*!< asm keyword for ARM Compiler          */
+  #define __INLINE         __inline                                   /*!< inline keyword for ARM Compiler       */
+  #define __STATIC_INLINE  static __inline
+  #define __STATIC_ASM     static __asm
+
+#elif defined ( __ICCARM__ )
+  #define __ASM            __asm                                      /*!< asm keyword for IAR Compiler          */
+  #define __INLINE         inline                                     /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */
+  #define __STATIC_INLINE  static inline
+  #define __STATIC_ASM     static __asm
+
+#elif defined ( __TMS470__ )
+  #define __ASM            __asm                                      /*!< asm keyword for TI CCS Compiler       */
+  #define __STATIC_INLINE  static inline
+  #define __STATIC_ASM     static __asm
+
+#elif defined ( __GNUC__ )
+  #define __ASM            __asm                                      /*!< asm keyword for GNU Compiler          */
+  #define __INLINE         inline                                     /*!< inline keyword for GNU Compiler       */
+  #define __STATIC_INLINE  static inline
+  #define __STATIC_ASM     static __asm
+
+#elif defined ( __TASKING__ )
+  #define __ASM            __asm                                      /*!< asm keyword for TASKING Compiler      */
+  #define __INLINE         inline                                     /*!< inline keyword for TASKING Compiler   */
+  #define __STATIC_INLINE  static inline
+  #define __STATIC_ASM     static __asm
+
+#endif
+
+/** __FPU_USED indicates whether an FPU is used or not. For this, __FPU_PRESENT has to be checked prior to making use of FPU specific registers and functions.
+*/
+#if defined ( __CC_ARM )
+  #if defined __TARGET_FPU_VFP
+    #if (__FPU_PRESENT == 1)
+      #define __FPU_USED       1
+    #else
+      #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
+      #define __FPU_USED       0
+    #endif
+  #else
+    #define __FPU_USED         0
+  #endif
+
+#elif defined ( __ICCARM__ )
+  #if defined __ARMVFP__
+    #if (__FPU_PRESENT == 1)
+      #define __FPU_USED       1
+    #else
+      #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
+      #define __FPU_USED       0
+    #endif
+  #else
+    #define __FPU_USED         0
+  #endif
+
+#elif defined ( __TMS470__ )
+  #if defined __TI_VFP_SUPPORT__
+    #if (__FPU_PRESENT == 1)
+      #define __FPU_USED       1
+    #else
+      #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
+      #define __FPU_USED       0
+    #endif
+  #else
+    #define __FPU_USED         0
+  #endif
+
+#elif defined ( __GNUC__ )
+  #if defined (__VFP_FP__) && !defined(__SOFTFP__)
+    #if (__FPU_PRESENT == 1)
+      #define __FPU_USED       1
+    #else
+      #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
+      #define __FPU_USED       0
+    #endif
+  #else
+    #define __FPU_USED         0
+  #endif
+
+#elif defined ( __TASKING__ )
+  #if defined __FPU_VFP__
+    #if (__FPU_PRESENT == 1)
+      #define __FPU_USED       1
+    #else
+      #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
+      #define __FPU_USED       0
+    #endif
+  #else
+    #define __FPU_USED         0
+  #endif
+#endif
+
+#include <stdint.h>                      /*!< standard types definitions                      */
+#include "core_caInstr.h"                /*!< Core Instruction Access                         */
+#include "core_caFunc.h"                 /*!< Core Function Access                            */
+#include "core_cm4_simd.h"               /*!< Compiler specific SIMD Intrinsics               */
+
+#endif /* __CORE_CA9_H_GENERIC */
+
+#ifndef __CMSIS_GENERIC
+
+#ifndef __CORE_CA9_H_DEPENDANT
+#define __CORE_CA9_H_DEPENDANT
+
+/* check device defines and use defaults */
+#if defined __CHECK_DEVICE_DEFINES
+  #ifndef __CA9_REV
+    #define __CA9_REV               0x0000
+    #warning "__CA9_REV not defined in device header file; using default!"
+  #endif
+
+  #ifndef __FPU_PRESENT
+    #define __FPU_PRESENT             1
+    #warning "__FPU_PRESENT not defined in device header file; using default!"
+  #endif
+
+  #ifndef __Vendor_SysTickConfig
+    #define __Vendor_SysTickConfig    1
+  #endif
+
+  #if __Vendor_SysTickConfig == 0
+    #error "__Vendor_SysTickConfig set to 0, but vendor systick timer must be supplied for Cortex-A9"
+  #endif
+#endif
+
+/* IO definitions (access restrictions to peripheral registers) */
+/**
+    \defgroup CMSIS_glob_defs CMSIS Global Defines
+
+    <strong>IO Type Qualifiers</strong> are used
+    \li to specify the access to peripheral variables.
+    \li for automatic generation of peripheral register debug information.
+*/
+#ifdef __cplusplus
+  #define   __I     volatile             /*!< Defines 'read only' permissions                 */
+#else
+  #define   __I     volatile const       /*!< Defines 'read only' permissions                 */
+#endif
+#define     __O     volatile             /*!< Defines 'write only' permissions                */
+#define     __IO    volatile             /*!< Defines 'read / write' permissions              */
+
+/*@} end of group Cortex_A9 */
+
+
+/*******************************************************************************
+ *                 Register Abstraction
+ ******************************************************************************/
+/** \defgroup CMSIS_core_register Defines and Type Definitions
+    \brief Type definitions and defines for Cortex-A processor based devices.
+*/
+
+/** \ingroup    CMSIS_core_register
+    \defgroup   CMSIS_CORE  Status and Control Registers
+    \brief  Core Register type definitions.
+  @{
+ */
+
+/** \brief  Union type to access the Application Program Status Register (APSR).
+ */
+typedef union
+{
+  struct
+  {
+    uint32_t _reserved0:16;              /*!< bit:  0..15  Reserved                           */
+    uint32_t GE:4;                       /*!< bit: 16..19  Greater than or Equal flags        */
+    uint32_t reserved1:7;                /*!< bit: 20..23  Reserved                           */
+    uint32_t Q:1;                        /*!< bit:     27  Saturation condition flag          */
+    uint32_t V:1;                        /*!< bit:     28  Overflow condition code flag       */
+    uint32_t C:1;                        /*!< bit:     29  Carry condition code flag          */
+    uint32_t Z:1;                        /*!< bit:     30  Zero condition code flag           */
+    uint32_t N:1;                        /*!< bit:     31  Negative condition code flag       */
+  } b;                                   /*!< Structure used for bit  access                  */
+  uint32_t w;                            /*!< Type      used for word access                  */ 
+} APSR_Type;
+
+
+/*@} end of group CMSIS_CORE */
+
+/*@} end of CMSIS_Core_FPUFunctions */
+
+
+#endif /* __CORE_CA9_H_GENERIC */
+
+#endif /* __CMSIS_GENERIC */
+
+#ifdef __cplusplus
+}
+
+
+#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/hw/cmsis-core/src/ext/core_caFunc.h
----------------------------------------------------------------------
diff --git a/hw/cmsis-core/src/ext/core_caFunc.h b/hw/cmsis-core/src/ext/core_caFunc.h
new file mode 100644
index 0000000..3f40094
--- /dev/null
+++ b/hw/cmsis-core/src/ext/core_caFunc.h
@@ -0,0 +1,1161 @@
+/**************************************************************************//**
+ * @file     core_caFunc.h
+ * @brief    CMSIS Cortex-A Core Function Access Header File
+ * @version  V3.10
+ * @date     9 May 2013
+ *
+ * @note
+ *
+ ******************************************************************************/
+/* Copyright (c) 2009 - 2012 ARM LIMITED
+
+   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 ARM 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 COPYRIGHT HOLDERS AND 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.
+   ---------------------------------------------------------------------------*/
+
+
+#ifndef __CORE_CAFUNC_H__
+#define __CORE_CAFUNC_H__
+
+
+/* ###########################  Core Function Access  ########################### */
+/** \ingroup  CMSIS_Core_FunctionInterface
+    \defgroup CMSIS_Core_RegAccFunctions CMSIS Core Register Access Functions
+  @{
+ */
+
+#if   defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/
+/* ARM armcc specific functions */
+
+#if (__ARMCC_VERSION < 400677)
+  #error "Please use ARM Compiler Toolchain V4.0.677 or later!"
+#endif
+
+#define MODE_USR 0x10
+#define MODE_FIQ 0x11
+#define MODE_IRQ 0x12
+#define MODE_SVC 0x13
+#define MODE_MON 0x16
+#define MODE_ABT 0x17
+#define MODE_HYP 0x1A
+#define MODE_UND 0x1B
+#define MODE_SYS 0x1F
+
+/** \brief  Get APSR Register
+
+    This function returns the content of the APSR Register.
+
+    \return               APSR Register value
+ */
+__STATIC_INLINE uint32_t __get_APSR(void)
+{
+  register uint32_t __regAPSR          __ASM("apsr");
+  return(__regAPSR);
+}
+
+
+/** \brief  Get CPSR Register
+
+    This function returns the content of the CPSR Register.
+
+    \return               CPSR Register value
+ */
+__STATIC_INLINE uint32_t __get_CPSR(void)
+{
+  register uint32_t __regCPSR          __ASM("cpsr");
+  return(__regCPSR);
+}
+
+/** \brief  Set Stack Pointer
+
+    This function assigns the given value to the current stack pointer.
+
+    \param [in]    topOfStack  Stack Pointer value to set
+ */
+register uint32_t __regSP              __ASM("sp");
+__STATIC_INLINE void __set_SP(uint32_t topOfStack)
+{
+    __regSP = topOfStack;
+}
+
+
+/** \brief  Get link register
+
+    This function returns the value of the link register
+
+    \return    Value of link register
+ */
+register uint32_t __reglr         __ASM("lr");
+__STATIC_INLINE uint32_t __get_LR(void)
+{
+  return(__reglr);
+}
+
+/** \brief  Set link register
+
+    This function sets the value of the link register
+
+    \param [in]    lr  LR value to set
+ */
+__STATIC_INLINE void __set_LR(uint32_t lr)
+{
+  __reglr = lr;
+}
+
+/** \brief  Set Process Stack Pointer
+
+    This function assigns the given value to the USR/SYS Stack Pointer (PSP).
+
+    \param [in]    topOfProcStack  USR/SYS Stack Pointer value to set
+ */
+__STATIC_ASM void __set_PSP(uint32_t topOfProcStack)
+{
+    ARM
+    PRESERVE8
+
+    BIC     R0, R0, #7  ;ensure stack is 8-byte aligned
+    MRS     R1, CPSR
+    CPS     #MODE_SYS   ;no effect in USR mode
+    MOV     SP, R0
+    MSR     CPSR_c, R1  ;no effect in USR mode
+    ISB
+    BX      LR
+
+}
+
+/** \brief  Set User Mode
+
+    This function changes the processor state to User Mode
+
+    \param [in]    topOfProcStack  USR/SYS Stack Pointer value to set
+ */
+__STATIC_ASM void __set_CPS_USR(void)
+{
+    ARM 
+
+    CPS  #MODE_USR  
+    BX   LR
+}
+
+
+/** \brief  Enable FIQ
+
+    This function enables FIQ interrupts by clearing the F-bit in the CPSR.
+    Can only be executed in Privileged modes.
+ */
+#define __enable_fault_irq                __enable_fiq
+
+
+/** \brief  Disable FIQ
+
+    This function disables FIQ interrupts by setting the F-bit in the CPSR.
+    Can only be executed in Privileged modes.
+ */
+#define __disable_fault_irq               __disable_fiq
+
+
+/** \brief  Get FPSCR
+
+    This function returns the current value of the Floating Point Status/Control register.
+
+    \return               Floating Point Status/Control register value
+ */
+__STATIC_INLINE uint32_t __get_FPSCR(void)
+{
+#if (__FPU_PRESENT == 1) && (__FPU_USED == 1)
+  register uint32_t __regfpscr         __ASM("fpscr");
+  return(__regfpscr);
+#else
+   return(0);
+#endif
+}
+
+
+/** \brief  Set FPSCR
+
+    This function assigns the given value to the Floating Point Status/Control register.
+
+    \param [in]    fpscr  Floating Point Status/Control value to set
+ */
+__STATIC_INLINE void __set_FPSCR(uint32_t fpscr)
+{
+#if (__FPU_PRESENT == 1) && (__FPU_USED == 1)
+  register uint32_t __regfpscr         __ASM("fpscr");
+  __regfpscr = (fpscr);
+#endif
+}
+
+/** \brief  Get FPEXC
+
+    This function returns the current value of the Floating Point Exception Control register.
+
+    \return               Floating Point Exception Control register value
+ */
+__STATIC_INLINE uint32_t __get_FPEXC(void)
+{
+#if (__FPU_PRESENT == 1)
+  register uint32_t __regfpexc         __ASM("fpexc");
+  return(__regfpexc);
+#else
+   return(0);
+#endif
+}
+
+
+/** \brief  Set FPEXC
+
+    This function assigns the given value to the Floating Point Exception Control register.
+
+    \param [in]    fpscr  Floating Point Exception Control value to set
+ */
+__STATIC_INLINE void __set_FPEXC(uint32_t fpexc)
+{
+#if (__FPU_PRESENT == 1)
+  register uint32_t __regfpexc         __ASM("fpexc");
+  __regfpexc = (fpexc);
+#endif
+}
+
+/** \brief  Get CPACR
+
+    This function returns the current value of the Coprocessor Access Control register.
+
+    \return               Coprocessor Access Control register value
+ */
+__STATIC_INLINE uint32_t __get_CPACR(void)
+{
+    register uint32_t __regCPACR         __ASM("cp15:0:c1:c0:2");
+    return __regCPACR;
+}
+
+/** \brief  Set CPACR
+
+    This function assigns the given value to the Coprocessor Access Control register.
+
+    \param [in]    cpacr  Coporcessor Acccess Control value to set
+ */
+__STATIC_INLINE void __set_CPACR(uint32_t cpacr)
+{
+    register uint32_t __regCPACR         __ASM("cp15:0:c1:c0:2");
+    __regCPACR = cpacr;
+    __ISB();
+}
+
+/** \brief  Get CBAR
+
+    This function returns the value of the Configuration Base Address register.
+
+    \return               Configuration Base Address register value
+ */
+__STATIC_INLINE uint32_t __get_CBAR() {
+    register uint32_t __regCBAR         __ASM("cp15:4:c15:c0:0");
+    return(__regCBAR);
+}
+
+/** \brief  Get TTBR0
+
+    This function returns the value of the Configuration Base Address register.
+
+    \return               Translation Table Base Register 0 value
+ */
+__STATIC_INLINE uint32_t __get_TTBR0() {
+    register uint32_t __regTTBR0        __ASM("cp15:0:c2:c0:0");
+    return(__regTTBR0);
+}
+
+/** \brief  Set TTBR0
+
+    This function assigns the given value to the Coprocessor Access Control register.
+
+    \param [in]    ttbr0  Translation Table Base Register 0 value to set
+ */
+__STATIC_INLINE void __set_TTBR0(uint32_t ttbr0) {
+    register uint32_t __regTTBR0        __ASM("cp15:0:c2:c0:0");
+    __regTTBR0 = ttbr0;
+    __ISB();
+}
+
+/** \brief  Get DACR
+
+    This function returns the value of the Domain Access Control Register.
+
+    \return               Domain Access Control Register value
+ */
+__STATIC_INLINE uint32_t __get_DACR() {
+    register uint32_t __regDACR         __ASM("cp15:0:c3:c0:0");
+    return(__regDACR);
+}
+
+/** \brief  Set DACR
+
+    This function assigns the given value to the Coprocessor Access Control register.
+
+    \param [in]    dacr   Domain Access Control Register value to set
+ */
+__STATIC_INLINE void __set_DACR(uint32_t dacr) {
+    register uint32_t __regDACR         __ASM("cp15:0:c3:c0:0");
+    __regDACR = dacr;
+    __ISB();
+}
+
+/******************************** Cache and BTAC enable  ****************************************************/
+
+/** \brief  Set SCTLR
+
+    This function assigns the given value to the System Control Register.
+
+    \param [in]    sctlr  System Control Register, value to set
+ */
+__STATIC_INLINE void __set_SCTLR(uint32_t sctlr)
+{
+    register uint32_t __regSCTLR         __ASM("cp15:0:c1:c0:0");
+    __regSCTLR = sctlr;
+}
+
+/** \brief  Get SCTLR
+
+    This function returns the value of the System Control Register.
+
+    \return               System Control Register value
+ */
+__STATIC_INLINE uint32_t __get_SCTLR() {
+    register uint32_t __regSCTLR         __ASM("cp15:0:c1:c0:0");
+    return(__regSCTLR);
+}
+
+/** \brief  Enable Caches
+
+    Enable Caches
+ */
+__STATIC_INLINE void __enable_caches(void) {
+    // Set I bit 12 to enable I Cache
+    // Set C bit  2 to enable D Cache
+    __set_SCTLR( __get_SCTLR() | (1 << 12) | (1 << 2));
+}
+
+/** \brief  Disable Caches
+
+    Disable Caches
+ */
+__STATIC_INLINE void __disable_caches(void) {
+    // Clear I bit 12 to disable I Cache
+    // Clear C bit  2 to disable D Cache
+    __set_SCTLR( __get_SCTLR() & ~(1 << 12) & ~(1 << 2));
+    __ISB();
+}
+
+/** \brief  Enable BTAC
+
+    Enable BTAC
+ */
+__STATIC_INLINE void __enable_btac(void) {
+    // Set Z bit 11 to enable branch prediction
+    __set_SCTLR( __get_SCTLR() | (1 << 11));
+    __ISB();
+}
+
+/** \brief  Disable BTAC
+
+    Disable BTAC
+ */
+__STATIC_INLINE void __disable_btac(void) {
+    // Clear Z bit 11 to disable branch prediction
+    __set_SCTLR( __get_SCTLR() & ~(1 << 11));
+}
+
+
+/** \brief  Enable MMU
+
+    Enable MMU
+ */
+__STATIC_INLINE void __enable_mmu(void) {
+    // Set M bit 0 to enable the MMU
+    // Set AFE bit to enable simplified access permissions model
+    // Clear TRE bit to disable TEX remap and A bit to disable strict alignment fault checking
+    __set_SCTLR( (__get_SCTLR() & ~(1 << 28) & ~(1 << 1)) | 1 | (1 << 29));
+    __ISB();
+}
+
+/** \brief  Enable MMU
+
+    Enable MMU
+ */
+__STATIC_INLINE void __disable_mmu(void) {
+    // Clear M bit 0 to disable the MMU
+    __set_SCTLR( __get_SCTLR() & ~1);
+    __ISB();
+}
+
+/******************************** TLB maintenance operations ************************************************/
+/** \brief  Invalidate the whole tlb
+
+    TLBIALL. Invalidate the whole tlb
+ */
+
+__STATIC_INLINE void __ca9u_inv_tlb_all(void) {
+    register uint32_t __TLBIALL         __ASM("cp15:0:c8:c7:0");
+    __TLBIALL = 0;
+    __DSB();
+    __ISB();
+}
+
+/******************************** BTB maintenance operations ************************************************/
+/** \brief  Invalidate entire branch predictor array
+
+    BPIALL. Branch Predictor Invalidate All.
+ */
+
+__STATIC_INLINE void __v7_inv_btac(void) {
+    register uint32_t __BPIALL          __ASM("cp15:0:c7:c5:6");
+    __BPIALL  = 0;
+    __DSB();     //ensure completion of the invalidation
+    __ISB();     //ensure instruction fetch path sees new state
+}
+
+
+/******************************** L1 cache operations ******************************************************/
+
+/** \brief  Invalidate the whole I$
+
+    ICIALLU. Instruction Cache Invalidate All to PoU
+ */
+__STATIC_INLINE void __v7_inv_icache_all(void) {
+    register uint32_t __ICIALLU         __ASM("cp15:0:c7:c5:0");
+    __ICIALLU = 0;
+    __DSB();     //ensure completion of the invalidation
+    __ISB();     //ensure instruction fetch path sees new I cache state
+}
+
+/** \brief  Clean D$ by MVA
+
+    DCCMVAC. Data cache clean by MVA to PoC
+ */
+__STATIC_INLINE void __v7_clean_dcache_mva(void *va) {
+    register uint32_t __DCCMVAC         __ASM("cp15:0:c7:c10:1");
+    __DCCMVAC = (uint32_t)va;
+    __DMB();     //ensure the ordering of data cache maintenance operations and their effects
+}
+
+/** \brief  Invalidate D$ by MVA
+
+    DCIMVAC. Data cache invalidate by MVA to PoC
+ */
+__STATIC_INLINE void __v7_inv_dcache_mva(void *va) {
+    register uint32_t __DCIMVAC         __ASM("cp15:0:c7:c6:1");
+    __DCIMVAC = (uint32_t)va;
+    __DMB();     //ensure the ordering of data cache maintenance operations and their effects
+}
+
+/** \brief  Clean and Invalidate D$ by MVA
+
+    DCCIMVAC. Data cache clean and invalidate by MVA to PoC
+ */
+__STATIC_INLINE void __v7_clean_inv_dcache_mva(void *va) {
+    register uint32_t __DCCIMVAC        __ASM("cp15:0:c7:c14:1");
+    __DCCIMVAC = (uint32_t)va;
+    __DMB();     //ensure the ordering of data cache maintenance operations and their effects
+}
+
+/** \brief
+ * Generic mechanism for cleaning/invalidating the entire data or unified cache to the point of coherency.
+ */
+#pragma push
+#pragma arm
+__STATIC_ASM void __v7_all_cache(uint32_t op) {
+        ARM 
+
+        PUSH    {R4-R11}
+
+        MRC     p15, 1, R6, c0, c0, 1      // Read CLIDR
+        ANDS    R3, R6, #0x07000000        // Extract coherency level
+        MOV     R3, R3, LSR #23            // Total cache levels << 1
+        BEQ     Finished                   // If 0, no need to clean
+
+        MOV     R10, #0                    // R10 holds current cache level << 1
+Loop1   ADD     R2, R10, R10, LSR #1       // R2 holds cache "Set" position
+        MOV     R1, R6, LSR R2             // Bottom 3 bits are the Cache-type for this level
+        AND     R1, R1, #7                 // Isolate those lower 3 bits
+        CMP     R1, #2
+        BLT     Skip                       // No cache or only instruction cache at this level
+
+        MCR     p15, 2, R10, c0, c0, 0     // Write the Cache Size selection register
+        ISB                                // ISB to sync the change to the CacheSizeID reg
+        MRC     p15, 1, R1, c0, c0, 0      // Reads current Cache Size ID register
+        AND     R2, R1, #7                 // Extract the line length field
+        ADD     R2, R2, #4                 // Add 4 for the line length offset (log2 16 bytes)
+        LDR     R4, =0x3FF
+        ANDS    R4, R4, R1, LSR #3         // R4 is the max number on the way size (right aligned)
+        CLZ     R5, R4                     // R5 is the bit position of the way size increment
+        LDR     R7, =0x7FFF
+        ANDS    R7, R7, R1, LSR #13        // R7 is the max number of the index size (right aligned)
+
+Loop2   MOV     R9, R4                     // R9 working copy of the max way size (right aligned)
+
+Loop3   ORR     R11, R10, R9, LSL R5       // Factor in the Way number and cache number into R11
+        ORR     R11, R11, R7, LSL R2       // Factor in the Set number
+        CMP     R0, #0
+        BNE     Dccsw
+        MCR     p15, 0, R11, c7, c6, 2     // DCISW. Invalidate by Set/Way
+        B       cont
+Dccsw   CMP     R0, #1
+        BNE     Dccisw
+        MCR     p15, 0, R11, c7, c10, 2    // DCCSW. Clean by Set/Way
+        B       cont
+Dccisw  MCR     p15, 0, R11, c7, c14, 2    // DCCISW, Clean and Invalidate by Set/Way
+cont    SUBS    R9, R9, #1                 // Decrement the Way number
+        BGE     Loop3
+        SUBS    R7, R7, #1                 // Decrement the Set number
+        BGE     Loop2
+Skip    ADD     R10, R10, #2               // increment the cache number
+        CMP     R3, R10
+        BGT     Loop1
+
+Finished
+        DSB
+        POP    {R4-R11}
+        BX     lr
+
+}
+#pragma pop
+
+/** \brief  __v7_all_cache - helper function
+
+ */
+
+/** \brief  Invalidate the whole D$
+
+    DCISW. Invalidate by Set/Way
+ */
+
+__STATIC_INLINE void __v7_inv_dcache_all(void) {
+    __v7_all_cache(0);
+}
+
+/** \brief  Clean the whole D$
+
+    DCCSW. Clean by Set/Way
+ */
+
+__STATIC_INLINE void __v7_clean_dcache_all(void) {
+    __v7_all_cache(1);
+}
+
+/** \brief  Clean and invalidate the whole D$
+
+    DCCISW. Clean and Invalidate by Set/Way
+ */
+
+__STATIC_INLINE void __v7_clean_inv_dcache_all(void) {
+    __v7_all_cache(2);
+}
+
+#include "core_ca_mmu.h"
+
+#elif (defined (__ICCARM__)) /*---------------- ICC Compiler ---------------------*/
+
+#error IAR Compiler support not implemented for Cortex-A
+
+#elif (defined (__GNUC__)) /*------------------ GNU Compiler ---------------------*/
+
+/* GNU gcc specific functions */
+
+#define MODE_USR 0x10
+#define MODE_FIQ 0x11
+#define MODE_IRQ 0x12
+#define MODE_SVC 0x13
+#define MODE_MON 0x16
+#define MODE_ABT 0x17
+#define MODE_HYP 0x1A
+#define MODE_UND 0x1B
+#define MODE_SYS 0x1F
+
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_irq(void)
+{
+    __ASM volatile ("cpsie i");
+}
+
+/** \brief  Disable IRQ Interrupts
+
+  This function disables IRQ interrupts by setting the I-bit in the CPSR.
+  Can only be executed in Privileged modes.
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __disable_irq(void)
+{
+    uint32_t result;
+
+    __ASM volatile ("mrs %0, cpsr" : "=r" (result));
+    __ASM volatile ("cpsid i");
+    return(result & 0x80);
+}
+
+
+/** \brief  Get APSR Register
+
+    This function returns the content of the APSR Register.
+
+    \return               APSR Register value
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_APSR(void)
+{
+#if 1
+    uint32_t result;
+
+    __ASM volatile ("mrs %0, apsr" : "=r" (result) );
+    return (result);
+#else
+  register uint32_t __regAPSR          __ASM("apsr");
+  return(__regAPSR);
+#endif
+}
+
+
+/** \brief  Get CPSR Register
+
+    This function returns the content of the CPSR Register.
+
+    \return               CPSR Register value
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_CPSR(void)
+{
+#if 1
+  register uint32_t __regCPSR;
+  __ASM volatile ("mrs %0, cpsr" : "=r" (__regCPSR));
+#else
+  register uint32_t __regCPSR          __ASM("cpsr");
+#endif
+  return(__regCPSR);
+}
+
+#if 0
+/** \brief  Set Stack Pointer
+
+    This function assigns the given value to the current stack pointer.
+
+    \param [in]    topOfStack  Stack Pointer value to set
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_SP(uint32_t topOfStack)
+{
+    register uint32_t __regSP       __ASM("sp");
+    __regSP = topOfStack;
+}
+#endif
+
+/** \brief  Get link register
+
+    This function returns the value of the link register
+
+    \return    Value of link register
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_LR(void)
+{
+  register uint32_t __reglr         __ASM("lr");
+  return(__reglr);
+}
+
+#if 0
+/** \brief  Set link register
+
+    This function sets the value of the link register
+
+    \param [in]    lr  LR value to set
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_LR(uint32_t lr)
+{
+  register uint32_t __reglr         __ASM("lr");
+  __reglr = lr;
+}
+#endif
+
+/** \brief  Set Process Stack Pointer
+
+    This function assigns the given value to the USR/SYS Stack Pointer (PSP).
+
+    \param [in]    topOfProcStack  USR/SYS Stack Pointer value to set
+ */
+extern void __set_PSP(uint32_t topOfProcStack);
+
+/** \brief  Set User Mode
+
+    This function changes the processor state to User Mode
+
+    \param [in]    topOfProcStack  USR/SYS Stack Pointer value to set
+ */
+extern void __set_CPS_USR(void);
+
+/** \brief  Enable FIQ
+
+    This function enables FIQ interrupts by clearing the F-bit in the CPSR.
+    Can only be executed in Privileged modes.
+ */
+#define __enable_fault_irq                __enable_fiq
+
+
+/** \brief  Disable FIQ
+
+    This function disables FIQ interrupts by setting the F-bit in the CPSR.
+    Can only be executed in Privileged modes.
+ */
+#define __disable_fault_irq               __disable_fiq
+
+
+/** \brief  Get FPSCR
+
+    This function returns the current value of the Floating Point Status/Control register.
+
+    \return               Floating Point Status/Control register value
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_FPSCR(void)
+{
+#if (__FPU_PRESENT == 1) && (__FPU_USED == 1)
+#if 1
+    uint32_t result;
+
+    __ASM volatile ("vmrs %0, fpscr" : "=r" (result) );
+    return (result);
+#else
+  register uint32_t __regfpscr         __ASM("fpscr");
+  return(__regfpscr);
+#endif
+#else
+   return(0);
+#endif
+}
+
+
+/** \brief  Set FPSCR
+
+    This function assigns the given value to the Floating Point Status/Control register.
+
+    \param [in]    fpscr  Floating Point Status/Control value to set
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_FPSCR(uint32_t fpscr)
+{
+#if (__FPU_PRESENT == 1) && (__FPU_USED == 1)
+#if 1
+    __ASM volatile ("vmsr fpscr, %0" : : "r" (fpscr) );
+#else
+  register uint32_t __regfpscr         __ASM("fpscr");
+  __regfpscr = (fpscr);
+#endif
+#endif
+}
+
+/** \brief  Get FPEXC
+
+    This function returns the current value of the Floating Point Exception Control register.
+
+    \return               Floating Point Exception Control register value
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_FPEXC(void)
+{
+#if (__FPU_PRESENT == 1)
+#if 1
+    uint32_t result;
+
+    __ASM volatile ("vmrs %0, fpexc" : "=r" (result));
+    return (result);
+#else
+  register uint32_t __regfpexc         __ASM("fpexc");
+  return(__regfpexc);
+#endif
+#else
+   return(0);
+#endif
+}
+
+
+/** \brief  Set FPEXC
+
+    This function assigns the given value to the Floating Point Exception Control register.
+
+    \param [in]    fpscr  Floating Point Exception Control value to set
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_FPEXC(uint32_t fpexc)
+{
+#if (__FPU_PRESENT == 1)
+#if 1
+    __ASM volatile ("vmsr fpexc, %0" : : "r" (fpexc));
+#else
+  register uint32_t __regfpexc         __ASM("fpexc");
+  __regfpexc = (fpexc);
+#endif
+#endif
+}
+
+/** \brief  Get CPACR
+
+    This function returns the current value of the Coprocessor Access Control register.
+
+    \return               Coprocessor Access Control register value
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_CPACR(void)
+{
+#if 1
+    register uint32_t __regCPACR;
+    __ASM volatile ("mrc p15, 0, %0, c1, c0, 2" : "=r" (__regCPACR));
+#else
+    register uint32_t __regCPACR         __ASM("cp15:0:c1:c0:2");
+#endif
+    return __regCPACR;
+}
+
+/** \brief  Set CPACR
+
+    This function assigns the given value to the Coprocessor Access Control register.
+
+    \param [in]    cpacr  Coporcessor Acccess Control value to set
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_CPACR(uint32_t cpacr)
+{
+#if 1
+    __ASM volatile ("mcr p15, 0, %0, c1, c0, 2" : : "r" (cpacr));
+#else
+    register uint32_t __regCPACR         __ASM("cp15:0:c1:c0:2");
+    __regCPACR = cpacr;
+#endif
+    __ISB();
+}
+
+/** \brief  Get CBAR
+
+    This function returns the value of the Configuration Base Address register.
+
+    \return               Configuration Base Address register value
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_CBAR() {
+#if 1
+    register uint32_t __regCBAR;
+    __ASM volatile ("mrc p15, 4, %0, c15, c0, 0" : "=r" (__regCBAR));
+#else
+    register uint32_t __regCBAR         __ASM("cp15:4:c15:c0:0");
+#endif
+    return(__regCBAR);
+}
+
+/** \brief  Get TTBR0
+
+    This function returns the value of the Configuration Base Address register.
+
+    \return               Translation Table Base Register 0 value
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_TTBR0() {
+#if 1
+    register uint32_t __regTTBR0;
+    __ASM volatile ("mrc p15, 0, %0, c2, c0, 0" : "=r" (__regTTBR0));
+#else
+    register uint32_t __regTTBR0        __ASM("cp15:0:c2:c0:0");
+#endif
+    return(__regTTBR0);
+}
+
+/** \brief  Set TTBR0
+
+    This function assigns the given value to the Coprocessor Access Control register.
+
+    \param [in]    ttbr0  Translation Table Base Register 0 value to set
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_TTBR0(uint32_t ttbr0) {
+#if 1
+	__ASM volatile ("mcr p15, 0, %0, c2, c0, 0" : : "r" (ttbr0));
+#else
+    register uint32_t __regTTBR0        __ASM("cp15:0:c2:c0:0");
+    __regTTBR0 = ttbr0;
+#endif
+    __ISB();
+}
+
+/** \brief  Get DACR
+
+    This function returns the value of the Domain Access Control Register.
+
+    \return               Domain Access Control Register value
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_DACR() {
+#if 1
+    register uint32_t __regDACR;
+    __ASM volatile ("mrc p15, 0, %0, c3, c0, 0" : "=r" (__regDACR));
+#else
+    register uint32_t __regDACR         __ASM("cp15:0:c3:c0:0");
+#endif
+    return(__regDACR);
+}
+
+/** \brief  Set DACR
+
+    This function assigns the given value to the Coprocessor Access Control register.
+
+    \param [in]    dacr   Domain Access Control Register value to set
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_DACR(uint32_t dacr) {
+#if 1
+	__ASM volatile ("mcr p15, 0, %0, c3, c0, 0" : : "r" (dacr));
+#else
+    register uint32_t __regDACR         __ASM("cp15:0:c3:c0:0");
+    __regDACR = dacr;
+#endif
+    __ISB();
+}
+
+/******************************** Cache and BTAC enable  ****************************************************/
+
+/** \brief  Set SCTLR
+
+    This function assigns the given value to the System Control Register.
+
+    \param [in]    sctlr  System Control Register, value to set
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_SCTLR(uint32_t sctlr)
+{
+#if 1
+	__ASM volatile ("mcr p15, 0, %0, c1, c0, 0" : : "r" (sctlr));
+#else
+    register uint32_t __regSCTLR         __ASM("cp15:0:c1:c0:0");
+    __regSCTLR = sctlr;
+#endif
+}
+
+/** \brief  Get SCTLR
+
+    This function returns the value of the System Control Register.
+
+    \return               System Control Register value
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_SCTLR() {
+#if 1
+	register uint32_t __regSCTLR;
+	__ASM volatile ("mrc p15, 0, %0, c1, c0, 0" : "=r" (__regSCTLR));
+#else
+    register uint32_t __regSCTLR         __ASM("cp15:0:c1:c0:0");
+#endif
+    return(__regSCTLR);
+}
+
+/** \brief  Enable Caches
+
+    Enable Caches
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_caches(void) {
+    // Set I bit 12 to enable I Cache
+    // Set C bit  2 to enable D Cache
+    __set_SCTLR( __get_SCTLR() | (1 << 12) | (1 << 2));
+}
+
+/** \brief  Disable Caches
+
+    Disable Caches
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_caches(void) {
+    // Clear I bit 12 to disable I Cache
+    // Clear C bit  2 to disable D Cache
+    __set_SCTLR( __get_SCTLR() & ~(1 << 12) & ~(1 << 2));
+    __ISB();
+}
+
+/** \brief  Enable BTAC
+
+    Enable BTAC
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_btac(void) {
+    // Set Z bit 11 to enable branch prediction
+    __set_SCTLR( __get_SCTLR() | (1 << 11));
+    __ISB();
+}
+
+/** \brief  Disable BTAC
+
+    Disable BTAC
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_btac(void) {
+    // Clear Z bit 11 to disable branch prediction
+    __set_SCTLR( __get_SCTLR() & ~(1 << 11));
+}
+
+
+/** \brief  Enable MMU
+
+    Enable MMU
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_mmu(void) {
+    // Set M bit 0 to enable the MMU
+    // Set AFE bit to enable simplified access permissions model
+    // Clear TRE bit to disable TEX remap and A bit to disable strict alignment fault checking
+    __set_SCTLR( (__get_SCTLR() & ~(1 << 28) & ~(1 << 1)) | 1 | (1 << 29));
+    __ISB();
+}
+
+/** \brief  Enable MMU
+
+    Enable MMU
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_mmu(void) {
+    // Clear M bit 0 to disable the MMU
+    __set_SCTLR( __get_SCTLR() & ~1);
+    __ISB();
+}
+
+/******************************** TLB maintenance operations ************************************************/
+/** \brief  Invalidate the whole tlb
+
+    TLBIALL. Invalidate the whole tlb
+ */
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __ca9u_inv_tlb_all(void) {
+#if 1
+	__ASM volatile ("mcr p15, 0, %0, c8, c7, 0" : : "r" (0));
+#else
+    register uint32_t __TLBIALL         __ASM("cp15:0:c8:c7:0");
+    __TLBIALL = 0;
+#endif
+    __DSB();
+    __ISB();
+}
+
+/******************************** BTB maintenance operations ************************************************/
+/** \brief  Invalidate entire branch predictor array
+
+    BPIALL. Branch Predictor Invalidate All.
+ */
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_inv_btac(void) {
+#if 1
+	__ASM volatile ("mcr p15, 0, %0, c7, c5, 6" : : "r" (0));
+#else
+    register uint32_t __BPIALL          __ASM("cp15:0:c7:c5:6");
+    __BPIALL  = 0;
+#endif
+    __DSB();     //ensure completion of the invalidation
+    __ISB();     //ensure instruction fetch path sees new state
+}
+
+
+/******************************** L1 cache operations ******************************************************/
+
+/** \brief  Invalidate the whole I$
+
+    ICIALLU. Instruction Cache Invalidate All to PoU
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_inv_icache_all(void) {
+#if 1
+	__ASM volatile ("mcr p15, 0, %0, c7, c5, 0" : : "r" (0));
+#else
+    register uint32_t __ICIALLU         __ASM("cp15:0:c7:c5:0");
+    __ICIALLU = 0;
+#endif
+    __DSB();     //ensure completion of the invalidation
+    __ISB();     //ensure instruction fetch path sees new I cache state
+}
+
+/** \brief  Clean D$ by MVA
+
+    DCCMVAC. Data cache clean by MVA to PoC
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_clean_dcache_mva(void *va) {
+#if 1
+    __ASM volatile ("mcr p15, 0, %0, c7, c10, 1" : : "r" ((uint32_t)va));
+#else
+    register uint32_t __DCCMVAC         __ASM("cp15:0:c7:c10:1");
+    __DCCMVAC = (uint32_t)va;
+#endif
+    __DMB();     //ensure the ordering of data cache maintenance operations and their effects
+}
+
+/** \brief  Invalidate D$ by MVA
+
+    DCIMVAC. Data cache invalidate by MVA to PoC
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_inv_dcache_mva(void *va) {
+#if 1
+    __ASM volatile ("mcr p15, 0, %0, c7, c6, 1" : : "r" ((uint32_t)va));
+#else
+    register uint32_t __DCIMVAC         __ASM("cp15:0:c7:c6:1");
+    __DCIMVAC = (uint32_t)va;
+#endif
+    __DMB();     //ensure the ordering of data cache maintenance operations and their effects
+}
+
+/** \brief  Clean and Invalidate D$ by MVA
+
+    DCCIMVAC. Data cache clean and invalidate by MVA to PoC
+ */
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_clean_inv_dcache_mva(void *va) {
+#if 1
+    __ASM volatile ("mcr p15, 0, %0, c7, c14, 1" : : "r" ((uint32_t)va));
+#else
+    register uint32_t __DCCIMVAC        __ASM("cp15:0:c7:c14:1");
+    __DCCIMVAC = (uint32_t)va;
+#endif
+    __DMB();     //ensure the ordering of data cache maintenance operations and their effects
+}
+
+/** \brief
+ * Generic mechanism for cleaning/invalidating the entire data or unified cache to the point of coherency.
+ */
+
+/** \brief  __v7_all_cache - helper function
+
+ */
+
+extern void __v7_all_cache(uint32_t op);
+
+
+/** \brief  Invalidate the whole D$
+
+    DCISW. Invalidate by Set/Way
+ */
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_inv_dcache_all(void) {
+    __v7_all_cache(0);
+}
+
+/** \brief  Clean the whole D$
+
+    DCCSW. Clean by Set/Way
+ */
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_clean_dcache_all(void) {
+    __v7_all_cache(1);
+}
+
+/** \brief  Clean and invalidate the whole D$
+
+    DCCISW. Clean and Invalidate by Set/Way
+ */
+
+__attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_clean_inv_dcache_all(void) {
+    __v7_all_cache(2);
+}
+
+#include "core_ca_mmu.h"
+
+#elif (defined (__TASKING__)) /*--------------- TASKING Compiler -----------------*/
+
+#error TASKING Compiler support not implemented for Cortex-A
+
+#endif
+
+/*@} end of CMSIS_Core_RegAccFunctions */
+
+
+#endif /* __CORE_CAFUNC_H__ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/hw/cmsis-core/src/ext/core_caInstr.h
----------------------------------------------------------------------
diff --git a/hw/cmsis-core/src/ext/core_caInstr.h b/hw/cmsis-core/src/ext/core_caInstr.h
new file mode 100644
index 0000000..b1d3435
--- /dev/null
+++ b/hw/cmsis-core/src/ext/core_caInstr.h
@@ -0,0 +1,45 @@
+/**************************************************************************//**
+ * @file     core_caInstr.h
+ * @brief    CMSIS Cortex-A9 Core Peripheral Access Layer Header File
+ * @version
+ * @date     04. December 2012
+ *
+ * @note
+ *
+ ******************************************************************************/
+/* Copyright (c) 2009 - 2012 ARM LIMITED
+
+   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 ARM 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 COPYRIGHT HOLDERS AND 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.
+   ---------------------------------------------------------------------------*/
+
+#ifndef __CORE_CAINSTR_H__
+#define __CORE_CAINSTR_H__
+
+#define __CORTEX_M 0x3
+#include "core_cmInstr.h"
+#undef  __CORTEX_M
+
+#endif
+

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/hw/cmsis-core/src/ext/core_ca_mmu.h
----------------------------------------------------------------------
diff --git a/hw/cmsis-core/src/ext/core_ca_mmu.h b/hw/cmsis-core/src/ext/core_ca_mmu.h
new file mode 100644
index 0000000..1fb99c5
--- /dev/null
+++ b/hw/cmsis-core/src/ext/core_ca_mmu.h
@@ -0,0 +1,848 @@
+;/**************************************************************************//**
+; * @file     core_ca_mmu.h
+; * @brief    MMU Startup File for
+; *           VE_A9_MP Device Series
+; * @version  V1.01
+; * @date     25 March 2013
+; *
+; * @note
+; *
+; ******************************************************************************/
+;/* Copyright (c) 2012 ARM LIMITED
+;
+;   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 ARM 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 COPYRIGHT HOLDERS AND 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.
+;   ---------------------------------------------------------------------------*/
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+#ifndef _MMU_FUNC_H
+#define _MMU_FUNC_H
+
+#define SECTION_DESCRIPTOR      (0x2)
+#define SECTION_MASK            (0xFFFFFFFC)
+
+#define SECTION_TEXCB_MASK      (0xFFFF8FF3)
+#define SECTION_B_SHIFT         (2)
+#define SECTION_C_SHIFT         (3)
+#define SECTION_TEX0_SHIFT      (12)
+#define SECTION_TEX1_SHIFT      (13)
+#define SECTION_TEX2_SHIFT      (14)
+
+#define SECTION_XN_MASK         (0xFFFFFFEF)
+#define SECTION_XN_SHIFT        (4)
+
+#define SECTION_DOMAIN_MASK     (0xFFFFFE1F)
+#define SECTION_DOMAIN_SHIFT    (5)
+
+#define SECTION_P_MASK          (0xFFFFFDFF)
+#define SECTION_P_SHIFT         (9)
+
+#define SECTION_AP_MASK         (0xFFFF73FF)
+#define SECTION_AP_SHIFT        (10)
+#define SECTION_AP2_SHIFT       (15)
+
+#define SECTION_S_MASK          (0xFFFEFFFF)
+#define SECTION_S_SHIFT         (16)
+
+#define SECTION_NG_MASK         (0xFFFDFFFF)
+#define SECTION_NG_SHIFT        (17)
+
+#define SECTION_NS_MASK         (0xFFF7FFFF)
+#define SECTION_NS_SHIFT        (19)
+
+
+#define PAGE_L1_DESCRIPTOR      (0x1)
+#define PAGE_L1_MASK            (0xFFFFFFFC)
+
+#define PAGE_L2_4K_DESC         (0x2)
+#define PAGE_L2_4K_MASK         (0xFFFFFFFD)
+
+#define PAGE_L2_64K_DESC        (0x1)
+#define PAGE_L2_64K_MASK        (0xFFFFFFFC)
+
+#define PAGE_4K_TEXCB_MASK      (0xFFFFFE33)
+#define PAGE_4K_B_SHIFT         (2)
+#define PAGE_4K_C_SHIFT         (3)
+#define PAGE_4K_TEX0_SHIFT      (6)
+#define PAGE_4K_TEX1_SHIFT      (7)
+#define PAGE_4K_TEX2_SHIFT      (8)
+
+#define PAGE_64K_TEXCB_MASK     (0xFFFF8FF3)
+#define PAGE_64K_B_SHIFT        (2)
+#define PAGE_64K_C_SHIFT        (3)
+#define PAGE_64K_TEX0_SHIFT     (12)
+#define PAGE_64K_TEX1_SHIFT     (13)
+#define PAGE_64K_TEX2_SHIFT     (14)
+
+#define PAGE_TEXCB_MASK         (0xFFFF8FF3)
+#define PAGE_B_SHIFT            (2)
+#define PAGE_C_SHIFT            (3)
+#define PAGE_TEX_SHIFT          (12)
+
+#define PAGE_XN_4K_MASK         (0xFFFFFFFE)
+#define PAGE_XN_4K_SHIFT        (0)
+#define PAGE_XN_64K_MASK        (0xFFFF7FFF)
+#define PAGE_XN_64K_SHIFT       (15)
+
+
+#define PAGE_DOMAIN_MASK        (0xFFFFFE1F)
+#define PAGE_DOMAIN_SHIFT       (5)
+
+#define PAGE_P_MASK             (0xFFFFFDFF)
+#define PAGE_P_SHIFT            (9)
+
+#define PAGE_AP_MASK            (0xFFFFFDCF)
+#define PAGE_AP_SHIFT           (4)
+#define PAGE_AP2_SHIFT          (9)
+
+#define PAGE_S_MASK             (0xFFFFFBFF)
+#define PAGE_S_SHIFT            (10)
+
+#define PAGE_NG_MASK            (0xFFFFF7FF)
+#define PAGE_NG_SHIFT           (11)
+
+#define PAGE_NS_MASK            (0xFFFFFFF7)
+#define PAGE_NS_SHIFT           (3)
+
+#define OFFSET_1M               (0x00100000)
+#define OFFSET_64K              (0x00010000)
+#define OFFSET_4K               (0x00001000)
+
+#define DESCRIPTOR_FAULT        (0x00000000)
+
+/* ###########################  MMU Function Access  ########################### */
+/** \ingroup  MMU_FunctionInterface
+    \defgroup MMU_Functions MMU Functions Interface
+  @{
+ */
+
+/* Attributes enumerations */
+
+/* Region size attributes */
+typedef enum
+{
+   SECTION,
+   PAGE_4k,
+   PAGE_64k,
+} mmu_region_size_Type;
+
+/* Region type attributes */
+typedef enum
+{
+   NORMAL,
+   DEVICE,
+   SHARED_DEVICE,
+   NON_SHARED_DEVICE,
+   STRONGLY_ORDERED
+} mmu_memory_Type;
+
+/* Region cacheability attributes */
+typedef enum
+{
+   NON_CACHEABLE,
+   WB_WA,
+   WT,
+   WB_NO_WA,
+} mmu_cacheability_Type;
+
+/* Region parity check attributes */
+typedef enum
+{
+   ECC_DISABLED,
+   ECC_ENABLED,
+} mmu_ecc_check_Type;
+
+/* Region execution attributes */
+typedef enum
+{
+   EXECUTE,
+   NON_EXECUTE,
+} mmu_execute_Type;
+
+/* Region global attributes */
+typedef enum
+{
+   GLOBAL,
+   NON_GLOBAL,
+} mmu_global_Type;
+
+/* Region shareability attributes */
+typedef enum
+{
+   NON_SHARED,
+   SHARED,
+} mmu_shared_Type;
+
+/* Region security attributes */
+typedef enum
+{
+   SECURE,
+   NON_SECURE,
+} mmu_secure_Type;
+
+/* Region access attributes */
+typedef enum
+{
+   NO_ACCESS,
+   RW,
+   READ,
+} mmu_access_Type;
+
+/* Memory Region definition */
+typedef struct RegionStruct {
+    mmu_region_size_Type rg_t;
+    mmu_memory_Type mem_t;
+    uint8_t domain;
+    mmu_cacheability_Type inner_norm_t;
+    mmu_cacheability_Type outer_norm_t;
+    mmu_ecc_check_Type e_t;
+    mmu_execute_Type xn_t;
+    mmu_global_Type g_t;
+    mmu_secure_Type sec_t;
+    mmu_access_Type priv_t;
+    mmu_access_Type user_t;
+    mmu_shared_Type sh_t;
+
+} mmu_region_attributes_Type;
+
+/** \brief  Set section execution-never attribute
+
+    The function sets section execution-never attribute
+
+    \param [out]    descriptor_l1  L1 descriptor.
+    \param [in]                xn  Section execution-never attribute : EXECUTE , NON_EXECUTE.
+
+    \return          0  
+ */
+__STATIC_INLINE int __xn_section(uint32_t *descriptor_l1, mmu_execute_Type xn)
+{
+    *descriptor_l1 &= SECTION_XN_MASK;
+    *descriptor_l1 |= ((xn & 0x1) << SECTION_XN_SHIFT);
+    return 0;
+}
+
+/** \brief  Set section domain
+
+    The function sets section domain
+
+    \param [out]    descriptor_l1  L1 descriptor.
+    \param [in]            domain  Section domain
+
+    \return          0  
+ */
+__STATIC_INLINE int __domain_section(uint32_t *descriptor_l1, uint8_t domain)
+{
+    *descriptor_l1 &= SECTION_DOMAIN_MASK;
+    *descriptor_l1 |= ((domain & 0xF) << SECTION_DOMAIN_SHIFT);
+    return 0;
+}
+
+/** \brief  Set section parity check
+
+    The function sets section parity check
+
+    \param [out]    descriptor_l1  L1 descriptor.
+    \param [in]              p_bit Parity check: ECC_DISABLED, ECC_ENABLED
+
+    \return          0  
+ */
+__STATIC_INLINE int __p_section(uint32_t *descriptor_l1, mmu_ecc_check_Type p_bit)
+{
+    *descriptor_l1 &= SECTION_P_MASK;
+    *descriptor_l1 |= ((p_bit & 0x1) << SECTION_P_SHIFT);
+    return 0;
+}
+
+/** \brief  Set section access privileges
+
+    The function sets section access privileges
+
+    \param [out]    descriptor_l1  L1 descriptor.
+    \param [in]              user  User Level Access: NO_ACCESS, RW, READ
+    \param [in]              priv  Privilege Level Access: NO_ACCESS, RW, READ
+    \param [in]               afe  Access flag enable
+
+    \return          0  
+ */
+__STATIC_INLINE int __ap_section(uint32_t *descriptor_l1, mmu_access_Type user, mmu_access_Type priv,  uint32_t afe)
+{
+    uint32_t ap = 0;
+
+    if (afe == 0) { //full access
+        if ((priv == NO_ACCESS) && (user == NO_ACCESS)) { ap = 0x0; }
+        else if ((priv == RW) && (user == NO_ACCESS))   { ap = 0x1; }
+        else if ((priv == RW) && (user == READ))        { ap = 0x2; }
+        else if ((priv == RW) && (user == RW))          { ap = 0x3; }
+        else if ((priv == READ) && (user == NO_ACCESS)) { ap = 0x5; }
+        else if ((priv == READ) && (user == READ))      { ap = 0x6; }
+    }
+
+    else { //Simplified access
+        if ((priv == RW) && (user == NO_ACCESS))        { ap = 0x1; }
+        else if ((priv == RW) && (user == RW))          { ap = 0x3; }
+        else if ((priv == READ) && (user == NO_ACCESS)) { ap = 0x5; }
+        else if ((priv == READ) && (user == READ))      { ap = 0x7; }
+    }
+
+    *descriptor_l1 &= SECTION_AP_MASK;
+    *descriptor_l1 |= (ap & 0x3) << SECTION_AP_SHIFT;
+    *descriptor_l1 |= ((ap & 0x4)>>2) << SECTION_AP2_SHIFT;
+
+    return 0;
+}
+
+/** \brief  Set section shareability
+
+    The function sets section shareability
+
+    \param [out]    descriptor_l1  L1 descriptor.
+    \param [in]             s_bit  Section shareability: NON_SHARED, SHARED
+
+    \return          0  
+ */
+__STATIC_INLINE int __shared_section(uint32_t *descriptor_l1, mmu_shared_Type s_bit)
+{
+    *descriptor_l1 &= SECTION_S_MASK;
+    *descriptor_l1 |= ((s_bit & 0x1) << SECTION_S_SHIFT);
+    return 0;
+}
+
+/** \brief  Set section Global attribute
+
+    The function sets section Global attribute
+
+    \param [out]    descriptor_l1  L1 descriptor.
+    \param [in]             g_bit  Section attribute: GLOBAL, NON_GLOBAL
+
+    \return          0  
+ */
+__STATIC_INLINE int __global_section(uint32_t *descriptor_l1, mmu_global_Type g_bit)
+{
+    *descriptor_l1 &= SECTION_NG_MASK;
+    *descriptor_l1 |= ((g_bit & 0x1) << SECTION_NG_SHIFT);
+    return 0;
+}
+
+/** \brief  Set section Security attribute
+
+    The function sets section Global attribute
+
+    \param [out]    descriptor_l1  L1 descriptor.
+    \param [in]             s_bit  Section Security attribute: SECURE, NON_SECURE
+
+    \return          0  
+ */
+__STATIC_INLINE int __secure_section(uint32_t *descriptor_l1, mmu_secure_Type s_bit)
+{
+    *descriptor_l1 &= SECTION_NS_MASK;
+    *descriptor_l1 |= ((s_bit & 0x1) << SECTION_NS_SHIFT);
+    return 0;
+}
+
+/* Page 4k or 64k */
+/** \brief  Set 4k/64k page execution-never attribute
+
+    The function sets 4k/64k page execution-never attribute
+
+    \param [out]    descriptor_l2  L2 descriptor.
+    \param [in]                xn  Page execution-never attribute : EXECUTE , NON_EXECUTE.
+    \param [in]              page  Page size: PAGE_4k, PAGE_64k,
+   
+    \return          0  
+ */
+__STATIC_INLINE int __xn_page(uint32_t *descriptor_l2, mmu_execute_Type xn, mmu_region_size_Type page)
+{
+    if (page == PAGE_4k)
+    {
+        *descriptor_l2 &= PAGE_XN_4K_MASK;
+        *descriptor_l2 |= ((xn & 0x1) << PAGE_XN_4K_SHIFT);
+    }
+    else
+    {
+        *descriptor_l2 &= PAGE_XN_64K_MASK;
+        *descriptor_l2 |= ((xn & 0x1) << PAGE_XN_64K_SHIFT);
+    }
+    return 0;
+}
+
+/** \brief  Set 4k/64k page domain
+
+    The function sets 4k/64k page domain
+
+    \param [out]    descriptor_l1  L1 descriptor.
+    \param [in]            domain  Page domain
+
+    \return          0  
+ */
+__STATIC_INLINE int __domain_page(uint32_t *descriptor_l1, uint8_t domain)
+{
+    *descriptor_l1 &= PAGE_DOMAIN_MASK;
+    *descriptor_l1 |= ((domain & 0xf) << PAGE_DOMAIN_SHIFT);
+    return 0;
+}
+
+/** \brief  Set 4k/64k page parity check
+
+    The function sets 4k/64k page parity check
+
+    \param [out]    descriptor_l1  L1 descriptor.
+    \param [in]              p_bit Parity check: ECC_DISABLED, ECC_ENABLED
+
+    \return          0  
+ */
+__STATIC_INLINE int __p_page(uint32_t *descriptor_l1, mmu_ecc_check_Type p_bit)
+{
+    *descriptor_l1 &= SECTION_P_MASK;
+    *descriptor_l1 |= ((p_bit & 0x1) << SECTION_P_SHIFT);
+    return 0;
+}
+
+/** \brief  Set 4k/64k page access privileges
+
+    The function sets 4k/64k page access privileges
+
+    \param [out]    descriptor_l2  L2 descriptor.
+    \param [in]              user  User Level Access: NO_ACCESS, RW, READ
+    \param [in]              priv  Privilege Level Access: NO_ACCESS, RW, READ
+    \param [in]               afe  Access flag enable
+
+    \return          0  
+ */
+__STATIC_INLINE int __ap_page(uint32_t *descriptor_l2, mmu_access_Type user, mmu_access_Type priv,  uint32_t afe)
+{
+    uint32_t ap = 0;
+
+    if (afe == 0) { //full access
+        if ((priv == NO_ACCESS) && (user == NO_ACCESS)) { ap = 0x0; }
+        else if ((priv == RW) && (user == NO_ACCESS))   { ap = 0x1; }
+        else if ((priv == RW) && (user == READ))        { ap = 0x2; }
+        else if ((priv == RW) && (user == RW))          { ap = 0x3; }
+        else if ((priv == READ) && (user == NO_ACCESS)) { ap = 0x5; }
+        else if ((priv == READ) && (user == READ))      { ap = 0x6; }
+    }
+
+    else { //Simplified access
+        if ((priv == RW) && (user == NO_ACCESS))        { ap = 0x1; }
+        else if ((priv == RW) && (user == RW))          { ap = 0x3; }
+        else if ((priv == READ) && (user == NO_ACCESS)) { ap = 0x5; }
+        else if ((priv == READ) && (user == READ))      { ap = 0x7; }
+    }
+
+    *descriptor_l2 &= PAGE_AP_MASK;
+    *descriptor_l2 |= (ap & 0x3) << PAGE_AP_SHIFT;
+    *descriptor_l2 |= ((ap & 0x4)>>2) << PAGE_AP2_SHIFT;
+
+    return 0;
+}
+
+/** \brief  Set 4k/64k page shareability
+
+    The function sets 4k/64k page shareability
+
+    \param [out]    descriptor_l2  L2 descriptor.
+    \param [in]             s_bit  4k/64k page shareability: NON_SHARED, SHARED
+
+    \return          0  
+ */
+__STATIC_INLINE int __shared_page(uint32_t *descriptor_l2, mmu_shared_Type s_bit)
+{
+    *descriptor_l2 &= PAGE_S_MASK;
+    *descriptor_l2 |= ((s_bit & 0x1) << PAGE_S_SHIFT);
+    return 0;
+}
+
+/** \brief  Set 4k/64k page Global attribute
+
+    The function sets 4k/64k page Global attribute
+
+    \param [out]    descriptor_l2  L2 descriptor.
+    \param [in]             g_bit  4k/64k page attribute: GLOBAL, NON_GLOBAL
+
+    \return          0  
+ */
+__STATIC_INLINE int __global_page(uint32_t *descriptor_l2, mmu_global_Type g_bit)
+{
+    *descriptor_l2 &= PAGE_NG_MASK;
+    *descriptor_l2 |= ((g_bit & 0x1) << PAGE_NG_SHIFT);
+    return 0;
+}
+
+/** \brief  Set 4k/64k page Security attribute
+
+    The function sets 4k/64k page Global attribute
+
+    \param [out]    descriptor_l1  L1 descriptor.
+    \param [in]             s_bit  4k/64k page Security attribute: SECURE, NON_SECURE
+
+    \return          0  
+ */
+__STATIC_INLINE int __secure_page(uint32_t *descriptor_l1, mmu_secure_Type s_bit)
+{
+    *descriptor_l1 &= PAGE_NS_MASK;
+    *descriptor_l1 |= ((s_bit & 0x1) << PAGE_NS_SHIFT);
+    return 0;
+}
+
+
+/** \brief  Set Section memory attributes
+
+    The function sets section memory attributes
+
+    \param [out]    descriptor_l1  L1 descriptor.
+    \param [in]               mem  Section memory type: NORMAL, DEVICE, SHARED_DEVICE, NON_SHARED_DEVICE, STRONGLY_ORDERED
+    \param [in]             outer  Outer cacheability: NON_CACHEABLE, WB_WA, WT, WB_NO_WA,
+    \param [in]             inner  Inner cacheability: NON_CACHEABLE, WB_WA, WT, WB_NO_WA,
+
+    \return          0  
+ */
+__STATIC_INLINE int __memory_section(uint32_t *descriptor_l1, mmu_memory_Type mem, mmu_cacheability_Type outer, mmu_cacheability_Type inner)
+{
+    *descriptor_l1 &= SECTION_TEXCB_MASK;
+
+    if (STRONGLY_ORDERED == mem)
+    {
+        return 0;
+    }
+    else if (SHARED_DEVICE == mem)
+    {
+        *descriptor_l1 |= (1 << SECTION_B_SHIFT);
+    }
+    else if (NON_SHARED_DEVICE == mem)
+    {
+        *descriptor_l1 |= (1 << SECTION_TEX1_SHIFT);
+    }
+    else if (NORMAL == mem)
+    {
+           *descriptor_l1 |= 1 << SECTION_TEX2_SHIFT;
+           switch(inner)
+           {
+            case NON_CACHEABLE:
+            break;
+            case WB_WA:
+                *descriptor_l1 |= (1 << SECTION_B_SHIFT);
+                break;
+            case WT:
+                *descriptor_l1 |= 1 << SECTION_C_SHIFT;
+                break;
+            case WB_NO_WA:
+                *descriptor_l1 |= (1 << SECTION_B_SHIFT) | (1 << SECTION_C_SHIFT);
+                break;
+        }
+        switch(outer)
+        {
+            case NON_CACHEABLE:
+             break;
+            case WB_WA:
+                *descriptor_l1 |= (1 << SECTION_TEX0_SHIFT);
+                break;
+            case WT:
+                *descriptor_l1 |= 1 << SECTION_TEX1_SHIFT;
+                break;
+            case WB_NO_WA:
+                *descriptor_l1 |= (1 << SECTION_TEX0_SHIFT) | (1 << SECTION_TEX0_SHIFT);
+                break;
+        }
+    }
+
+    return 0;
+}
+
+/** \brief  Set 4k/64k page memory attributes
+
+    The function sets 4k/64k page memory attributes
+
+    \param [out]    descriptor_l2  L2 descriptor.
+    \param [in]               mem  4k/64k page memory type: NORMAL, DEVICE, SHARED_DEVICE, NON_SHARED_DEVICE, STRONGLY_ORDERED
+    \param [in]             outer  Outer cacheability: NON_CACHEABLE, WB_WA, WT, WB_NO_WA,
+    \param [in]             inner  Inner cacheability: NON_CACHEABLE, WB_WA, WT, WB_NO_WA,
+
+    \return          0  
+ */
+__STATIC_INLINE int __memory_page(uint32_t *descriptor_l2, mmu_memory_Type mem, mmu_cacheability_Type outer, mmu_cacheability_Type inner, mmu_region_size_Type page)
+{
+    *descriptor_l2 &= PAGE_4K_TEXCB_MASK;
+
+    if (page == PAGE_64k)
+    {
+        //same as section
+        __memory_section(descriptor_l2, mem, outer, inner);
+    }
+    else
+    {
+        if (STRONGLY_ORDERED == mem)
+        {
+            return 0;
+        }
+        else if (SHARED_DEVICE == mem)
+        {
+            *descriptor_l2 |= (1 << PAGE_4K_B_SHIFT);
+        }
+        else if (NON_SHARED_DEVICE == mem)
+        {
+             *descriptor_l2 |= (1 << PAGE_4K_TEX1_SHIFT);
+        }
+        else if (NORMAL == mem)
+        {
+            *descriptor_l2 |= 1 << PAGE_4K_TEX2_SHIFT;
+            switch(inner)
+            {
+                case NON_CACHEABLE:
+                break;
+                case WB_WA:
+                     *descriptor_l2 |= (1 << PAGE_4K_B_SHIFT);
+                     break;
+                case WT:
+                    *descriptor_l2 |= 1 << PAGE_4K_C_SHIFT;
+                     break;
+                case WB_NO_WA:
+                    *descriptor_l2 |= (1 << PAGE_4K_B_SHIFT) | (1 << PAGE_4K_C_SHIFT);
+                    break;
+            }
+            switch(outer)
+            {
+                case NON_CACHEABLE:
+                break;
+                case WB_WA:
+                      *descriptor_l2 |= (1 << PAGE_4K_TEX0_SHIFT);
+                    break;
+                case WT:
+                     *descriptor_l2 |= 1 << PAGE_4K_TEX1_SHIFT;
+                    break;
+                case WB_NO_WA:
+                    *descriptor_l2 |= (1 << PAGE_4K_TEX0_SHIFT) | (1 << PAGE_4K_TEX0_SHIFT);
+                    break;
+            }
+        }
+    }
+
+    return 0;
+}
+
+/** \brief  Create a L1 section descriptor
+
+    The function creates a section descriptor.
+    
+    Assumptions:
+    - 16MB super sections not suported
+    - TEX remap disabled, so memory type and attributes are described directly by bits in the descriptor
+    - Functions always return 0
+
+    \param [out]       descriptor  L1 descriptor
+    \param [out]      descriptor2  L2 descriptor
+    \param [in]               reg  Section attributes
+
+    \return          0  
+ */
+__STATIC_INLINE int __get_section_descriptor(uint32_t *descriptor, mmu_region_attributes_Type reg)
+{
+    *descriptor  = 0;
+
+   __memory_section(descriptor, reg.mem_t, reg.outer_norm_t, reg.inner_norm_t);
+   __xn_section(descriptor,reg.xn_t);
+   __domain_section(descriptor, reg.domain);
+   __p_section(descriptor, reg.e_t);
+   __ap_section(descriptor, reg.priv_t, reg.user_t, 1);
+   __shared_section(descriptor,reg.sh_t);
+   __global_section(descriptor,reg.g_t);
+   __secure_section(descriptor,reg.sec_t);
+   *descriptor &= SECTION_MASK;
+   *descriptor |= SECTION_DESCRIPTOR;
+
+   return 0;
+
+}
+
+
+/** \brief  Create a L1 and L2 4k/64k page descriptor
+
+    The function creates a 4k/64k page descriptor.
+    Assumptions:
+    - TEX remap disabled, so memory type and attributes are described directly by bits in the descriptor
+    - Functions always return 0
+
+    \param [out]       descriptor  L1 descriptor
+    \param [out]      descriptor2  L2 descriptor
+    \param [in]               reg  4k/64k page attributes
+
+    \return          0  
+ */
+__STATIC_INLINE int __get_page_descriptor(uint32_t *descriptor, uint32_t *descriptor2, mmu_region_attributes_Type reg)
+{
+    *descriptor  = 0;
+    *descriptor2 = 0;
+
+    switch (reg.rg_t)
+    {
+        case PAGE_4k:
+            __memory_page(descriptor2, reg.mem_t, reg.outer_norm_t, reg.inner_norm_t, PAGE_4k);
+            __xn_page(descriptor2, reg.xn_t, PAGE_4k);
+            __domain_page(descriptor, reg.domain);
+            __p_page(descriptor, reg.e_t);
+            __ap_page(descriptor2, reg.priv_t, reg.user_t, 1);
+            __shared_page(descriptor2,reg.sh_t);
+            __global_page(descriptor2,reg.g_t);
+            __secure_page(descriptor,reg.sec_t);
+            *descriptor &= PAGE_L1_MASK;
+            *descriptor |= PAGE_L1_DESCRIPTOR;
+            *descriptor2 &= PAGE_L2_4K_MASK;
+            *descriptor2 |= PAGE_L2_4K_DESC;
+            break;
+
+        case PAGE_64k:
+            __memory_page(descriptor2, reg.mem_t, reg.outer_norm_t, reg.inner_norm_t, PAGE_64k);
+            __xn_page(descriptor2, reg.xn_t, PAGE_64k);
+            __domain_page(descriptor, reg.domain);
+            __p_page(descriptor, reg.e_t);
+            __ap_page(descriptor2, reg.priv_t, reg.user_t, 1);
+            __shared_page(descriptor2,reg.sh_t);
+            __global_page(descriptor2,reg.g_t);
+            __secure_page(descriptor,reg.sec_t);
+            *descriptor &= PAGE_L1_MASK;
+            *descriptor |= PAGE_L1_DESCRIPTOR;
+            *descriptor2 &= PAGE_L2_64K_MASK;
+            *descriptor2 |= PAGE_L2_64K_DESC;
+            break;
+
+        case SECTION:
+            //error
+            break;    
+
+    }
+
+   return 0;
+
+}
+
+/** \brief  Create a 1MB Section
+
+    \param [in]               ttb  Translation table base address
+    \param [in]      base_address  Section base address
+    \param [in]             count  Number of sections to create
+    \param [in]     descriptor_l1  L1 descriptor (region attributes) 
+
+ */
+__STATIC_INLINE void __TTSection(uint32_t *ttb, uint32_t base_address, uint32_t count, uint32_t descriptor_l1)
+{
+    uint32_t offset;
+    uint32_t entry;
+    uint32_t i;
+
+    offset = base_address >> 20;
+    entry  = (base_address & 0xFFF00000) | descriptor_l1;
+
+    //4 bytes aligned
+    ttb = ttb + offset;
+
+    for (i = 0; i < count; i++ )
+    {
+        //4 bytes aligned
+       *ttb++ = entry;
+       entry += OFFSET_1M;
+    }
+}
+
+/** \brief  Create a 4k page entry
+
+    \param [in]               ttb  L1 table base address
+    \param [in]      base_address  4k base address
+    \param [in]             count  Number of 4k pages to create
+    \param [in]     descriptor_l1  L1 descriptor (region attributes) 
+    \param [in]            ttb_l2  L2 table base address
+    \param [in]     descriptor_l2  L2 descriptor (region attributes) 
+
+ */
+__STATIC_INLINE void __TTPage_4k(uint32_t *ttb, uint32_t base_address, uint32_t count, uint32_t descriptor_l1, uint32_t *ttb_l2, uint32_t descriptor_l2 )
+{
+
+    uint32_t offset, offset2;
+    uint32_t entry, entry2;
+    uint32_t i;
+
+
+    offset = base_address >> 20;
+    entry  = ((int)ttb_l2 & 0xFFFFFC00) | descriptor_l1;
+
+    //4 bytes aligned
+    ttb += offset;
+    //create l1_entry
+    *ttb = entry;
+
+    offset2 = (base_address & 0xff000) >> 12;
+    ttb_l2 += offset2;
+    entry2 = (base_address & 0xFFFFF000) | descriptor_l2;
+    for (i = 0; i < count; i++ )
+    {
+        //4 bytes aligned
+       *ttb_l2++ = entry2;
+       entry2 += OFFSET_4K;
+    }
+}
+
+/** \brief  Create a 64k page entry
+
+    \param [in]               ttb  L1 table base address
+    \param [in]      base_address  64k base address
+    \param [in]             count  Number of 64k pages to create
+    \param [in]     descriptor_l1  L1 descriptor (region attributes) 
+    \param [in]            ttb_l2  L2 table base address
+    \param [in]     descriptor_l2  L2 descriptor (region attributes) 
+
+ */
+__STATIC_INLINE void __TTPage_64k(uint32_t *ttb, uint32_t base_address, uint32_t count, uint32_t descriptor_l1, uint32_t *ttb_l2, uint32_t descriptor_l2 )
+{
+    uint32_t offset, offset2;
+    uint32_t entry, entry2;
+    uint32_t i,j;
+
+
+    offset = base_address >> 20;
+    entry  = ((int)ttb_l2 & 0xFFFFFC00) | descriptor_l1;
+
+    //4 bytes aligned
+    ttb += offset;
+    //create l1_entry
+    *ttb = entry;
+
+    offset2 = (base_address & 0xff000) >> 12;
+    ttb_l2 += offset2;
+    entry2 = (base_address & 0xFFFF0000) | descriptor_l2;
+    for (i = 0; i < count; i++ )
+    {
+        //create 16 entries
+        for (j = 0; j < 16; j++)
+            //4 bytes aligned
+            *ttb_l2++ = entry2;
+        entry2 += OFFSET_64K;
+    }
+}
+
+/*@} end of MMU_Functions */
+#endif
+
+#ifdef __cplusplus
+}
+#endif


[40/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/hw/cmsis-core/src/ext/core_cm3.h
----------------------------------------------------------------------
diff --git a/hw/cmsis-core/src/ext/core_cm3.h b/hw/cmsis-core/src/ext/core_cm3.h
new file mode 100644
index 0000000..122c9aa
--- /dev/null
+++ b/hw/cmsis-core/src/ext/core_cm3.h
@@ -0,0 +1,1627 @@
+/**************************************************************************//**
+ * @file     core_cm3.h
+ * @brief    CMSIS Cortex-M3 Core Peripheral Access Layer Header File
+ * @version  V3.20
+ * @date     25. February 2013
+ *
+ * @note
+ *
+ ******************************************************************************/
+/* Copyright (c) 2009 - 2013 ARM LIMITED
+
+   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 ARM 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 COPYRIGHT HOLDERS AND CONTRIBUTORS BE
+   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+   POSSIBILITY OF SUCH DAMAGE.
+   ---------------------------------------------------------------------------*/
+
+
+#if defined ( __ICCARM__ )
+ #pragma system_include  /* treat file as system include file for MISRA check */
+#endif
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+#ifndef __CORE_CM3_H_GENERIC
+#define __CORE_CM3_H_GENERIC
+
+/** \page CMSIS_MISRA_Exceptions  MISRA-C:2004 Compliance Exceptions
+  CMSIS violates the following MISRA-C:2004 rules:
+
+   \li Required Rule 8.5, object/function definition in header file.<br>
+     Function definitions in header files are used to allow 'inlining'.
+
+   \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.<br>
+     Unions are used for effective representation of core registers.
+
+   \li Advisory Rule 19.7, Function-like macro defined.<br>
+     Function-like macros are used to allow more efficient code.
+ */
+
+
+/*******************************************************************************
+ *                 CMSIS definitions
+ ******************************************************************************/
+/** \ingroup Cortex_M3
+  @{
+ */
+
+/*  CMSIS CM3 definitions */
+#define __CM3_CMSIS_VERSION_MAIN  (0x03)                                   /*!< [31:16] CMSIS HAL main version   */
+#define __CM3_CMSIS_VERSION_SUB   (0x20)                                   /*!< [15:0]  CMSIS HAL sub version    */
+#define __CM3_CMSIS_VERSION       ((__CM3_CMSIS_VERSION_MAIN << 16) | \
+                                    __CM3_CMSIS_VERSION_SUB          )     /*!< CMSIS HAL version number         */
+
+#define __CORTEX_M                (0x03)                                   /*!< Cortex-M Core                    */
+
+
+#if   defined ( __CC_ARM )
+  #define __ASM            __asm                                      /*!< asm keyword for ARM Compiler          */
+  #define __INLINE         __inline                                   /*!< inline keyword for ARM Compiler       */
+  #define __STATIC_INLINE  static __inline
+
+#elif defined ( __ICCARM__ )
+  #define __ASM            __asm                                      /*!< asm keyword for IAR Compiler          */
+  #define __INLINE         inline                                     /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */
+  #define __STATIC_INLINE  static inline
+
+#elif defined ( __TMS470__ )
+  #define __ASM            __asm                                      /*!< asm keyword for TI CCS Compiler       */
+  #define __STATIC_INLINE  static inline
+
+#elif defined ( __GNUC__ )
+  #define __ASM            __asm                                      /*!< asm keyword for GNU Compiler          */
+  #define __INLINE         inline                                     /*!< inline keyword for GNU Compiler       */
+  #define __STATIC_INLINE  static inline
+
+#elif defined ( __TASKING__ )
+  #define __ASM            __asm                                      /*!< asm keyword for TASKING Compiler      */
+  #define __INLINE         inline                                     /*!< inline keyword for TASKING Compiler   */
+  #define __STATIC_INLINE  static inline
+
+#endif
+
+/** __FPU_USED indicates whether an FPU is used or not. This core does not support an FPU at all
+*/
+#define __FPU_USED       0
+
+#if defined ( __CC_ARM )
+  #if defined __TARGET_FPU_VFP
+    #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
+  #endif
+
+#elif defined ( __ICCARM__ )
+  #if defined __ARMVFP__
+    #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
+  #endif
+
+#elif defined ( __TMS470__ )
+  #if defined __TI__VFP_SUPPORT____
+    #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
+  #endif
+
+#elif defined ( __GNUC__ )
+  #if defined (__VFP_FP__) && !defined(__SOFTFP__)
+    #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
+  #endif
+
+#elif defined ( __TASKING__ )
+  #if defined __FPU_VFP__
+    #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
+  #endif
+#endif
+
+#include <stdint.h>                      /* standard types definitions                      */
+#include <core_cmInstr.h>                /* Core Instruction Access                         */
+#include <core_cmFunc.h>                 /* Core Function Access                            */
+
+#endif /* __CORE_CM3_H_GENERIC */
+
+#ifndef __CMSIS_GENERIC
+
+#ifndef __CORE_CM3_H_DEPENDANT
+#define __CORE_CM3_H_DEPENDANT
+
+/* check device defines and use defaults */
+#if defined __CHECK_DEVICE_DEFINES
+  #ifndef __CM3_REV
+    #define __CM3_REV               0x0200
+    #warning "__CM3_REV not defined in device header file; using default!"
+  #endif
+
+  #ifndef __MPU_PRESENT
+    #define __MPU_PRESENT             0
+    #warning "__MPU_PRESENT not defined in device header file; using default!"
+  #endif
+
+  #ifndef __NVIC_PRIO_BITS
+    #define __NVIC_PRIO_BITS          4
+    #warning "__NVIC_PRIO_BITS not defined in device header file; using default!"
+  #endif
+
+  #ifndef __Vendor_SysTickConfig
+    #define __Vendor_SysTickConfig    0
+    #warning "__Vendor_SysTickConfig not defined in device header file; using default!"
+  #endif
+#endif
+
+/* IO definitions (access restrictions to peripheral registers) */
+/**
+    \defgroup CMSIS_glob_defs CMSIS Global Defines
+
+    <strong>IO Type Qualifiers</strong> are used
+    \li to specify the access to peripheral variables.
+    \li for automatic generation of peripheral register debug information.
+*/
+#ifdef __cplusplus
+  #define   __I     volatile             /*!< Defines 'read only' permissions                 */
+#else
+  #define   __I     volatile const       /*!< Defines 'read only' permissions                 */
+#endif
+#define     __O     volatile             /*!< Defines 'write only' permissions                */
+#define     __IO    volatile             /*!< Defines 'read / write' permissions              */
+
+/*@} end of group Cortex_M3 */
+
+
+
+/*******************************************************************************
+ *                 Register Abstraction
+  Core Register contain:
+  - Core Register
+  - Core NVIC Register
+  - Core SCB Register
+  - Core SysTick Register
+  - Core Debug Register
+  - Core MPU Register
+ ******************************************************************************/
+/** \defgroup CMSIS_core_register Defines and Type Definitions
+    \brief Type definitions and defines for Cortex-M processor based devices.
+*/
+
+/** \ingroup    CMSIS_core_register
+    \defgroup   CMSIS_CORE  Status and Control Registers
+    \brief  Core Register type definitions.
+  @{
+ */
+
+/** \brief  Union type to access the Application Program Status Register (APSR).
+ */
+typedef union
+{
+  struct
+  {
+#if (__CORTEX_M != 0x04)
+    uint32_t _reserved0:27;              /*!< bit:  0..26  Reserved                           */
+#else
+    uint32_t _reserved0:16;              /*!< bit:  0..15  Reserved                           */
+    uint32_t GE:4;                       /*!< bit: 16..19  Greater than or Equal flags        */
+    uint32_t _reserved1:7;               /*!< bit: 20..26  Reserved                           */
+#endif
+    uint32_t Q:1;                        /*!< bit:     27  Saturation condition flag          */
+    uint32_t V:1;                        /*!< bit:     28  Overflow condition code flag       */
+    uint32_t C:1;                        /*!< bit:     29  Carry condition code flag          */
+    uint32_t Z:1;                        /*!< bit:     30  Zero condition code flag           */
+    uint32_t N:1;                        /*!< bit:     31  Negative condition code flag       */
+  } b;                                   /*!< Structure used for bit  access                  */
+  uint32_t w;                            /*!< Type      used for word access                  */
+} APSR_Type;
+
+
+/** \brief  Union type to access the Interrupt Program Status Register (IPSR).
+ */
+typedef union
+{
+  struct
+  {
+    uint32_t ISR:9;                      /*!< bit:  0.. 8  Exception number                   */
+    uint32_t _reserved0:23;              /*!< bit:  9..31  Reserved                           */
+  } b;                                   /*!< Structure used for bit  access                  */
+  uint32_t w;                            /*!< Type      used for word access                  */
+} IPSR_Type;
+
+
+/** \brief  Union type to access the Special-Purpose Program Status Registers (xPSR).
+ */
+typedef union
+{
+  struct
+  {
+    uint32_t ISR:9;                      /*!< bit:  0.. 8  Exception number                   */
+#if (__CORTEX_M != 0x04)
+    uint32_t _reserved0:15;              /*!< bit:  9..23  Reserved                           */
+#else
+    uint32_t _reserved0:7;               /*!< bit:  9..15  Reserved                           */
+    uint32_t GE:4;                       /*!< bit: 16..19  Greater than or Equal flags        */
+    uint32_t _reserved1:4;               /*!< bit: 20..23  Reserved                           */
+#endif
+    uint32_t T:1;                        /*!< bit:     24  Thumb bit        (read 0)          */
+    uint32_t IT:2;                       /*!< bit: 25..26  saved IT state   (read 0)          */
+    uint32_t Q:1;                        /*!< bit:     27  Saturation condition flag          */
+    uint32_t V:1;                        /*!< bit:     28  Overflow condition code flag       */
+    uint32_t C:1;                        /*!< bit:     29  Carry condition code flag          */
+    uint32_t Z:1;                        /*!< bit:     30  Zero condition code flag           */
+    uint32_t N:1;                        /*!< bit:     31  Negative condition code flag       */
+  } b;                                   /*!< Structure used for bit  access                  */
+  uint32_t w;                            /*!< Type      used for word access                  */
+} xPSR_Type;
+
+
+/** \brief  Union type to access the Control Registers (CONTROL).
+ */
+typedef union
+{
+  struct
+  {
+    uint32_t nPRIV:1;                    /*!< bit:      0  Execution privilege in Thread mode */
+    uint32_t SPSEL:1;                    /*!< bit:      1  Stack to be used                   */
+    uint32_t FPCA:1;                     /*!< bit:      2  FP extension active flag           */
+    uint32_t _reserved0:29;              /*!< bit:  3..31  Reserved                           */
+  } b;                                   /*!< Structure used for bit  access                  */
+  uint32_t w;                            /*!< Type      used for word access                  */
+} CONTROL_Type;
+
+/*@} end of group CMSIS_CORE */
+
+
+/** \ingroup    CMSIS_core_register
+    \defgroup   CMSIS_NVIC  Nested Vectored Interrupt Controller (NVIC)
+    \brief      Type definitions for the NVIC Registers
+  @{
+ */
+
+/** \brief  Structure type to access the Nested Vectored Interrupt Controller (NVIC).
+ */
+typedef struct
+{
+  __IO uint32_t ISER[8];                 /*!< Offset: 0x000 (R/W)  Interrupt Set Enable Register           */
+       uint32_t RESERVED0[24];
+  __IO uint32_t ICER[8];                 /*!< Offset: 0x080 (R/W)  Interrupt Clear Enable Register         */
+       uint32_t RSERVED1[24];
+  __IO uint32_t ISPR[8];                 /*!< Offset: 0x100 (R/W)  Interrupt Set Pending Register          */
+       uint32_t RESERVED2[24];
+  __IO uint32_t ICPR[8];                 /*!< Offset: 0x180 (R/W)  Interrupt Clear Pending Register        */
+       uint32_t RESERVED3[24];
+  __IO uint32_t IABR[8];                 /*!< Offset: 0x200 (R/W)  Interrupt Active bit Register           */
+       uint32_t RESERVED4[56];
+  __IO uint8_t  IP[240];                 /*!< Offset: 0x300 (R/W)  Interrupt Priority Register (8Bit wide) */
+       uint32_t RESERVED5[644];
+  __O  uint32_t STIR;                    /*!< Offset: 0xE00 ( /W)  Software Trigger Interrupt Register     */
+}  NVIC_Type;
+
+/* Software Triggered Interrupt Register Definitions */
+#define NVIC_STIR_INTID_Pos                 0                                          /*!< STIR: INTLINESNUM Position */
+#define NVIC_STIR_INTID_Msk                (0x1FFUL << NVIC_STIR_INTID_Pos)            /*!< STIR: INTLINESNUM Mask */
+
+/*@} end of group CMSIS_NVIC */
+
+
+/** \ingroup  CMSIS_core_register
+    \defgroup CMSIS_SCB     System Control Block (SCB)
+    \brief      Type definitions for the System Control Block Registers
+  @{
+ */
+
+/** \brief  Structure type to access the System Control Block (SCB).
+ */
+typedef struct
+{
+  __I  uint32_t CPUID;                   /*!< Offset: 0x000 (R/ )  CPUID Base Register                                   */
+  __IO uint32_t ICSR;                    /*!< Offset: 0x004 (R/W)  Interrupt Control and State Register                  */
+  __IO uint32_t VTOR;                    /*!< Offset: 0x008 (R/W)  Vector Table Offset Register                          */
+  __IO uint32_t AIRCR;                   /*!< Offset: 0x00C (R/W)  Application Interrupt and Reset Control Register      */
+  __IO uint32_t SCR;                     /*!< Offset: 0x010 (R/W)  System Control Register                               */
+  __IO uint32_t CCR;                     /*!< Offset: 0x014 (R/W)  Configuration Control Register                        */
+  __IO uint8_t  SHP[12];                 /*!< Offset: 0x018 (R/W)  System Handlers Priority Registers (4-7, 8-11, 12-15) */
+  __IO uint32_t SHCSR;                   /*!< Offset: 0x024 (R/W)  System Handler Control and State Register             */
+  __IO uint32_t CFSR;                    /*!< Offset: 0x028 (R/W)  Configurable Fault Status Register                    */
+  __IO uint32_t HFSR;                    /*!< Offset: 0x02C (R/W)  HardFault Status Register                             */
+  __IO uint32_t DFSR;                    /*!< Offset: 0x030 (R/W)  Debug Fault Status Register                           */
+  __IO uint32_t MMFAR;                   /*!< Offset: 0x034 (R/W)  MemManage Fault Address Register                      */
+  __IO uint32_t BFAR;                    /*!< Offset: 0x038 (R/W)  BusFault Address Register                             */
+  __IO uint32_t AFSR;                    /*!< Offset: 0x03C (R/W)  Auxiliary Fault Status Register                       */
+  __I  uint32_t PFR[2];                  /*!< Offset: 0x040 (R/ )  Processor Feature Register                            */
+  __I  uint32_t DFR;                     /*!< Offset: 0x048 (R/ )  Debug Feature Register                                */
+  __I  uint32_t ADR;                     /*!< Offset: 0x04C (R/ )  Auxiliary Feature Register                            */
+  __I  uint32_t MMFR[4];                 /*!< Offset: 0x050 (R/ )  Memory Model Feature Register                         */
+  __I  uint32_t ISAR[5];                 /*!< Offset: 0x060 (R/ )  Instruction Set Attributes Register                   */
+       uint32_t RESERVED0[5];
+  __IO uint32_t CPACR;                   /*!< Offset: 0x088 (R/W)  Coprocessor Access Control Register                   */
+} SCB_Type;
+
+/* SCB CPUID Register Definitions */
+#define SCB_CPUID_IMPLEMENTER_Pos          24                                             /*!< SCB CPUID: IMPLEMENTER Position */
+#define SCB_CPUID_IMPLEMENTER_Msk          (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos)          /*!< SCB CPUID: IMPLEMENTER Mask */
+
+#define SCB_CPUID_VARIANT_Pos              20                                             /*!< SCB CPUID: VARIANT Position */
+#define SCB_CPUID_VARIANT_Msk              (0xFUL << SCB_CPUID_VARIANT_Pos)               /*!< SCB CPUID: VARIANT Mask */
+
+#define SCB_CPUID_ARCHITECTURE_Pos         16                                             /*!< SCB CPUID: ARCHITECTURE Position */
+#define SCB_CPUID_ARCHITECTURE_Msk         (0xFUL << SCB_CPUID_ARCHITECTURE_Pos)          /*!< SCB CPUID: ARCHITECTURE Mask */
+
+#define SCB_CPUID_PARTNO_Pos                4                                             /*!< SCB CPUID: PARTNO Position */
+#define SCB_CPUID_PARTNO_Msk               (0xFFFUL << SCB_CPUID_PARTNO_Pos)              /*!< SCB CPUID: PARTNO Mask */
+
+#define SCB_CPUID_REVISION_Pos              0                                             /*!< SCB CPUID: REVISION Position */
+#define SCB_CPUID_REVISION_Msk             (0xFUL << SCB_CPUID_REVISION_Pos)              /*!< SCB CPUID: REVISION Mask */
+
+/* SCB Interrupt Control State Register Definitions */
+#define SCB_ICSR_NMIPENDSET_Pos            31                                             /*!< SCB ICSR: NMIPENDSET Position */
+#define SCB_ICSR_NMIPENDSET_Msk            (1UL << SCB_ICSR_NMIPENDSET_Pos)               /*!< SCB ICSR: NMIPENDSET Mask */
+
+#define SCB_ICSR_PENDSVSET_Pos             28                                             /*!< SCB ICSR: PENDSVSET Position */
+#define SCB_ICSR_PENDSVSET_Msk             (1UL << SCB_ICSR_PENDSVSET_Pos)                /*!< SCB ICSR: PENDSVSET Mask */
+
+#define SCB_ICSR_PENDSVCLR_Pos             27                                             /*!< SCB ICSR: PENDSVCLR Position */
+#define SCB_ICSR_PENDSVCLR_Msk             (1UL << SCB_ICSR_PENDSVCLR_Pos)                /*!< SCB ICSR: PENDSVCLR Mask */
+
+#define SCB_ICSR_PENDSTSET_Pos             26                                             /*!< SCB ICSR: PENDSTSET Position */
+#define SCB_ICSR_PENDSTSET_Msk             (1UL << SCB_ICSR_PENDSTSET_Pos)                /*!< SCB ICSR: PENDSTSET Mask */
+
+#define SCB_ICSR_PENDSTCLR_Pos             25                                             /*!< SCB ICSR: PENDSTCLR Position */
+#define SCB_ICSR_PENDSTCLR_Msk             (1UL << SCB_ICSR_PENDSTCLR_Pos)                /*!< SCB ICSR: PENDSTCLR Mask */
+
+#define SCB_ICSR_ISRPREEMPT_Pos            23                                             /*!< SCB ICSR: ISRPREEMPT Position */
+#define SCB_ICSR_ISRPREEMPT_Msk            (1UL << SCB_ICSR_ISRPREEMPT_Pos)               /*!< SCB ICSR: ISRPREEMPT Mask */
+
+#define SCB_ICSR_ISRPENDING_Pos            22                                             /*!< SCB ICSR: ISRPENDING Position */
+#define SCB_ICSR_ISRPENDING_Msk            (1UL << SCB_ICSR_ISRPENDING_Pos)               /*!< SCB ICSR: ISRPENDING Mask */
+
+#define SCB_ICSR_VECTPENDING_Pos           12                                             /*!< SCB ICSR: VECTPENDING Position */
+#define SCB_ICSR_VECTPENDING_Msk           (0x1FFUL << SCB_ICSR_VECTPENDING_Pos)          /*!< SCB ICSR: VECTPENDING Mask */
+
+#define SCB_ICSR_RETTOBASE_Pos             11                                             /*!< SCB ICSR: RETTOBASE Position */
+#define SCB_ICSR_RETTOBASE_Msk             (1UL << SCB_ICSR_RETTOBASE_Pos)                /*!< SCB ICSR: RETTOBASE Mask */
+
+#define SCB_ICSR_VECTACTIVE_Pos             0                                             /*!< SCB ICSR: VECTACTIVE Position */
+#define SCB_ICSR_VECTACTIVE_Msk            (0x1FFUL << SCB_ICSR_VECTACTIVE_Pos)           /*!< SCB ICSR: VECTACTIVE Mask */
+
+/* SCB Vector Table Offset Register Definitions */
+#if (__CM3_REV < 0x0201)                   /* core r2p1 */
+#define SCB_VTOR_TBLBASE_Pos               29                                             /*!< SCB VTOR: TBLBASE Position */
+#define SCB_VTOR_TBLBASE_Msk               (1UL << SCB_VTOR_TBLBASE_Pos)                  /*!< SCB VTOR: TBLBASE Mask */
+
+#define SCB_VTOR_TBLOFF_Pos                 7                                             /*!< SCB VTOR: TBLOFF Position */
+#define SCB_VTOR_TBLOFF_Msk                (0x3FFFFFUL << SCB_VTOR_TBLOFF_Pos)            /*!< SCB VTOR: TBLOFF Mask */
+#else
+#define SCB_VTOR_TBLOFF_Pos                 7                                             /*!< SCB VTOR: TBLOFF Position */
+#define SCB_VTOR_TBLOFF_Msk                (0x1FFFFFFUL << SCB_VTOR_TBLOFF_Pos)           /*!< SCB VTOR: TBLOFF Mask */
+#endif
+
+/* SCB Application Interrupt and Reset Control Register Definitions */
+#define SCB_AIRCR_VECTKEY_Pos              16                                             /*!< SCB AIRCR: VECTKEY Position */
+#define SCB_AIRCR_VECTKEY_Msk              (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos)            /*!< SCB AIRCR: VECTKEY Mask */
+
+#define SCB_AIRCR_VECTKEYSTAT_Pos          16                                             /*!< SCB AIRCR: VECTKEYSTAT Position */
+#define SCB_AIRCR_VECTKEYSTAT_Msk          (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos)        /*!< SCB AIRCR: VECTKEYSTAT Mask */
+
+#define SCB_AIRCR_ENDIANESS_Pos            15                                             /*!< SCB AIRCR: ENDIANESS Position */
+#define SCB_AIRCR_ENDIANESS_Msk            (1UL << SCB_AIRCR_ENDIANESS_Pos)               /*!< SCB AIRCR: ENDIANESS Mask */
+
+#define SCB_AIRCR_PRIGROUP_Pos              8                                             /*!< SCB AIRCR: PRIGROUP Position */
+#define SCB_AIRCR_PRIGROUP_Msk             (7UL << SCB_AIRCR_PRIGROUP_Pos)                /*!< SCB AIRCR: PRIGROUP Mask */
+
+#define SCB_AIRCR_SYSRESETREQ_Pos           2                                             /*!< SCB AIRCR: SYSRESETREQ Position */
+#define SCB_AIRCR_SYSRESETREQ_Msk          (1UL << SCB_AIRCR_SYSRESETREQ_Pos)             /*!< SCB AIRCR: SYSRESETREQ Mask */
+
+#define SCB_AIRCR_VECTCLRACTIVE_Pos         1                                             /*!< SCB AIRCR: VECTCLRACTIVE Position */
+#define SCB_AIRCR_VECTCLRACTIVE_Msk        (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos)           /*!< SCB AIRCR: VECTCLRACTIVE Mask */
+
+#define SCB_AIRCR_VECTRESET_Pos             0                                             /*!< SCB AIRCR: VECTRESET Position */
+#define SCB_AIRCR_VECTRESET_Msk            (1UL << SCB_AIRCR_VECTRESET_Pos)               /*!< SCB AIRCR: VECTRESET Mask */
+
+/* SCB System Control Register Definitions */
+#define SCB_SCR_SEVONPEND_Pos               4                                             /*!< SCB SCR: SEVONPEND Position */
+#define SCB_SCR_SEVONPEND_Msk              (1UL << SCB_SCR_SEVONPEND_Pos)                 /*!< SCB SCR: SEVONPEND Mask */
+
+#define SCB_SCR_SLEEPDEEP_Pos               2                                             /*!< SCB SCR: SLEEPDEEP Position */
+#define SCB_SCR_SLEEPDEEP_Msk              (1UL << SCB_SCR_SLEEPDEEP_Pos)                 /*!< SCB SCR: SLEEPDEEP Mask */
+
+#define SCB_SCR_SLEEPONEXIT_Pos             1                                             /*!< SCB SCR: SLEEPONEXIT Position */
+#define SCB_SCR_SLEEPONEXIT_Msk            (1UL << SCB_SCR_SLEEPONEXIT_Pos)               /*!< SCB SCR: SLEEPONEXIT Mask */
+
+/* SCB Configuration Control Register Definitions */
+#define SCB_CCR_STKALIGN_Pos                9                                             /*!< SCB CCR: STKALIGN Position */
+#define SCB_CCR_STKALIGN_Msk               (1UL << SCB_CCR_STKALIGN_Pos)                  /*!< SCB CCR: STKALIGN Mask */
+
+#define SCB_CCR_BFHFNMIGN_Pos               8                                             /*!< SCB CCR: BFHFNMIGN Position */
+#define SCB_CCR_BFHFNMIGN_Msk              (1UL << SCB_CCR_BFHFNMIGN_Pos)                 /*!< SCB CCR: BFHFNMIGN Mask */
+
+#define SCB_CCR_DIV_0_TRP_Pos               4                                             /*!< SCB CCR: DIV_0_TRP Position */
+#define SCB_CCR_DIV_0_TRP_Msk              (1UL << SCB_CCR_DIV_0_TRP_Pos)                 /*!< SCB CCR: DIV_0_TRP Mask */
+
+#define SCB_CCR_UNALIGN_TRP_Pos             3                                             /*!< SCB CCR: UNALIGN_TRP Position */
+#define SCB_CCR_UNALIGN_TRP_Msk            (1UL << SCB_CCR_UNALIGN_TRP_Pos)               /*!< SCB CCR: UNALIGN_TRP Mask */
+
+#define SCB_CCR_USERSETMPEND_Pos            1                                             /*!< SCB CCR: USERSETMPEND Position */
+#define SCB_CCR_USERSETMPEND_Msk           (1UL << SCB_CCR_USERSETMPEND_Pos)              /*!< SCB CCR: USERSETMPEND Mask */
+
+#define SCB_CCR_NONBASETHRDENA_Pos          0                                             /*!< SCB CCR: NONBASETHRDENA Position */
+#define SCB_CCR_NONBASETHRDENA_Msk         (1UL << SCB_CCR_NONBASETHRDENA_Pos)            /*!< SCB CCR: NONBASETHRDENA Mask */
+
+/* SCB System Handler Control and State Register Definitions */
+#define SCB_SHCSR_USGFAULTENA_Pos          18                                             /*!< SCB SHCSR: USGFAULTENA Position */
+#define SCB_SHCSR_USGFAULTENA_Msk          (1UL << SCB_SHCSR_USGFAULTENA_Pos)             /*!< SCB SHCSR: USGFAULTENA Mask */
+
+#define SCB_SHCSR_BUSFAULTENA_Pos          17                                             /*!< SCB SHCSR: BUSFAULTENA Position */
+#define SCB_SHCSR_BUSFAULTENA_Msk          (1UL << SCB_SHCSR_BUSFAULTENA_Pos)             /*!< SCB SHCSR: BUSFAULTENA Mask */
+
+#define SCB_SHCSR_MEMFAULTENA_Pos          16                                             /*!< SCB SHCSR: MEMFAULTENA Position */
+#define SCB_SHCSR_MEMFAULTENA_Msk          (1UL << SCB_SHCSR_MEMFAULTENA_Pos)             /*!< SCB SHCSR: MEMFAULTENA Mask */
+
+#define SCB_SHCSR_SVCALLPENDED_Pos         15                                             /*!< SCB SHCSR: SVCALLPENDED Position */
+#define SCB_SHCSR_SVCALLPENDED_Msk         (1UL << SCB_SHCSR_SVCALLPENDED_Pos)            /*!< SCB SHCSR: SVCALLPENDED Mask */
+
+#define SCB_SHCSR_BUSFAULTPENDED_Pos       14                                             /*!< SCB SHCSR: BUSFAULTPENDED Position */
+#define SCB_SHCSR_BUSFAULTPENDED_Msk       (1UL << SCB_SHCSR_BUSFAULTPENDED_Pos)          /*!< SCB SHCSR: BUSFAULTPENDED Mask */
+
+#define SCB_SHCSR_MEMFAULTPENDED_Pos       13                                             /*!< SCB SHCSR: MEMFAULTPENDED Position */
+#define SCB_SHCSR_MEMFAULTPENDED_Msk       (1UL << SCB_SHCSR_MEMFAULTPENDED_Pos)          /*!< SCB SHCSR: MEMFAULTPENDED Mask */
+
+#define SCB_SHCSR_USGFAULTPENDED_Pos       12                                             /*!< SCB SHCSR: USGFAULTPENDED Position */
+#define SCB_SHCSR_USGFAULTPENDED_Msk       (1UL << SCB_SHCSR_USGFAULTPENDED_Pos)          /*!< SCB SHCSR: USGFAULTPENDED Mask */
+
+#define SCB_SHCSR_SYSTICKACT_Pos           11                                             /*!< SCB SHCSR: SYSTICKACT Position */
+#define SCB_SHCSR_SYSTICKACT_Msk           (1UL << SCB_SHCSR_SYSTICKACT_Pos)              /*!< SCB SHCSR: SYSTICKACT Mask */
+
+#define SCB_SHCSR_PENDSVACT_Pos            10                                             /*!< SCB SHCSR: PENDSVACT Position */
+#define SCB_SHCSR_PENDSVACT_Msk            (1UL << SCB_SHCSR_PENDSVACT_Pos)               /*!< SCB SHCSR: PENDSVACT Mask */
+
+#define SCB_SHCSR_MONITORACT_Pos            8                                             /*!< SCB SHCSR: MONITORACT Position */
+#define SCB_SHCSR_MONITORACT_Msk           (1UL << SCB_SHCSR_MONITORACT_Pos)              /*!< SCB SHCSR: MONITORACT Mask */
+
+#define SCB_SHCSR_SVCALLACT_Pos             7                                             /*!< SCB SHCSR: SVCALLACT Position */
+#define SCB_SHCSR_SVCALLACT_Msk            (1UL << SCB_SHCSR_SVCALLACT_Pos)               /*!< SCB SHCSR: SVCALLACT Mask */
+
+#define SCB_SHCSR_USGFAULTACT_Pos           3                                             /*!< SCB SHCSR: USGFAULTACT Position */
+#define SCB_SHCSR_USGFAULTACT_Msk          (1UL << SCB_SHCSR_USGFAULTACT_Pos)             /*!< SCB SHCSR: USGFAULTACT Mask */
+
+#define SCB_SHCSR_BUSFAULTACT_Pos           1                                             /*!< SCB SHCSR: BUSFAULTACT Position */
+#define SCB_SHCSR_BUSFAULTACT_Msk          (1UL << SCB_SHCSR_BUSFAULTACT_Pos)             /*!< SCB SHCSR: BUSFAULTACT Mask */
+
+#define SCB_SHCSR_MEMFAULTACT_Pos           0                                             /*!< SCB SHCSR: MEMFAULTACT Position */
+#define SCB_SHCSR_MEMFAULTACT_Msk          (1UL << SCB_SHCSR_MEMFAULTACT_Pos)             /*!< SCB SHCSR: MEMFAULTACT Mask */
+
+/* SCB Configurable Fault Status Registers Definitions */
+#define SCB_CFSR_USGFAULTSR_Pos            16                                             /*!< SCB CFSR: Usage Fault Status Register Position */
+#define SCB_CFSR_USGFAULTSR_Msk            (0xFFFFUL << SCB_CFSR_USGFAULTSR_Pos)          /*!< SCB CFSR: Usage Fault Status Register Mask */
+
+#define SCB_CFSR_BUSFAULTSR_Pos             8                                             /*!< SCB CFSR: Bus Fault Status Register Position */
+#define SCB_CFSR_BUSFAULTSR_Msk            (0xFFUL << SCB_CFSR_BUSFAULTSR_Pos)            /*!< SCB CFSR: Bus Fault Status Register Mask */
+
+#define SCB_CFSR_MEMFAULTSR_Pos             0                                             /*!< SCB CFSR: Memory Manage Fault Status Register Position */
+#define SCB_CFSR_MEMFAULTSR_Msk            (0xFFUL << SCB_CFSR_MEMFAULTSR_Pos)            /*!< SCB CFSR: Memory Manage Fault Status Register Mask */
+
+/* SCB Hard Fault Status Registers Definitions */
+#define SCB_HFSR_DEBUGEVT_Pos              31                                             /*!< SCB HFSR: DEBUGEVT Position */
+#define SCB_HFSR_DEBUGEVT_Msk              (1UL << SCB_HFSR_DEBUGEVT_Pos)                 /*!< SCB HFSR: DEBUGEVT Mask */
+
+#define SCB_HFSR_FORCED_Pos                30                                             /*!< SCB HFSR: FORCED Position */
+#define SCB_HFSR_FORCED_Msk                (1UL << SCB_HFSR_FORCED_Pos)                   /*!< SCB HFSR: FORCED Mask */
+
+#define SCB_HFSR_VECTTBL_Pos                1                                             /*!< SCB HFSR: VECTTBL Position */
+#define SCB_HFSR_VECTTBL_Msk               (1UL << SCB_HFSR_VECTTBL_Pos)                  /*!< SCB HFSR: VECTTBL Mask */
+
+/* SCB Debug Fault Status Register Definitions */
+#define SCB_DFSR_EXTERNAL_Pos               4                                             /*!< SCB DFSR: EXTERNAL Position */
+#define SCB_DFSR_EXTERNAL_Msk              (1UL << SCB_DFSR_EXTERNAL_Pos)                 /*!< SCB DFSR: EXTERNAL Mask */
+
+#define SCB_DFSR_VCATCH_Pos                 3                                             /*!< SCB DFSR: VCATCH Position */
+#define SCB_DFSR_VCATCH_Msk                (1UL << SCB_DFSR_VCATCH_Pos)                   /*!< SCB DFSR: VCATCH Mask */
+
+#define SCB_DFSR_DWTTRAP_Pos                2                                             /*!< SCB DFSR: DWTTRAP Position */
+#define SCB_DFSR_DWTTRAP_Msk               (1UL << SCB_DFSR_DWTTRAP_Pos)                  /*!< SCB DFSR: DWTTRAP Mask */
+
+#define SCB_DFSR_BKPT_Pos                   1                                             /*!< SCB DFSR: BKPT Position */
+#define SCB_DFSR_BKPT_Msk                  (1UL << SCB_DFSR_BKPT_Pos)                     /*!< SCB DFSR: BKPT Mask */
+
+#define SCB_DFSR_HALTED_Pos                 0                                             /*!< SCB DFSR: HALTED Position */
+#define SCB_DFSR_HALTED_Msk                (1UL << SCB_DFSR_HALTED_Pos)                   /*!< SCB DFSR: HALTED Mask */
+
+/*@} end of group CMSIS_SCB */
+
+
+/** \ingroup  CMSIS_core_register
+    \defgroup CMSIS_SCnSCB System Controls not in SCB (SCnSCB)
+    \brief      Type definitions for the System Control and ID Register not in the SCB
+  @{
+ */
+
+/** \brief  Structure type to access the System Control and ID Register not in the SCB.
+ */
+typedef struct
+{
+       uint32_t RESERVED0[1];
+  __I  uint32_t ICTR;                    /*!< Offset: 0x004 (R/ )  Interrupt Controller Type Register      */
+#if ((defined __CM3_REV) && (__CM3_REV >= 0x200))
+  __IO uint32_t ACTLR;                   /*!< Offset: 0x008 (R/W)  Auxiliary Control Register      */
+#else
+       uint32_t RESERVED1[1];
+#endif
+} SCnSCB_Type;
+
+/* Interrupt Controller Type Register Definitions */
+#define SCnSCB_ICTR_INTLINESNUM_Pos         0                                          /*!< ICTR: INTLINESNUM Position */
+#define SCnSCB_ICTR_INTLINESNUM_Msk        (0xFUL << SCnSCB_ICTR_INTLINESNUM_Pos)      /*!< ICTR: INTLINESNUM Mask */
+
+/* Auxiliary Control Register Definitions */
+
+#define SCnSCB_ACTLR_DISFOLD_Pos            2                                          /*!< ACTLR: DISFOLD Position */
+#define SCnSCB_ACTLR_DISFOLD_Msk           (1UL << SCnSCB_ACTLR_DISFOLD_Pos)           /*!< ACTLR: DISFOLD Mask */
+
+#define SCnSCB_ACTLR_DISDEFWBUF_Pos         1                                          /*!< ACTLR: DISDEFWBUF Position */
+#define SCnSCB_ACTLR_DISDEFWBUF_Msk        (1UL << SCnSCB_ACTLR_DISDEFWBUF_Pos)        /*!< ACTLR: DISDEFWBUF Mask */
+
+#define SCnSCB_ACTLR_DISMCYCINT_Pos         0                                          /*!< ACTLR: DISMCYCINT Position */
+#define SCnSCB_ACTLR_DISMCYCINT_Msk        (1UL << SCnSCB_ACTLR_DISMCYCINT_Pos)        /*!< ACTLR: DISMCYCINT Mask */
+
+/*@} end of group CMSIS_SCnotSCB */
+
+
+/** \ingroup  CMSIS_core_register
+    \defgroup CMSIS_SysTick     System Tick Timer (SysTick)
+    \brief      Type definitions for the System Timer Registers.
+  @{
+ */
+
+/** \brief  Structure type to access the System Timer (SysTick).
+ */
+typedef struct
+{
+  __IO uint32_t CTRL;                    /*!< Offset: 0x000 (R/W)  SysTick Control and Status Register */
+  __IO uint32_t LOAD;                    /*!< Offset: 0x004 (R/W)  SysTick Reload Value Register       */
+  __IO uint32_t VAL;                     /*!< Offset: 0x008 (R/W)  SysTick Current Value Register      */
+  __I  uint32_t CALIB;                   /*!< Offset: 0x00C (R/ )  SysTick Calibration Register        */
+} SysTick_Type;
+
+/* SysTick Control / Status Register Definitions */
+#define SysTick_CTRL_COUNTFLAG_Pos         16                                             /*!< SysTick CTRL: COUNTFLAG Position */
+#define SysTick_CTRL_COUNTFLAG_Msk         (1UL << SysTick_CTRL_COUNTFLAG_Pos)            /*!< SysTick CTRL: COUNTFLAG Mask */
+
+#define SysTick_CTRL_CLKSOURCE_Pos          2                                             /*!< SysTick CTRL: CLKSOURCE Position */
+#define SysTick_CTRL_CLKSOURCE_Msk         (1UL << SysTick_CTRL_CLKSOURCE_Pos)            /*!< SysTick CTRL: CLKSOURCE Mask */
+
+#define SysTick_CTRL_TICKINT_Pos            1                                             /*!< SysTick CTRL: TICKINT Position */
+#define SysTick_CTRL_TICKINT_Msk           (1UL << SysTick_CTRL_TICKINT_Pos)              /*!< SysTick CTRL: TICKINT Mask */
+
+#define SysTick_CTRL_ENABLE_Pos             0                                             /*!< SysTick CTRL: ENABLE Position */
+#define SysTick_CTRL_ENABLE_Msk            (1UL << SysTick_CTRL_ENABLE_Pos)               /*!< SysTick CTRL: ENABLE Mask */
+
+/* SysTick Reload Register Definitions */
+#define SysTick_LOAD_RELOAD_Pos             0                                             /*!< SysTick LOAD: RELOAD Position */
+#define SysTick_LOAD_RELOAD_Msk            (0xFFFFFFUL << SysTick_LOAD_RELOAD_Pos)        /*!< SysTick LOAD: RELOAD Mask */
+
+/* SysTick Current Register Definitions */
+#define SysTick_VAL_CURRENT_Pos             0                                             /*!< SysTick VAL: CURRENT Position */
+#define SysTick_VAL_CURRENT_Msk            (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos)        /*!< SysTick VAL: CURRENT Mask */
+
+/* SysTick Calibration Register Definitions */
+#define SysTick_CALIB_NOREF_Pos            31                                             /*!< SysTick CALIB: NOREF Position */
+#define SysTick_CALIB_NOREF_Msk            (1UL << SysTick_CALIB_NOREF_Pos)               /*!< SysTick CALIB: NOREF Mask */
+
+#define SysTick_CALIB_SKEW_Pos             30                                             /*!< SysTick CALIB: SKEW Position */
+#define SysTick_CALIB_SKEW_Msk             (1UL << SysTick_CALIB_SKEW_Pos)                /*!< SysTick CALIB: SKEW Mask */
+
+#define SysTick_CALIB_TENMS_Pos             0                                             /*!< SysTick CALIB: TENMS Position */
+#define SysTick_CALIB_TENMS_Msk            (0xFFFFFFUL << SysTick_VAL_CURRENT_Pos)        /*!< SysTick CALIB: TENMS Mask */
+
+/*@} end of group CMSIS_SysTick */
+
+
+/** \ingroup  CMSIS_core_register
+    \defgroup CMSIS_ITM     Instrumentation Trace Macrocell (ITM)
+    \brief      Type definitions for the Instrumentation Trace Macrocell (ITM)
+  @{
+ */
+
+/** \brief  Structure type to access the Instrumentation Trace Macrocell Register (ITM).
+ */
+typedef struct
+{
+  __O  union
+  {
+    __O  uint8_t    u8;                  /*!< Offset: 0x000 ( /W)  ITM Stimulus Port 8-bit                   */
+    __O  uint16_t   u16;                 /*!< Offset: 0x000 ( /W)  ITM Stimulus Port 16-bit                  */
+    __O  uint32_t   u32;                 /*!< Offset: 0x000 ( /W)  ITM Stimulus Port 32-bit                  */
+  }  PORT [32];                          /*!< Offset: 0x000 ( /W)  ITM Stimulus Port Registers               */
+       uint32_t RESERVED0[864];
+  __IO uint32_t TER;                     /*!< Offset: 0xE00 (R/W)  ITM Trace Enable Register                 */
+       uint32_t RESERVED1[15];
+  __IO uint32_t TPR;                     /*!< Offset: 0xE40 (R/W)  ITM Trace Privilege Register              */
+       uint32_t RESERVED2[15];
+  __IO uint32_t TCR;                     /*!< Offset: 0xE80 (R/W)  ITM Trace Control Register                */
+       uint32_t RESERVED3[29];
+  __O  uint32_t IWR;                     /*!< Offset: 0xEF8 ( /W)  ITM Integration Write Register            */
+  __I  uint32_t IRR;                     /*!< Offset: 0xEFC (R/ )  ITM Integration Read Register             */
+  __IO uint32_t IMCR;                    /*!< Offset: 0xF00 (R/W)  ITM Integration Mode Control Register     */
+       uint32_t RESERVED4[43];
+  __O  uint32_t LAR;                     /*!< Offset: 0xFB0 ( /W)  ITM Lock Access Register                  */
+  __I  uint32_t LSR;                     /*!< Offset: 0xFB4 (R/ )  ITM Lock Status Register                  */
+       uint32_t RESERVED5[6];
+  __I  uint32_t PID4;                    /*!< Offset: 0xFD0 (R/ )  ITM Peripheral Identification Register #4 */
+  __I  uint32_t PID5;                    /*!< Offset: 0xFD4 (R/ )  ITM Peripheral Identification Register #5 */
+  __I  uint32_t PID6;                    /*!< Offset: 0xFD8 (R/ )  ITM Peripheral Identification Register #6 */
+  __I  uint32_t PID7;                    /*!< Offset: 0xFDC (R/ )  ITM Peripheral Identification Register #7 */
+  __I  uint32_t PID0;                    /*!< Offset: 0xFE0 (R/ )  ITM Peripheral Identification Register #0 */
+  __I  uint32_t PID1;                    /*!< Offset: 0xFE4 (R/ )  ITM Peripheral Identification Register #1 */
+  __I  uint32_t PID2;                    /*!< Offset: 0xFE8 (R/ )  ITM Peripheral Identification Register #2 */
+  __I  uint32_t PID3;                    /*!< Offset: 0xFEC (R/ )  ITM Peripheral Identification Register #3 */
+  __I  uint32_t CID0;                    /*!< Offset: 0xFF0 (R/ )  ITM Component  Identification Register #0 */
+  __I  uint32_t CID1;                    /*!< Offset: 0xFF4 (R/ )  ITM Component  Identification Register #1 */
+  __I  uint32_t CID2;                    /*!< Offset: 0xFF8 (R/ )  ITM Component  Identification Register #2 */
+  __I  uint32_t CID3;                    /*!< Offset: 0xFFC (R/ )  ITM Component  Identification Register #3 */
+} ITM_Type;
+
+/* ITM Trace Privilege Register Definitions */
+#define ITM_TPR_PRIVMASK_Pos                0                                             /*!< ITM TPR: PRIVMASK Position */
+#define ITM_TPR_PRIVMASK_Msk               (0xFUL << ITM_TPR_PRIVMASK_Pos)                /*!< ITM TPR: PRIVMASK Mask */
+
+/* ITM Trace Control Register Definitions */
+#define ITM_TCR_BUSY_Pos                   23                                             /*!< ITM TCR: BUSY Position */
+#define ITM_TCR_BUSY_Msk                   (1UL << ITM_TCR_BUSY_Pos)                      /*!< ITM TCR: BUSY Mask */
+
+#define ITM_TCR_TraceBusID_Pos             16                                             /*!< ITM TCR: ATBID Position */
+#define ITM_TCR_TraceBusID_Msk             (0x7FUL << ITM_TCR_TraceBusID_Pos)             /*!< ITM TCR: ATBID Mask */
+
+#define ITM_TCR_GTSFREQ_Pos                10                                             /*!< ITM TCR: Global timestamp frequency Position */
+#define ITM_TCR_GTSFREQ_Msk                (3UL << ITM_TCR_GTSFREQ_Pos)                   /*!< ITM TCR: Global timestamp frequency Mask */
+
+#define ITM_TCR_TSPrescale_Pos              8                                             /*!< ITM TCR: TSPrescale Position */
+#define ITM_TCR_TSPrescale_Msk             (3UL << ITM_TCR_TSPrescale_Pos)                /*!< ITM TCR: TSPrescale Mask */
+
+#define ITM_TCR_SWOENA_Pos                  4                                             /*!< ITM TCR: SWOENA Position */
+#define ITM_TCR_SWOENA_Msk                 (1UL << ITM_TCR_SWOENA_Pos)                    /*!< ITM TCR: SWOENA Mask */
+
+#define ITM_TCR_DWTENA_Pos                  3                                             /*!< ITM TCR: DWTENA Position */
+#define ITM_TCR_DWTENA_Msk                 (1UL << ITM_TCR_DWTENA_Pos)                    /*!< ITM TCR: DWTENA Mask */
+
+#define ITM_TCR_SYNCENA_Pos                 2                                             /*!< ITM TCR: SYNCENA Position */
+#define ITM_TCR_SYNCENA_Msk                (1UL << ITM_TCR_SYNCENA_Pos)                   /*!< ITM TCR: SYNCENA Mask */
+
+#define ITM_TCR_TSENA_Pos                   1                                             /*!< ITM TCR: TSENA Position */
+#define ITM_TCR_TSENA_Msk                  (1UL << ITM_TCR_TSENA_Pos)                     /*!< ITM TCR: TSENA Mask */
+
+#define ITM_TCR_ITMENA_Pos                  0                                             /*!< ITM TCR: ITM Enable bit Position */
+#define ITM_TCR_ITMENA_Msk                 (1UL << ITM_TCR_ITMENA_Pos)                    /*!< ITM TCR: ITM Enable bit Mask */
+
+/* ITM Integration Write Register Definitions */
+#define ITM_IWR_ATVALIDM_Pos                0                                             /*!< ITM IWR: ATVALIDM Position */
+#define ITM_IWR_ATVALIDM_Msk               (1UL << ITM_IWR_ATVALIDM_Pos)                  /*!< ITM IWR: ATVALIDM Mask */
+
+/* ITM Integration Read Register Definitions */
+#define ITM_IRR_ATREADYM_Pos                0                                             /*!< ITM IRR: ATREADYM Position */
+#define ITM_IRR_ATREADYM_Msk               (1UL << ITM_IRR_ATREADYM_Pos)                  /*!< ITM IRR: ATREADYM Mask */
+
+/* ITM Integration Mode Control Register Definitions */
+#define ITM_IMCR_INTEGRATION_Pos            0                                             /*!< ITM IMCR: INTEGRATION Position */
+#define ITM_IMCR_INTEGRATION_Msk           (1UL << ITM_IMCR_INTEGRATION_Pos)              /*!< ITM IMCR: INTEGRATION Mask */
+
+/* ITM Lock Status Register Definitions */
+#define ITM_LSR_ByteAcc_Pos                 2                                             /*!< ITM LSR: ByteAcc Position */
+#define ITM_LSR_ByteAcc_Msk                (1UL << ITM_LSR_ByteAcc_Pos)                   /*!< ITM LSR: ByteAcc Mask */
+
+#define ITM_LSR_Access_Pos                  1                                             /*!< ITM LSR: Access Position */
+#define ITM_LSR_Access_Msk                 (1UL << ITM_LSR_Access_Pos)                    /*!< ITM LSR: Access Mask */
+
+#define ITM_LSR_Present_Pos                 0                                             /*!< ITM LSR: Present Position */
+#define ITM_LSR_Present_Msk                (1UL << ITM_LSR_Present_Pos)                   /*!< ITM LSR: Present Mask */
+
+/*@}*/ /* end of group CMSIS_ITM */
+
+
+/** \ingroup  CMSIS_core_register
+    \defgroup CMSIS_DWT     Data Watchpoint and Trace (DWT)
+    \brief      Type definitions for the Data Watchpoint and Trace (DWT)
+  @{
+ */
+
+/** \brief  Structure type to access the Data Watchpoint and Trace Register (DWT).
+ */
+typedef struct
+{
+  __IO uint32_t CTRL;                    /*!< Offset: 0x000 (R/W)  Control Register                          */
+  __IO uint32_t CYCCNT;                  /*!< Offset: 0x004 (R/W)  Cycle Count Register                      */
+  __IO uint32_t CPICNT;                  /*!< Offset: 0x008 (R/W)  CPI Count Register                        */
+  __IO uint32_t EXCCNT;                  /*!< Offset: 0x00C (R/W)  Exception Overhead Count Register         */
+  __IO uint32_t SLEEPCNT;                /*!< Offset: 0x010 (R/W)  Sleep Count Register                      */
+  __IO uint32_t LSUCNT;                  /*!< Offset: 0x014 (R/W)  LSU Count Register                        */
+  __IO uint32_t FOLDCNT;                 /*!< Offset: 0x018 (R/W)  Folded-instruction Count Register         */
+  __I  uint32_t PCSR;                    /*!< Offset: 0x01C (R/ )  Program Counter Sample Register           */
+  __IO uint32_t COMP0;                   /*!< Offset: 0x020 (R/W)  Comparator Register 0                     */
+  __IO uint32_t MASK0;                   /*!< Offset: 0x024 (R/W)  Mask Register 0                           */
+  __IO uint32_t FUNCTION0;               /*!< Offset: 0x028 (R/W)  Function Register 0                       */
+       uint32_t RESERVED0[1];
+  __IO uint32_t COMP1;                   /*!< Offset: 0x030 (R/W)  Comparator Register 1                     */
+  __IO uint32_t MASK1;                   /*!< Offset: 0x034 (R/W)  Mask Register 1                           */
+  __IO uint32_t FUNCTION1;               /*!< Offset: 0x038 (R/W)  Function Register 1                       */
+       uint32_t RESERVED1[1];
+  __IO uint32_t COMP2;                   /*!< Offset: 0x040 (R/W)  Comparator Register 2                     */
+  __IO uint32_t MASK2;                   /*!< Offset: 0x044 (R/W)  Mask Register 2                           */
+  __IO uint32_t FUNCTION2;               /*!< Offset: 0x048 (R/W)  Function Register 2                       */
+       uint32_t RESERVED2[1];
+  __IO uint32_t COMP3;                   /*!< Offset: 0x050 (R/W)  Comparator Register 3                     */
+  __IO uint32_t MASK3;                   /*!< Offset: 0x054 (R/W)  Mask Register 3                           */
+  __IO uint32_t FUNCTION3;               /*!< Offset: 0x058 (R/W)  Function Register 3                       */
+} DWT_Type;
+
+/* DWT Control Register Definitions */
+#define DWT_CTRL_NUMCOMP_Pos               28                                          /*!< DWT CTRL: NUMCOMP Position */
+#define DWT_CTRL_NUMCOMP_Msk               (0xFUL << DWT_CTRL_NUMCOMP_Pos)             /*!< DWT CTRL: NUMCOMP Mask */
+
+#define DWT_CTRL_NOTRCPKT_Pos              27                                          /*!< DWT CTRL: NOTRCPKT Position */
+#define DWT_CTRL_NOTRCPKT_Msk              (0x1UL << DWT_CTRL_NOTRCPKT_Pos)            /*!< DWT CTRL: NOTRCPKT Mask */
+
+#define DWT_CTRL_NOEXTTRIG_Pos             26                                          /*!< DWT CTRL: NOEXTTRIG Position */
+#define DWT_CTRL_NOEXTTRIG_Msk             (0x1UL << DWT_CTRL_NOEXTTRIG_Pos)           /*!< DWT CTRL: NOEXTTRIG Mask */
+
+#define DWT_CTRL_NOCYCCNT_Pos              25                                          /*!< DWT CTRL: NOCYCCNT Position */
+#define DWT_CTRL_NOCYCCNT_Msk              (0x1UL << DWT_CTRL_NOCYCCNT_Pos)            /*!< DWT CTRL: NOCYCCNT Mask */
+
+#define DWT_CTRL_NOPRFCNT_Pos              24                                          /*!< DWT CTRL: NOPRFCNT Position */
+#define DWT_CTRL_NOPRFCNT_Msk              (0x1UL << DWT_CTRL_NOPRFCNT_Pos)            /*!< DWT CTRL: NOPRFCNT Mask */
+
+#define DWT_CTRL_CYCEVTENA_Pos             22                                          /*!< DWT CTRL: CYCEVTENA Position */
+#define DWT_CTRL_CYCEVTENA_Msk             (0x1UL << DWT_CTRL_CYCEVTENA_Pos)           /*!< DWT CTRL: CYCEVTENA Mask */
+
+#define DWT_CTRL_FOLDEVTENA_Pos            21                                          /*!< DWT CTRL: FOLDEVTENA Position */
+#define DWT_CTRL_FOLDEVTENA_Msk            (0x1UL << DWT_CTRL_FOLDEVTENA_Pos)          /*!< DWT CTRL: FOLDEVTENA Mask */
+
+#define DWT_CTRL_LSUEVTENA_Pos             20                                          /*!< DWT CTRL: LSUEVTENA Position */
+#define DWT_CTRL_LSUEVTENA_Msk             (0x1UL << DWT_CTRL_LSUEVTENA_Pos)           /*!< DWT CTRL: LSUEVTENA Mask */
+
+#define DWT_CTRL_SLEEPEVTENA_Pos           19                                          /*!< DWT CTRL: SLEEPEVTENA Position */
+#define DWT_CTRL_SLEEPEVTENA_Msk           (0x1UL << DWT_CTRL_SLEEPEVTENA_Pos)         /*!< DWT CTRL: SLEEPEVTENA Mask */
+
+#define DWT_CTRL_EXCEVTENA_Pos             18                                          /*!< DWT CTRL: EXCEVTENA Position */
+#define DWT_CTRL_EXCEVTENA_Msk             (0x1UL << DWT_CTRL_EXCEVTENA_Pos)           /*!< DWT CTRL: EXCEVTENA Mask */
+
+#define DWT_CTRL_CPIEVTENA_Pos             17                                          /*!< DWT CTRL: CPIEVTENA Position */
+#define DWT_CTRL_CPIEVTENA_Msk             (0x1UL << DWT_CTRL_CPIEVTENA_Pos)           /*!< DWT CTRL: CPIEVTENA Mask */
+
+#define DWT_CTRL_EXCTRCENA_Pos             16                                          /*!< DWT CTRL: EXCTRCENA Position */
+#define DWT_CTRL_EXCTRCENA_Msk             (0x1UL << DWT_CTRL_EXCTRCENA_Pos)           /*!< DWT CTRL: EXCTRCENA Mask */
+
+#define DWT_CTRL_PCSAMPLENA_Pos            12                                          /*!< DWT CTRL: PCSAMPLENA Position */
+#define DWT_CTRL_PCSAMPLENA_Msk            (0x1UL << DWT_CTRL_PCSAMPLENA_Pos)          /*!< DWT CTRL: PCSAMPLENA Mask */
+
+#define DWT_CTRL_SYNCTAP_Pos               10                                          /*!< DWT CTRL: SYNCTAP Position */
+#define DWT_CTRL_SYNCTAP_Msk               (0x3UL << DWT_CTRL_SYNCTAP_Pos)             /*!< DWT CTRL: SYNCTAP Mask */
+
+#define DWT_CTRL_CYCTAP_Pos                 9                                          /*!< DWT CTRL: CYCTAP Position */
+#define DWT_CTRL_CYCTAP_Msk                (0x1UL << DWT_CTRL_CYCTAP_Pos)              /*!< DWT CTRL: CYCTAP Mask */
+
+#define DWT_CTRL_POSTINIT_Pos               5                                          /*!< DWT CTRL: POSTINIT Position */
+#define DWT_CTRL_POSTINIT_Msk              (0xFUL << DWT_CTRL_POSTINIT_Pos)            /*!< DWT CTRL: POSTINIT Mask */
+
+#define DWT_CTRL_POSTPRESET_Pos             1                                          /*!< DWT CTRL: POSTPRESET Position */
+#define DWT_CTRL_POSTPRESET_Msk            (0xFUL << DWT_CTRL_POSTPRESET_Pos)          /*!< DWT CTRL: POSTPRESET Mask */
+
+#define DWT_CTRL_CYCCNTENA_Pos              0                                          /*!< DWT CTRL: CYCCNTENA Position */
+#define DWT_CTRL_CYCCNTENA_Msk             (0x1UL << DWT_CTRL_CYCCNTENA_Pos)           /*!< DWT CTRL: CYCCNTENA Mask */
+
+/* DWT CPI Count Register Definitions */
+#define DWT_CPICNT_CPICNT_Pos               0                                          /*!< DWT CPICNT: CPICNT Position */
+#define DWT_CPICNT_CPICNT_Msk              (0xFFUL << DWT_CPICNT_CPICNT_Pos)           /*!< DWT CPICNT: CPICNT Mask */
+
+/* DWT Exception Overhead Count Register Definitions */
+#define DWT_EXCCNT_EXCCNT_Pos               0                                          /*!< DWT EXCCNT: EXCCNT Position */
+#define DWT_EXCCNT_EXCCNT_Msk              (0xFFUL << DWT_EXCCNT_EXCCNT_Pos)           /*!< DWT EXCCNT: EXCCNT Mask */
+
+/* DWT Sleep Count Register Definitions */
+#define DWT_SLEEPCNT_SLEEPCNT_Pos           0                                          /*!< DWT SLEEPCNT: SLEEPCNT Position */
+#define DWT_SLEEPCNT_SLEEPCNT_Msk          (0xFFUL << DWT_SLEEPCNT_SLEEPCNT_Pos)       /*!< DWT SLEEPCNT: SLEEPCNT Mask */
+
+/* DWT LSU Count Register Definitions */
+#define DWT_LSUCNT_LSUCNT_Pos               0                                          /*!< DWT LSUCNT: LSUCNT Position */
+#define DWT_LSUCNT_LSUCNT_Msk              (0xFFUL << DWT_LSUCNT_LSUCNT_Pos)           /*!< DWT LSUCNT: LSUCNT Mask */
+
+/* DWT Folded-instruction Count Register Definitions */
+#define DWT_FOLDCNT_FOLDCNT_Pos             0                                          /*!< DWT FOLDCNT: FOLDCNT Position */
+#define DWT_FOLDCNT_FOLDCNT_Msk            (0xFFUL << DWT_FOLDCNT_FOLDCNT_Pos)         /*!< DWT FOLDCNT: FOLDCNT Mask */
+
+/* DWT Comparator Mask Register Definitions */
+#define DWT_MASK_MASK_Pos                   0                                          /*!< DWT MASK: MASK Position */
+#define DWT_MASK_MASK_Msk                  (0x1FUL << DWT_MASK_MASK_Pos)               /*!< DWT MASK: MASK Mask */
+
+/* DWT Comparator Function Register Definitions */
+#define DWT_FUNCTION_MATCHED_Pos           24                                          /*!< DWT FUNCTION: MATCHED Position */
+#define DWT_FUNCTION_MATCHED_Msk           (0x1UL << DWT_FUNCTION_MATCHED_Pos)         /*!< DWT FUNCTION: MATCHED Mask */
+
+#define DWT_FUNCTION_DATAVADDR1_Pos        16                                          /*!< DWT FUNCTION: DATAVADDR1 Position */
+#define DWT_FUNCTION_DATAVADDR1_Msk        (0xFUL << DWT_FUNCTION_DATAVADDR1_Pos)      /*!< DWT FUNCTION: DATAVADDR1 Mask */
+
+#define DWT_FUNCTION_DATAVADDR0_Pos        12                                          /*!< DWT FUNCTION: DATAVADDR0 Position */
+#define DWT_FUNCTION_DATAVADDR0_Msk        (0xFUL << DWT_FUNCTION_DATAVADDR0_Pos)      /*!< DWT FUNCTION: DATAVADDR0 Mask */
+
+#define DWT_FUNCTION_DATAVSIZE_Pos         10                                          /*!< DWT FUNCTION: DATAVSIZE Position */
+#define DWT_FUNCTION_DATAVSIZE_Msk         (0x3UL << DWT_FUNCTION_DATAVSIZE_Pos)       /*!< DWT FUNCTION: DATAVSIZE Mask */
+
+#define DWT_FUNCTION_LNK1ENA_Pos            9                                          /*!< DWT FUNCTION: LNK1ENA Position */
+#define DWT_FUNCTION_LNK1ENA_Msk           (0x1UL << DWT_FUNCTION_LNK1ENA_Pos)         /*!< DWT FUNCTION: LNK1ENA Mask */
+
+#define DWT_FUNCTION_DATAVMATCH_Pos         8                                          /*!< DWT FUNCTION: DATAVMATCH Position */
+#define DWT_FUNCTION_DATAVMATCH_Msk        (0x1UL << DWT_FUNCTION_DATAVMATCH_Pos)      /*!< DWT FUNCTION: DATAVMATCH Mask */
+
+#define DWT_FUNCTION_CYCMATCH_Pos           7                                          /*!< DWT FUNCTION: CYCMATCH Position */
+#define DWT_FUNCTION_CYCMATCH_Msk          (0x1UL << DWT_FUNCTION_CYCMATCH_Pos)        /*!< DWT FUNCTION: CYCMATCH Mask */
+
+#define DWT_FUNCTION_EMITRANGE_Pos          5                                          /*!< DWT FUNCTION: EMITRANGE Position */
+#define DWT_FUNCTION_EMITRANGE_Msk         (0x1UL << DWT_FUNCTION_EMITRANGE_Pos)       /*!< DWT FUNCTION: EMITRANGE Mask */
+
+#define DWT_FUNCTION_FUNCTION_Pos           0                                          /*!< DWT FUNCTION: FUNCTION Position */
+#define DWT_FUNCTION_FUNCTION_Msk          (0xFUL << DWT_FUNCTION_FUNCTION_Pos)        /*!< DWT FUNCTION: FUNCTION Mask */
+
+/*@}*/ /* end of group CMSIS_DWT */
+
+
+/** \ingroup  CMSIS_core_register
+    \defgroup CMSIS_TPI     Trace Port Interface (TPI)
+    \brief      Type definitions for the Trace Port Interface (TPI)
+  @{
+ */
+
+/** \brief  Structure type to access the Trace Port Interface Register (TPI).
+ */
+typedef struct
+{
+  __IO uint32_t SSPSR;                   /*!< Offset: 0x000 (R/ )  Supported Parallel Port Size Register     */
+  __IO uint32_t CSPSR;                   /*!< Offset: 0x004 (R/W)  Current Parallel Port Size Register */
+       uint32_t RESERVED0[2];
+  __IO uint32_t ACPR;                    /*!< Offset: 0x010 (R/W)  Asynchronous Clock Prescaler Register */
+       uint32_t RESERVED1[55];
+  __IO uint32_t SPPR;                    /*!< Offset: 0x0F0 (R/W)  Selected Pin Protocol Register */
+       uint32_t RESERVED2[131];
+  __I  uint32_t FFSR;                    /*!< Offset: 0x300 (R/ )  Formatter and Flush Status Register */
+  __IO uint32_t FFCR;                    /*!< Offset: 0x304 (R/W)  Formatter and Flush Control Register */
+  __I  uint32_t FSCR;                    /*!< Offset: 0x308 (R/ )  Formatter Synchronization Counter Register */
+       uint32_t RESERVED3[759];
+  __I  uint32_t TRIGGER;                 /*!< Offset: 0xEE8 (R/ )  TRIGGER */
+  __I  uint32_t FIFO0;                   /*!< Offset: 0xEEC (R/ )  Integration ETM Data */
+  __I  uint32_t ITATBCTR2;               /*!< Offset: 0xEF0 (R/ )  ITATBCTR2 */
+       uint32_t RESERVED4[1];
+  __I  uint32_t ITATBCTR0;               /*!< Offset: 0xEF8 (R/ )  ITATBCTR0 */
+  __I  uint32_t FIFO1;                   /*!< Offset: 0xEFC (R/ )  Integration ITM Data */
+  __IO uint32_t ITCTRL;                  /*!< Offset: 0xF00 (R/W)  Integration Mode Control */
+       uint32_t RESERVED5[39];
+  __IO uint32_t CLAIMSET;                /*!< Offset: 0xFA0 (R/W)  Claim tag set */
+  __IO uint32_t CLAIMCLR;                /*!< Offset: 0xFA4 (R/W)  Claim tag clear */
+       uint32_t RESERVED7[8];
+  __I  uint32_t DEVID;                   /*!< Offset: 0xFC8 (R/ )  TPIU_DEVID */
+  __I  uint32_t DEVTYPE;                 /*!< Offset: 0xFCC (R/ )  TPIU_DEVTYPE */
+} TPI_Type;
+
+/* TPI Asynchronous Clock Prescaler Register Definitions */
+#define TPI_ACPR_PRESCALER_Pos              0                                          /*!< TPI ACPR: PRESCALER Position */
+#define TPI_ACPR_PRESCALER_Msk             (0x1FFFUL << TPI_ACPR_PRESCALER_Pos)        /*!< TPI ACPR: PRESCALER Mask */
+
+/* TPI Selected Pin Protocol Register Definitions */
+#define TPI_SPPR_TXMODE_Pos                 0                                          /*!< TPI SPPR: TXMODE Position */
+#define TPI_SPPR_TXMODE_Msk                (0x3UL << TPI_SPPR_TXMODE_Pos)              /*!< TPI SPPR: TXMODE Mask */
+
+/* TPI Formatter and Flush Status Register Definitions */
+#define TPI_FFSR_FtNonStop_Pos              3                                          /*!< TPI FFSR: FtNonStop Position */
+#define TPI_FFSR_FtNonStop_Msk             (0x1UL << TPI_FFSR_FtNonStop_Pos)           /*!< TPI FFSR: FtNonStop Mask */
+
+#define TPI_FFSR_TCPresent_Pos              2                                          /*!< TPI FFSR: TCPresent Position */
+#define TPI_FFSR_TCPresent_Msk             (0x1UL << TPI_FFSR_TCPresent_Pos)           /*!< TPI FFSR: TCPresent Mask */
+
+#define TPI_FFSR_FtStopped_Pos              1                                          /*!< TPI FFSR: FtStopped Position */
+#define TPI_FFSR_FtStopped_Msk             (0x1UL << TPI_FFSR_FtStopped_Pos)           /*!< TPI FFSR: FtStopped Mask */
+
+#define TPI_FFSR_FlInProg_Pos               0                                          /*!< TPI FFSR: FlInProg Position */
+#define TPI_FFSR_FlInProg_Msk              (0x1UL << TPI_FFSR_FlInProg_Pos)            /*!< TPI FFSR: FlInProg Mask */
+
+/* TPI Formatter and Flush Control Register Definitions */
+#define TPI_FFCR_TrigIn_Pos                 8                                          /*!< TPI FFCR: TrigIn Position */
+#define TPI_FFCR_TrigIn_Msk                (0x1UL << TPI_FFCR_TrigIn_Pos)              /*!< TPI FFCR: TrigIn Mask */
+
+#define TPI_FFCR_EnFCont_Pos                1                                          /*!< TPI FFCR: EnFCont Position */
+#define TPI_FFCR_EnFCont_Msk               (0x1UL << TPI_FFCR_EnFCont_Pos)             /*!< TPI FFCR: EnFCont Mask */
+
+/* TPI TRIGGER Register Definitions */
+#define TPI_TRIGGER_TRIGGER_Pos             0                                          /*!< TPI TRIGGER: TRIGGER Position */
+#define TPI_TRIGGER_TRIGGER_Msk            (0x1UL << TPI_TRIGGER_TRIGGER_Pos)          /*!< TPI TRIGGER: TRIGGER Mask */
+
+/* TPI Integration ETM Data Register Definitions (FIFO0) */
+#define TPI_FIFO0_ITM_ATVALID_Pos          29                                          /*!< TPI FIFO0: ITM_ATVALID Position */
+#define TPI_FIFO0_ITM_ATVALID_Msk          (0x3UL << TPI_FIFO0_ITM_ATVALID_Pos)        /*!< TPI FIFO0: ITM_ATVALID Mask */
+
+#define TPI_FIFO0_ITM_bytecount_Pos        27                                          /*!< TPI FIFO0: ITM_bytecount Position */
+#define TPI_FIFO0_ITM_bytecount_Msk        (0x3UL << TPI_FIFO0_ITM_bytecount_Pos)      /*!< TPI FIFO0: ITM_bytecount Mask */
+
+#define TPI_FIFO0_ETM_ATVALID_Pos          26                                          /*!< TPI FIFO0: ETM_ATVALID Position */
+#define TPI_FIFO0_ETM_ATVALID_Msk          (0x3UL << TPI_FIFO0_ETM_ATVALID_Pos)        /*!< TPI FIFO0: ETM_ATVALID Mask */
+
+#define TPI_FIFO0_ETM_bytecount_Pos        24                                          /*!< TPI FIFO0: ETM_bytecount Position */
+#define TPI_FIFO0_ETM_bytecount_Msk        (0x3UL << TPI_FIFO0_ETM_bytecount_Pos)      /*!< TPI FIFO0: ETM_bytecount Mask */
+
+#define TPI_FIFO0_ETM2_Pos                 16                                          /*!< TPI FIFO0: ETM2 Position */
+#define TPI_FIFO0_ETM2_Msk                 (0xFFUL << TPI_FIFO0_ETM2_Pos)              /*!< TPI FIFO0: ETM2 Mask */
+
+#define TPI_FIFO0_ETM1_Pos                  8                                          /*!< TPI FIFO0: ETM1 Position */
+#define TPI_FIFO0_ETM1_Msk                 (0xFFUL << TPI_FIFO0_ETM1_Pos)              /*!< TPI FIFO0: ETM1 Mask */
+
+#define TPI_FIFO0_ETM0_Pos                  0                                          /*!< TPI FIFO0: ETM0 Position */
+#define TPI_FIFO0_ETM0_Msk                 (0xFFUL << TPI_FIFO0_ETM0_Pos)              /*!< TPI FIFO0: ETM0 Mask */
+
+/* TPI ITATBCTR2 Register Definitions */
+#define TPI_ITATBCTR2_ATREADY_Pos           0                                          /*!< TPI ITATBCTR2: ATREADY Position */
+#define TPI_ITATBCTR2_ATREADY_Msk          (0x1UL << TPI_ITATBCTR2_ATREADY_Pos)        /*!< TPI ITATBCTR2: ATREADY Mask */
+
+/* TPI Integration ITM Data Register Definitions (FIFO1) */
+#define TPI_FIFO1_ITM_ATVALID_Pos          29                                          /*!< TPI FIFO1: ITM_ATVALID Position */
+#define TPI_FIFO1_ITM_ATVALID_Msk          (0x3UL << TPI_FIFO1_ITM_ATVALID_Pos)        /*!< TPI FIFO1: ITM_ATVALID Mask */
+
+#define TPI_FIFO1_ITM_bytecount_Pos        27                                          /*!< TPI FIFO1: ITM_bytecount Position */
+#define TPI_FIFO1_ITM_bytecount_Msk        (0x3UL << TPI_FIFO1_ITM_bytecount_Pos)      /*!< TPI FIFO1: ITM_bytecount Mask */
+
+#define TPI_FIFO1_ETM_ATVALID_Pos          26                                          /*!< TPI FIFO1: ETM_ATVALID Position */
+#define TPI_FIFO1_ETM_ATVALID_Msk          (0x3UL << TPI_FIFO1_ETM_ATVALID_Pos)        /*!< TPI FIFO1: ETM_ATVALID Mask */
+
+#define TPI_FIFO1_ETM_bytecount_Pos        24                                          /*!< TPI FIFO1: ETM_bytecount Position */
+#define TPI_FIFO1_ETM_bytecount_Msk        (0x3UL << TPI_FIFO1_ETM_bytecount_Pos)      /*!< TPI FIFO1: ETM_bytecount Mask */
+
+#define TPI_FIFO1_ITM2_Pos                 16                                          /*!< TPI FIFO1: ITM2 Position */
+#define TPI_FIFO1_ITM2_Msk                 (0xFFUL << TPI_FIFO1_ITM2_Pos)              /*!< TPI FIFO1: ITM2 Mask */
+
+#define TPI_FIFO1_ITM1_Pos                  8                                          /*!< TPI FIFO1: ITM1 Position */
+#define TPI_FIFO1_ITM1_Msk                 (0xFFUL << TPI_FIFO1_ITM1_Pos)              /*!< TPI FIFO1: ITM1 Mask */
+
+#define TPI_FIFO1_ITM0_Pos                  0                                          /*!< TPI FIFO1: ITM0 Position */
+#define TPI_FIFO1_ITM0_Msk                 (0xFFUL << TPI_FIFO1_ITM0_Pos)              /*!< TPI FIFO1: ITM0 Mask */
+
+/* TPI ITATBCTR0 Register Definitions */
+#define TPI_ITATBCTR0_ATREADY_Pos           0                                          /*!< TPI ITATBCTR0: ATREADY Position */
+#define TPI_ITATBCTR0_ATREADY_Msk          (0x1UL << TPI_ITATBCTR0_ATREADY_Pos)        /*!< TPI ITATBCTR0: ATREADY Mask */
+
+/* TPI Integration Mode Control Register Definitions */
+#define TPI_ITCTRL_Mode_Pos                 0                                          /*!< TPI ITCTRL: Mode Position */
+#define TPI_ITCTRL_Mode_Msk                (0x1UL << TPI_ITCTRL_Mode_Pos)              /*!< TPI ITCTRL: Mode Mask */
+
+/* TPI DEVID Register Definitions */
+#define TPI_DEVID_NRZVALID_Pos             11                                          /*!< TPI DEVID: NRZVALID Position */
+#define TPI_DEVID_NRZVALID_Msk             (0x1UL << TPI_DEVID_NRZVALID_Pos)           /*!< TPI DEVID: NRZVALID Mask */
+
+#define TPI_DEVID_MANCVALID_Pos            10                                          /*!< TPI DEVID: MANCVALID Position */
+#define TPI_DEVID_MANCVALID_Msk            (0x1UL << TPI_DEVID_MANCVALID_Pos)          /*!< TPI DEVID: MANCVALID Mask */
+
+#define TPI_DEVID_PTINVALID_Pos             9                                          /*!< TPI DEVID: PTINVALID Position */
+#define TPI_DEVID_PTINVALID_Msk            (0x1UL << TPI_DEVID_PTINVALID_Pos)          /*!< TPI DEVID: PTINVALID Mask */
+
+#define TPI_DEVID_MinBufSz_Pos              6                                          /*!< TPI DEVID: MinBufSz Position */
+#define TPI_DEVID_MinBufSz_Msk             (0x7UL << TPI_DEVID_MinBufSz_Pos)           /*!< TPI DEVID: MinBufSz Mask */
+
+#define TPI_DEVID_AsynClkIn_Pos             5                                          /*!< TPI DEVID: AsynClkIn Position */
+#define TPI_DEVID_AsynClkIn_Msk            (0x1UL << TPI_DEVID_AsynClkIn_Pos)          /*!< TPI DEVID: AsynClkIn Mask */
+
+#define TPI_DEVID_NrTraceInput_Pos          0                                          /*!< TPI DEVID: NrTraceInput Position */
+#define TPI_DEVID_NrTraceInput_Msk         (0x1FUL << TPI_DEVID_NrTraceInput_Pos)      /*!< TPI DEVID: NrTraceInput Mask */
+
+/* TPI DEVTYPE Register Definitions */
+#define TPI_DEVTYPE_SubType_Pos             0                                          /*!< TPI DEVTYPE: SubType Position */
+#define TPI_DEVTYPE_SubType_Msk            (0xFUL << TPI_DEVTYPE_SubType_Pos)          /*!< TPI DEVTYPE: SubType Mask */
+
+#define TPI_DEVTYPE_MajorType_Pos           4                                          /*!< TPI DEVTYPE: MajorType Position */
+#define TPI_DEVTYPE_MajorType_Msk          (0xFUL << TPI_DEVTYPE_MajorType_Pos)        /*!< TPI DEVTYPE: MajorType Mask */
+
+/*@}*/ /* end of group CMSIS_TPI */
+
+
+#if (__MPU_PRESENT == 1)
+/** \ingroup  CMSIS_core_register
+    \defgroup CMSIS_MPU     Memory Protection Unit (MPU)
+    \brief      Type definitions for the Memory Protection Unit (MPU)
+  @{
+ */
+
+/** \brief  Structure type to access the Memory Protection Unit (MPU).
+ */
+typedef struct
+{
+  __I  uint32_t TYPE;                    /*!< Offset: 0x000 (R/ )  MPU Type Register                              */
+  __IO uint32_t CTRL;                    /*!< Offset: 0x004 (R/W)  MPU Control Register                           */
+  __IO uint32_t RNR;                     /*!< Offset: 0x008 (R/W)  MPU Region RNRber Register                     */
+  __IO uint32_t RBAR;                    /*!< Offset: 0x00C (R/W)  MPU Region Base Address Register               */
+  __IO uint32_t RASR;                    /*!< Offset: 0x010 (R/W)  MPU Region Attribute and Size Register         */
+  __IO uint32_t RBAR_A1;                 /*!< Offset: 0x014 (R/W)  MPU Alias 1 Region Base Address Register       */
+  __IO uint32_t RASR_A1;                 /*!< Offset: 0x018 (R/W)  MPU Alias 1 Region Attribute and Size Register */
+  __IO uint32_t RBAR_A2;                 /*!< Offset: 0x01C (R/W)  MPU Alias 2 Region Base Address Register       */
+  __IO uint32_t RASR_A2;                 /*!< Offset: 0x020 (R/W)  MPU Alias 2 Region Attribute and Size Register */
+  __IO uint32_t RBAR_A3;                 /*!< Offset: 0x024 (R/W)  MPU Alias 3 Region Base Address Register       */
+  __IO uint32_t RASR_A3;                 /*!< Offset: 0x028 (R/W)  MPU Alias 3 Region Attribute and Size Register */
+} MPU_Type;
+
+/* MPU Type Register */
+#define MPU_TYPE_IREGION_Pos               16                                             /*!< MPU TYPE: IREGION Position */
+#define MPU_TYPE_IREGION_Msk               (0xFFUL << MPU_TYPE_IREGION_Pos)               /*!< MPU TYPE: IREGION Mask */
+
+#define MPU_TYPE_DREGION_Pos                8                                             /*!< MPU TYPE: DREGION Position */
+#define MPU_TYPE_DREGION_Msk               (0xFFUL << MPU_TYPE_DREGION_Pos)               /*!< MPU TYPE: DREGION Mask */
+
+#define MPU_TYPE_SEPARATE_Pos               0                                             /*!< MPU TYPE: SEPARATE Position */
+#define MPU_TYPE_SEPARATE_Msk              (1UL << MPU_TYPE_SEPARATE_Pos)                 /*!< MPU TYPE: SEPARATE Mask */
+
+/* MPU Control Register */
+#define MPU_CTRL_PRIVDEFENA_Pos             2                                             /*!< MPU CTRL: PRIVDEFENA Position */
+#define MPU_CTRL_PRIVDEFENA_Msk            (1UL << MPU_CTRL_PRIVDEFENA_Pos)               /*!< MPU CTRL: PRIVDEFENA Mask */
+
+#define MPU_CTRL_HFNMIENA_Pos               1                                             /*!< MPU CTRL: HFNMIENA Position */
+#define MPU_CTRL_HFNMIENA_Msk              (1UL << MPU_CTRL_HFNMIENA_Pos)                 /*!< MPU CTRL: HFNMIENA Mask */
+
+#define MPU_CTRL_ENABLE_Pos                 0                                             /*!< MPU CTRL: ENABLE Position */
+#define MPU_CTRL_ENABLE_Msk                (1UL << MPU_CTRL_ENABLE_Pos)                   /*!< MPU CTRL: ENABLE Mask */
+
+/* MPU Region Number Register */
+#define MPU_RNR_REGION_Pos                  0                                             /*!< MPU RNR: REGION Position */
+#define MPU_RNR_REGION_Msk                 (0xFFUL << MPU_RNR_REGION_Pos)                 /*!< MPU RNR: REGION Mask */
+
+/* MPU Region Base Address Register */
+#define MPU_RBAR_ADDR_Pos                   5                                             /*!< MPU RBAR: ADDR Position */
+#define MPU_RBAR_ADDR_Msk                  (0x7FFFFFFUL << MPU_RBAR_ADDR_Pos)             /*!< MPU RBAR: ADDR Mask */
+
+#define MPU_RBAR_VALID_Pos                  4                                             /*!< MPU RBAR: VALID Position */
+#define MPU_RBAR_VALID_Msk                 (1UL << MPU_RBAR_VALID_Pos)                    /*!< MPU RBAR: VALID Mask */
+
+#define MPU_RBAR_REGION_Pos                 0                                             /*!< MPU RBAR: REGION Position */
+#define MPU_RBAR_REGION_Msk                (0xFUL << MPU_RBAR_REGION_Pos)                 /*!< MPU RBAR: REGION Mask */
+
+/* MPU Region Attribute and Size Register */
+#define MPU_RASR_ATTRS_Pos                 16                                             /*!< MPU RASR: MPU Region Attribute field Position */
+#define MPU_RASR_ATTRS_Msk                 (0xFFFFUL << MPU_RASR_ATTRS_Pos)               /*!< MPU RASR: MPU Region Attribute field Mask */
+
+#define MPU_RASR_XN_Pos                    28                                             /*!< MPU RASR: ATTRS.XN Position */
+#define MPU_RASR_XN_Msk                    (1UL << MPU_RASR_XN_Pos)                       /*!< MPU RASR: ATTRS.XN Mask */
+
+#define MPU_RASR_AP_Pos                    24                                             /*!< MPU RASR: ATTRS.AP Position */
+#define MPU_RASR_AP_Msk                    (0x7UL << MPU_RASR_AP_Pos)                     /*!< MPU RASR: ATTRS.AP Mask */
+
+#define MPU_RASR_TEX_Pos                   19                                             /*!< MPU RASR: ATTRS.TEX Position */
+#define MPU_RASR_TEX_Msk                   (0x7UL << MPU_RASR_TEX_Pos)                    /*!< MPU RASR: ATTRS.TEX Mask */
+
+#define MPU_RASR_S_Pos                     18                                             /*!< MPU RASR: ATTRS.S Position */
+#define MPU_RASR_S_Msk                     (1UL << MPU_RASR_S_Pos)                        /*!< MPU RASR: ATTRS.S Mask */
+
+#define MPU_RASR_C_Pos                     17                                             /*!< MPU RASR: ATTRS.C Position */
+#define MPU_RASR_C_Msk                     (1UL << MPU_RASR_C_Pos)                        /*!< MPU RASR: ATTRS.C Mask */
+
+#define MPU_RASR_B_Pos                     16                                             /*!< MPU RASR: ATTRS.B Position */
+#define MPU_RASR_B_Msk                     (1UL << MPU_RASR_B_Pos)                        /*!< MPU RASR: ATTRS.B Mask */
+
+#define MPU_RASR_SRD_Pos                    8                                             /*!< MPU RASR: Sub-Region Disable Position */
+#define MPU_RASR_SRD_Msk                   (0xFFUL << MPU_RASR_SRD_Pos)                   /*!< MPU RASR: Sub-Region Disable Mask */
+
+#define MPU_RASR_SIZE_Pos                   1                                             /*!< MPU RASR: Region Size Field Position */
+#define MPU_RASR_SIZE_Msk                  (0x1FUL << MPU_RASR_SIZE_Pos)                  /*!< MPU RASR: Region Size Field Mask */
+
+#define MPU_RASR_ENABLE_Pos                 0                                             /*!< MPU RASR: Region enable bit Position */
+#define MPU_RASR_ENABLE_Msk                (1UL << MPU_RASR_ENABLE_Pos)                   /*!< MPU RASR: Region enable bit Disable Mask */
+
+/*@} end of group CMSIS_MPU */
+#endif
+
+
+/** \ingroup  CMSIS_core_register
+    \defgroup CMSIS_CoreDebug       Core Debug Registers (CoreDebug)
+    \brief      Type definitions for the Core Debug Registers
+  @{
+ */
+
+/** \brief  Structure type to access the Core Debug Register (CoreDebug).
+ */
+typedef struct
+{
+  __IO uint32_t DHCSR;                   /*!< Offset: 0x000 (R/W)  Debug Halting Control and Status Register    */
+  __O  uint32_t DCRSR;                   /*!< Offset: 0x004 ( /W)  Debug Core Register Selector Register        */
+  __IO uint32_t DCRDR;                   /*!< Offset: 0x008 (R/W)  Debug Core Register Data Register            */
+  __IO uint32_t DEMCR;                   /*!< Offset: 0x00C (R/W)  Debug Exception and Monitor Control Register */
+} CoreDebug_Type;
+
+/* Debug Halting Control and Status Register */
+#define CoreDebug_DHCSR_DBGKEY_Pos         16                                             /*!< CoreDebug DHCSR: DBGKEY Position */
+#define CoreDebug_DHCSR_DBGKEY_Msk         (0xFFFFUL << CoreDebug_DHCSR_DBGKEY_Pos)       /*!< CoreDebug DHCSR: DBGKEY Mask */
+
+#define CoreDebug_DHCSR_S_RESET_ST_Pos     25                                             /*!< CoreDebug DHCSR: S_RESET_ST Position */
+#define CoreDebug_DHCSR_S_RESET_ST_Msk     (1UL << CoreDebug_DHCSR_S_RESET_ST_Pos)        /*!< CoreDebug DHCSR: S_RESET_ST Mask */
+
+#define CoreDebug_DHCSR_S_RETIRE_ST_Pos    24                                             /*!< CoreDebug DHCSR: S_RETIRE_ST Position */
+#define CoreDebug_DHCSR_S_RETIRE_ST_Msk    (1UL << CoreDebug_DHCSR_S_RETIRE_ST_Pos)       /*!< CoreDebug DHCSR: S_RETIRE_ST Mask */
+
+#define CoreDebug_DHCSR_S_LOCKUP_Pos       19                                             /*!< CoreDebug DHCSR: S_LOCKUP Position */
+#define CoreDebug_DHCSR_S_LOCKUP_Msk       (1UL << CoreDebug_DHCSR_S_LOCKUP_Pos)          /*!< CoreDebug DHCSR: S_LOCKUP Mask */
+
+#define CoreDebug_DHCSR_S_SLEEP_Pos        18                                             /*!< CoreDebug DHCSR: S_SLEEP Position */
+#define CoreDebug_DHCSR_S_SLEEP_Msk        (1UL << CoreDebug_DHCSR_S_SLEEP_Pos)           /*!< CoreDebug DHCSR: S_SLEEP Mask */
+
+#define CoreDebug_DHCSR_S_HALT_Pos         17                                             /*!< CoreDebug DHCSR: S_HALT Position */
+#define CoreDebug_DHCSR_S_HALT_Msk         (1UL << CoreDebug_DHCSR_S_HALT_Pos)            /*!< CoreDebug DHCSR: S_HALT Mask */
+
+#define CoreDebug_DHCSR_S_REGRDY_Pos       16                                             /*!< CoreDebug DHCSR: S_REGRDY Position */
+#define CoreDebug_DHCSR_S_REGRDY_Msk       (1UL << CoreDebug_DHCSR_S_REGRDY_Pos)          /*!< CoreDebug DHCSR: S_REGRDY Mask */
+
+#define CoreDebug_DHCSR_C_SNAPSTALL_Pos     5                                             /*!< CoreDebug DHCSR: C_SNAPSTALL Position */
+#define CoreDebug_DHCSR_C_SNAPSTALL_Msk    (1UL << CoreDebug_DHCSR_C_SNAPSTALL_Pos)       /*!< CoreDebug DHCSR: C_SNAPSTALL Mask */
+
+#define CoreDebug_DHCSR_C_MASKINTS_Pos      3                                             /*!< CoreDebug DHCSR: C_MASKINTS Position */
+#define CoreDebug_DHCSR_C_MASKINTS_Msk     (1UL << CoreDebug_DHCSR_C_MASKINTS_Pos)        /*!< CoreDebug DHCSR: C_MASKINTS Mask */
+
+#define CoreDebug_DHCSR_C_STEP_Pos          2                                             /*!< CoreDebug DHCSR: C_STEP Position */
+#define CoreDebug_DHCSR_C_STEP_Msk         (1UL << CoreDebug_DHCSR_C_STEP_Pos)            /*!< CoreDebug DHCSR: C_STEP Mask */
+
+#define CoreDebug_DHCSR_C_HALT_Pos          1                                             /*!< CoreDebug DHCSR: C_HALT Position */
+#define CoreDebug_DHCSR_C_HALT_Msk         (1UL << CoreDebug_DHCSR_C_HALT_Pos)            /*!< CoreDebug DHCSR: C_HALT Mask */
+
+#define CoreDebug_DHCSR_C_DEBUGEN_Pos       0                                             /*!< CoreDebug DHCSR: C_DEBUGEN Position */
+#define CoreDebug_DHCSR_C_DEBUGEN_Msk      (1UL << CoreDebug_DHCSR_C_DEBUGEN_Pos)         /*!< CoreDebug DHCSR: C_DEBUGEN Mask */
+
+/* Debug Core Register Selector Register */
+#define CoreDebug_DCRSR_REGWnR_Pos         16                                             /*!< CoreDebug DCRSR: REGWnR Position */
+#define CoreDebug_DCRSR_REGWnR_Msk         (1UL << CoreDebug_DCRSR_REGWnR_Pos)            /*!< CoreDebug DCRSR: REGWnR Mask */
+
+#define CoreDebug_DCRSR_REGSEL_Pos          0                                             /*!< CoreDebug DCRSR: REGSEL Position */
+#define CoreDebug_DCRSR_REGSEL_Msk         (0x1FUL << CoreDebug_DCRSR_REGSEL_Pos)         /*!< CoreDebug DCRSR: REGSEL Mask */
+
+/* Debug Exception and Monitor Control Register */
+#define CoreDebug_DEMCR_TRCENA_Pos         24                                             /*!< CoreDebug DEMCR: TRCENA Position */
+#define CoreDebug_DEMCR_TRCENA_Msk         (1UL << CoreDebug_DEMCR_TRCENA_Pos)            /*!< CoreDebug DEMCR: TRCENA Mask */
+
+#define CoreDebug_DEMCR_MON_REQ_Pos        19                                             /*!< CoreDebug DEMCR: MON_REQ Position */
+#define CoreDebug_DEMCR_MON_REQ_Msk        (1UL << CoreDebug_DEMCR_MON_REQ_Pos)           /*!< CoreDebug DEMCR: MON_REQ Mask */
+
+#define CoreDebug_DEMCR_MON_STEP_Pos       18                                             /*!< CoreDebug DEMCR: MON_STEP Position */
+#define CoreDebug_DEMCR_MON_STEP_Msk       (1UL << CoreDebug_DEMCR_MON_STEP_Pos)          /*!< CoreDebug DEMCR: MON_STEP Mask */
+
+#define CoreDebug_DEMCR_MON_PEND_Pos       17                                             /*!< CoreDebug DEMCR: MON_PEND Position */
+#define CoreDebug_DEMCR_MON_PEND_Msk       (1UL << CoreDebug_DEMCR_MON_PEND_Pos)          /*!< CoreDebug DEMCR: MON_PEND Mask */
+
+#define CoreDebug_DEMCR_MON_EN_Pos         16                                             /*!< CoreDebug DEMCR: MON_EN Position */
+#define CoreDebug_DEMCR_MON_EN_Msk         (1UL << CoreDebug_DEMCR_MON_EN_Pos)            /*!< CoreDebug DEMCR: MON_EN Mask */
+
+#define CoreDebug_DEMCR_VC_HARDERR_Pos     10                                             /*!< CoreDebug DEMCR: VC_HARDERR Position */
+#define CoreDebug_DEMCR_VC_HARDERR_Msk     (1UL << CoreDebug_DEMCR_VC_HARDERR_Pos)        /*!< CoreDebug DEMCR: VC_HARDERR Mask */
+
+#define CoreDebug_DEMCR_VC_INTERR_Pos       9                                             /*!< CoreDebug DEMCR: VC_INTERR Position */
+#define CoreDebug_DEMCR_VC_INTERR_Msk      (1UL << CoreDebug_DEMCR_VC_INTERR_Pos)         /*!< CoreDebug DEMCR: VC_INTERR Mask */
+
+#define CoreDebug_DEMCR_VC_BUSERR_Pos       8                                             /*!< CoreDebug DEMCR: VC_BUSERR Position */
+#define CoreDebug_DEMCR_VC_BUSERR_Msk      (1UL << CoreDebug_DEMCR_VC_BUSERR_Pos)         /*!< CoreDebug DEMCR: VC_BUSERR Mask */
+
+#define CoreDebug_DEMCR_VC_STATERR_Pos      7                                             /*!< CoreDebug DEMCR: VC_STATERR Position */
+#define CoreDebug_DEMCR_VC_STATERR_Msk     (1UL << CoreDebug_DEMCR_VC_STATERR_Pos)        /*!< CoreDebug DEMCR: VC_STATERR Mask */
+
+#define CoreDebug_DEMCR_VC_CHKERR_Pos       6                                             /*!< CoreDebug DEMCR: VC_CHKERR Position */
+#define CoreDebug_DEMCR_VC_CHKERR_Msk      (1UL << CoreDebug_DEMCR_VC_CHKERR_Pos)         /*!< CoreDebug DEMCR: VC_CHKERR Mask */
+
+#define CoreDebug_DEMCR_VC_NOCPERR_Pos      5                                             /*!< CoreDebug DEMCR: VC_NOCPERR Position */
+#define CoreDebug_DEMCR_VC_NOCPERR_Msk     (1UL << CoreDebug_DEMCR_VC_NOCPERR_Pos)        /*!< CoreDebug DEMCR: VC_NOCPERR Mask */
+
+#define CoreDebug_DEMCR_VC_MMERR_Pos        4                                             /*!< CoreDebug DEMCR: VC_MMERR Position */
+#define CoreDebug_DEMCR_VC_MMERR_Msk       (1UL << CoreDebug_DEMCR_VC_MMERR_Pos)          /*!< CoreDebug DEMCR: VC_MMERR Mask */
+
+#define CoreDebug_DEMCR_VC_CORERESET_Pos    0                                             /*!< CoreDebug DEMCR: VC_CORERESET Position */
+#define CoreDebug_DEMCR_VC_CORERESET_Msk   (1UL << CoreDebug_DEMCR_VC_CORERESET_Pos)      /*!< CoreDebug DEMCR: VC_CORERESET Mask */
+
+/*@} end of group CMSIS_CoreDebug */
+
+
+/** \ingroup    CMSIS_core_register
+    \defgroup   CMSIS_core_base     Core Definitions
+    \brief      Definitions for base addresses, unions, and structures.
+  @{
+ */
+
+/* Memory mapping of Cortex-M3 Hardware */
+#define SCS_BASE            (0xE000E000UL)                            /*!< System Control Space Base Address  */
+#define ITM_BASE            (0xE0000000UL)                            /*!< ITM Base Address                   */
+#define DWT_BASE            (0xE0001000UL)                            /*!< DWT Base Address                   */
+#define TPI_BASE            (0xE0040000UL)                            /*!< TPI Base Address                   */
+#define CoreDebug_BASE      (0xE000EDF0UL)                            /*!< Core Debug Base Address            */
+#define SysTick_BASE        (SCS_BASE +  0x0010UL)                    /*!< SysTick Base Address               */
+#define NVIC_BASE           (SCS_BASE +  0x0100UL)                    /*!< NVIC Base Address                  */
+#define SCB_BASE            (SCS_BASE +  0x0D00UL)                    /*!< System Control Block Base Address  */
+
+#define SCnSCB              ((SCnSCB_Type    *)     SCS_BASE      )   /*!< System control Register not in SCB */
+#define SCB                 ((SCB_Type       *)     SCB_BASE      )   /*!< SCB configuration struct           */
+#define SysTick             ((SysTick_Type   *)     SysTick_BASE  )   /*!< SysTick configuration struct       */
+#define NVIC                ((NVIC_Type      *)     NVIC_BASE     )   /*!< NVIC configuration struct          */
+#define ITM                 ((ITM_Type       *)     ITM_BASE      )   /*!< ITM configuration struct           */
+#define DWT                 ((DWT_Type       *)     DWT_BASE      )   /*!< DWT configuration struct           */
+#define TPI                 ((TPI_Type       *)     TPI_BASE      )   /*!< TPI configuration struct           */
+#define CoreDebug           ((CoreDebug_Type *)     CoreDebug_BASE)   /*!< Core Debug configuration struct    */
+
+#if (__MPU_PRESENT == 1)
+  #define MPU_BASE          (SCS_BASE +  0x0D90UL)                    /*!< Memory Protection Unit             */
+  #define MPU               ((MPU_Type       *)     MPU_BASE      )   /*!< Memory Protection Unit             */
+#endif
+
+/*@} */
+
+
+
+/*******************************************************************************
+ *                Hardware Abstraction Layer
+  Core Function Interface contains:
+  - Core NVIC Functions
+  - Core SysTick Functions
+  - Core Debug Functions
+  - Core Register Access Functions
+ ******************************************************************************/
+/** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference
+*/
+
+
+
+/* ##########################   NVIC functions  #################################### */
+/** \ingroup  CMSIS_Core_FunctionInterface
+    \defgroup CMSIS_Core_NVICFunctions NVIC Functions
+    \brief      Functions that manage interrupts and exceptions via the NVIC.
+    @{
+ */
+
+/** \brief  Set Priority Grouping
+
+  The function sets the priority grouping field using the required unlock sequence.
+  The parameter PriorityGroup is assigned to the field SCB->AIRCR [10:8] PRIGROUP field.
+  Only values from 0..7 are used.
+  In case of a conflict between priority grouping and available
+  priority bits (__NVIC_PRIO_BITS), the smallest possible priority group is set.
+
+    \param [in]      PriorityGroup  Priority grouping field.
+ */
+__STATIC_INLINE void NVIC_SetPriorityGrouping(uint32_t PriorityGroup)
+{
+  uint32_t reg_value;
+  uint32_t PriorityGroupTmp = (PriorityGroup & (uint32_t)0x07);               /* only values 0..7 are used          */
+
+  reg_value  =  SCB->AIRCR;                                                   /* read old register configuration    */
+  reg_value &= ~(SCB_AIRCR_VECTKEY_Msk | SCB_AIRCR_PRIGROUP_Msk);             /* clear bits to change               */
+  reg_value  =  (reg_value                                 |
+                ((uint32_t)0x5FA << SCB_AIRCR_VECTKEY_Pos) |
+                (PriorityGroupTmp << 8));                                     /* Insert write key and priorty group */
+  SCB->AIRCR =  reg_value;
+}
+
+
+/** \brief  Get Priority Grouping
+
+  The function reads the priority grouping field from the NVIC Interrupt Controller.
+
+    \return                Priority grouping field (SCB->AIRCR [10:8] PRIGROUP field).
+ */
+__STATIC_INLINE uint32_t NVIC_GetPriorityGrouping(void)
+{
+  return ((SCB->AIRCR & SCB_AIRCR_PRIGROUP_Msk) >> SCB_AIRCR_PRIGROUP_Pos);   /* read priority grouping field */
+}
+
+
+/** \brief  Enable External Interrupt
+
+    The function enables a device-specific interrupt in the NVIC interrupt controller.
+
+    \param [in]      IRQn  External interrupt number. Value cannot be negative.
+ */
+__STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn)
+{
+  NVIC->ISER[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* enable interrupt */
+}
+
+
+/** \brief  Disable External Interrupt
+
+    The function disables a device-specific interrupt in the NVIC interrupt controller.
+
+    \param [in]      IRQn  External interrupt number. Value cannot be negative.
+ */
+__STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn)
+{
+  NVIC->ICER[((uint32_t)(IRQn) >> 5)] = (1 << ((uint32_t)(IRQn) & 0x1F)); /* disable interrupt */
+}
+
+
+/** \brief  Get Pending Interrupt
+
+    The function reads the pending register in the NVIC and returns the pending bit
+    for the specified interrupt.
+
+    \param [in]      IRQn  Interrupt number.
+
+    \return             0  Interrupt status is not pending.
+    \return             1  Interrupt status is pendi

<TRUNCATED>


[47/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/boot/bootutil/test/src/boot_test.c
----------------------------------------------------------------------
diff --git a/boot/bootutil/test/src/boot_test.c b/boot/bootutil/test/src/boot_test.c
new file mode 100644
index 0000000..10cd045
--- /dev/null
+++ b/boot/bootutil/test/src/boot_test.c
@@ -0,0 +1,1169 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include <assert.h>
+#include <stddef.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <inttypes.h>
+#include "syscfg/syscfg.h"
+#include "testutil/testutil.h"
+#include "hal/hal_flash.h"
+#include "hal/flash_map.h"
+#include "bootutil/image.h"
+#include "bootutil/loader.h"
+#include "bootutil/bootutil_misc.h"
+#include "../src/bootutil_priv.h"
+
+#include "mbedtls/sha256.h"
+
+#define BOOT_TEST_HEADER_SIZE       0x200
+
+/** Internal flash layout. */
+static struct flash_area boot_test_area_descs[] = {
+    [0] = { .fa_off = 0x00020000, .fa_size = 128 * 1024 },
+    [1] = { .fa_off = 0x00040000, .fa_size = 128 * 1024 },
+    [2] = { .fa_off = 0x00060000, .fa_size = 128 * 1024 },
+    [3] = { .fa_off = 0x00080000, .fa_size = 128 * 1024 },
+    [4] = { .fa_off = 0x000a0000, .fa_size = 128 * 1024 },
+    [5] = { .fa_off = 0x000c0000, .fa_size = 128 * 1024 },
+    [6] = { .fa_off = 0x000e0000, .fa_size = 128 * 1024 },
+    [7] = { 0 },
+};
+
+/** Areas representing the beginning of image slots. */
+static uint8_t boot_test_slot_areas[] = {
+    0, 3,
+};
+
+/** Flash offsets of the two image slots. */
+static struct {
+    uint8_t flash_id;
+    uint32_t address;
+} boot_test_img_addrs[] = {
+    { 0, 0x20000 },
+    { 0, 0x80000 },
+};
+
+#define BOOT_TEST_AREA_IDX_SCRATCH 6
+
+static uint8_t
+boot_test_util_byte_at(int img_msb, uint32_t image_offset)
+{
+    uint32_t u32;
+    uint8_t *u8p;
+
+    TEST_ASSERT(image_offset < 0x01000000);
+    u32 = image_offset + (img_msb << 24);
+    u8p = (void *)&u32;
+    return u8p[image_offset % 4];
+}
+
+static void
+boot_test_util_init_flash(void)
+{
+    const struct flash_area *area_desc;
+    int rc;
+
+    rc = hal_flash_init();
+    TEST_ASSERT(rc == 0);
+
+    for (area_desc = boot_test_area_descs;
+         area_desc->fa_size != 0;
+         area_desc++) {
+
+        rc = flash_area_erase(area_desc, 0, area_desc->fa_size);
+        TEST_ASSERT(rc == 0);
+    }
+}
+
+static void
+boot_test_util_copy_area(int from_area_idx, int to_area_idx)
+{
+    const struct flash_area *from_area_desc;
+    const struct flash_area *to_area_desc;
+    void *buf;
+    int rc;
+
+    from_area_desc = boot_test_area_descs + from_area_idx;
+    to_area_desc = boot_test_area_descs + to_area_idx;
+
+    TEST_ASSERT(from_area_desc->fa_size == to_area_desc->fa_size);
+
+    buf = malloc(from_area_desc->fa_size);
+    TEST_ASSERT(buf != NULL);
+
+    rc = flash_area_read(from_area_desc, 0, buf,
+                         from_area_desc->fa_size);
+    TEST_ASSERT(rc == 0);
+
+    rc = flash_area_erase(to_area_desc,
+                          0,
+                          to_area_desc->fa_size);
+    TEST_ASSERT(rc == 0);
+
+    rc = flash_area_write(to_area_desc, 0, buf,
+                          to_area_desc->fa_size);
+    TEST_ASSERT(rc == 0);
+
+    free(buf);
+}
+
+static void
+boot_test_util_swap_areas(int area_idx1, int area_idx2)
+{
+    const struct flash_area *area_desc1;
+    const struct flash_area *area_desc2;
+    void *buf1;
+    void *buf2;
+    int rc;
+
+    area_desc1 = boot_test_area_descs + area_idx1;
+    area_desc2 = boot_test_area_descs + area_idx2;
+
+    TEST_ASSERT(area_desc1->fa_size == area_desc2->fa_size);
+
+    buf1 = malloc(area_desc1->fa_size);
+    TEST_ASSERT(buf1 != NULL);
+
+    buf2 = malloc(area_desc2->fa_size);
+    TEST_ASSERT(buf2 != NULL);
+
+    rc = flash_area_read(area_desc1, 0, buf1, area_desc1->fa_size);
+    TEST_ASSERT(rc == 0);
+
+    rc = flash_area_read(area_desc2, 0, buf2, area_desc2->fa_size);
+    TEST_ASSERT(rc == 0);
+
+    rc = flash_area_erase(area_desc1, 0, area_desc1->fa_size);
+    TEST_ASSERT(rc == 0);
+
+    rc = flash_area_erase(area_desc2, 0, area_desc2->fa_size);
+    TEST_ASSERT(rc == 0);
+
+    rc = flash_area_write(area_desc1, 0, buf2, area_desc1->fa_size);
+    TEST_ASSERT(rc == 0);
+
+    rc = flash_area_write(area_desc2, 0, buf1, area_desc2->fa_size);
+    TEST_ASSERT(rc == 0);
+
+    free(buf1);
+    free(buf2);
+}
+
+static void
+boot_test_util_write_image(const struct image_header *hdr, int slot)
+{
+    uint32_t image_off;
+    uint32_t off;
+    uint8_t flash_id;
+    uint8_t buf[256];
+    int chunk_sz;
+    int rc;
+    int i;
+
+    TEST_ASSERT(slot == 0 || slot == 1);
+
+    flash_id = boot_test_img_addrs[slot].flash_id;
+    off = boot_test_img_addrs[slot].address;
+
+    rc = hal_flash_write(flash_id, off, hdr, sizeof *hdr);
+    TEST_ASSERT(rc == 0);
+
+    off += hdr->ih_hdr_size;
+
+    image_off = 0;
+    while (image_off < hdr->ih_img_size) {
+        if (hdr->ih_img_size - image_off > sizeof buf) {
+            chunk_sz = sizeof buf;
+        } else {
+            chunk_sz = hdr->ih_img_size - image_off;
+        }
+
+        for (i = 0; i < chunk_sz; i++) {
+            buf[i] = boot_test_util_byte_at(slot, image_off + i);
+        }
+
+        rc = hal_flash_write(flash_id, off + image_off, buf, chunk_sz);
+        TEST_ASSERT(rc == 0);
+
+        image_off += chunk_sz;
+    }
+}
+
+static void
+boot_test_util_write_hash(const struct image_header *hdr, int slot)
+{
+    uint8_t tmpdata[1024];
+    uint8_t hash[32];
+    int rc;
+    uint32_t off;
+    uint32_t blk_sz;
+    uint32_t sz;
+    mbedtls_sha256_context ctx;
+    uint8_t flash_id;
+    uint32_t addr;
+    struct image_tlv tlv;
+
+    mbedtls_sha256_init(&ctx);
+    mbedtls_sha256_starts(&ctx, 0);
+
+    flash_id = boot_test_img_addrs[slot].flash_id;
+    addr = boot_test_img_addrs[slot].address;
+
+    sz = hdr->ih_hdr_size + hdr->ih_img_size;
+    for (off = 0; off < sz; off += blk_sz) {
+        blk_sz = sz - off;
+        if (blk_sz > sizeof(tmpdata)) {
+            blk_sz = sizeof(tmpdata);
+        }
+        rc = hal_flash_read(flash_id, addr + off, tmpdata, blk_sz);
+        TEST_ASSERT(rc == 0);
+        mbedtls_sha256_update(&ctx, tmpdata, blk_sz);
+    }
+    mbedtls_sha256_finish(&ctx, hash);
+
+    tlv.it_type = IMAGE_TLV_SHA256;
+    tlv._pad = 0;
+    tlv.it_len = sizeof(hash);
+
+    rc = hal_flash_write(flash_id, addr + off, &tlv, sizeof(tlv));
+    TEST_ASSERT(rc == 0);
+    off += sizeof(tlv);
+    rc = hal_flash_write(flash_id, addr + off, hash, sizeof(hash));
+    TEST_ASSERT(rc == 0);
+}
+
+static void
+boot_test_util_verify_area(const struct flash_area *area_desc,
+                           const struct image_header *hdr,
+                           uint32_t image_addr, int img_msb)
+{
+    struct image_header temp_hdr;
+    uint32_t area_end;
+    uint32_t img_size;
+    uint32_t img_off;
+    uint32_t img_end;
+    uint32_t addr;
+    uint8_t buf[256];
+    int rem_area;
+    int past_image;
+    int chunk_sz;
+    int rem_img;
+    int rc;
+    int i;
+
+    addr = area_desc->fa_off;
+
+    if (hdr != NULL) {
+        img_size = hdr->ih_img_size;
+
+        if (addr == image_addr) {
+            rc = hal_flash_read(area_desc->fa_flash_id, image_addr,
+                                &temp_hdr, sizeof temp_hdr);
+            TEST_ASSERT(rc == 0);
+            TEST_ASSERT(memcmp(&temp_hdr, hdr, sizeof *hdr) == 0);
+
+            addr += hdr->ih_hdr_size;
+        }
+    } else {
+        img_size = 0;
+    }
+
+    area_end = area_desc->fa_off + area_desc->fa_size;
+    img_end = image_addr + img_size;
+    past_image = addr >= img_end;
+
+    while (addr < area_end) {
+        rem_area = area_end - addr;
+        rem_img = img_end - addr;
+
+        if (hdr != NULL) {
+            img_off = addr - image_addr - hdr->ih_hdr_size;
+        } else {
+            img_off = 0;
+        }
+
+        if (rem_area > sizeof buf) {
+            chunk_sz = sizeof buf;
+        } else {
+            chunk_sz = rem_area;
+        }
+
+        rc = hal_flash_read(area_desc->fa_flash_id, addr, buf, chunk_sz);
+        TEST_ASSERT(rc == 0);
+
+        for (i = 0; i < chunk_sz; i++) {
+            if (rem_img > 0) {
+                TEST_ASSERT(buf[i] == boot_test_util_byte_at(img_msb,
+                                                        img_off + i));
+            } else if (past_image) {
+#if 0
+                TEST_ASSERT(buf[i] == 0xff);
+#endif
+            }
+        }
+
+        addr += chunk_sz;
+    }
+}
+
+static void
+boot_test_util_verify_status_clear(void)
+{
+    struct boot_img_trailer bit;
+    const struct flash_area *fap;
+    int rc;
+
+    rc = flash_area_open(FLASH_AREA_IMAGE_0, &fap);
+    TEST_ASSERT(rc == 0);
+
+    rc = flash_area_read(fap, fap->fa_size - sizeof(bit), &bit, sizeof(bit));
+    TEST_ASSERT(rc == 0);
+
+    TEST_ASSERT(bit.bit_copy_start != BOOT_IMG_MAGIC ||
+      bit.bit_copy_done != 0xff);
+}
+
+static void
+boot_test_util_verify_flash(const struct image_header *hdr0, int orig_slot_0,
+                            const struct image_header *hdr1, int orig_slot_1)
+{
+    const struct flash_area *area_desc;
+    int area_idx;
+
+    area_idx = 0;
+
+    while (1) {
+        area_desc = boot_test_area_descs + area_idx;
+        if (area_desc->fa_off == boot_test_img_addrs[1].address &&
+            area_desc->fa_flash_id == boot_test_img_addrs[1].flash_id) {
+            break;
+        }
+
+        boot_test_util_verify_area(area_desc, hdr0,
+                                   boot_test_img_addrs[0].address, orig_slot_0);
+        area_idx++;
+    }
+
+    while (1) {
+        if (area_idx == BOOT_TEST_AREA_IDX_SCRATCH) {
+            break;
+        }
+
+        area_desc = boot_test_area_descs + area_idx;
+        boot_test_util_verify_area(area_desc, hdr1,
+                                   boot_test_img_addrs[1].address, orig_slot_1);
+        area_idx++;
+    }
+}
+
+TEST_CASE(boot_test_nv_ns_10)
+{
+    struct boot_rsp rsp;
+    int rc;
+
+    struct image_header hdr = {
+        .ih_magic = IMAGE_MAGIC,
+        .ih_tlv_size = 4 + 32,
+        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
+        .ih_img_size = 12 * 1024,
+        .ih_flags = IMAGE_F_SHA256,
+        .ih_ver = { 0, 2, 3, 4 },
+    };
+
+    struct boot_req req = {
+        .br_area_descs = boot_test_area_descs,
+        .br_slot_areas = boot_test_slot_areas,
+        .br_num_image_areas = BOOT_TEST_AREA_IDX_SCRATCH + 1,
+        .br_scratch_area_idx = BOOT_TEST_AREA_IDX_SCRATCH,
+        .br_img_sz = (384 * 1024),
+    };
+
+    boot_test_util_init_flash();
+    boot_test_util_write_image(&hdr, 0);
+    boot_test_util_write_hash(&hdr, 0);
+
+    rc = boot_go(&req, &rsp);
+    TEST_ASSERT(rc == 0);
+
+    TEST_ASSERT(memcmp(rsp.br_hdr, &hdr, sizeof hdr) == 0);
+    TEST_ASSERT(rsp.br_flash_id == boot_test_img_addrs[0].flash_id);
+    TEST_ASSERT(rsp.br_image_addr == boot_test_img_addrs[0].address);
+
+    boot_test_util_verify_flash(&hdr, 0, NULL, 0xff);
+    boot_test_util_verify_status_clear();
+}
+
+TEST_CASE(boot_test_nv_ns_01)
+{
+    struct boot_rsp rsp;
+    int rc;
+
+
+    struct image_header hdr = {
+        .ih_magic = IMAGE_MAGIC,
+        .ih_tlv_size = 4 + 32,
+        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
+        .ih_img_size = 10 * 1024,
+        .ih_flags = IMAGE_F_SHA256,
+        .ih_ver = { 1, 2, 3, 432 },
+    };
+
+    struct boot_req req = {
+        .br_area_descs = boot_test_area_descs,
+        .br_slot_areas = boot_test_slot_areas,
+        .br_num_image_areas = BOOT_TEST_AREA_IDX_SCRATCH + 1,
+        .br_scratch_area_idx = BOOT_TEST_AREA_IDX_SCRATCH,
+        .br_img_sz = (384 * 1024),
+    };
+
+    boot_test_util_init_flash();
+    boot_test_util_write_image(&hdr, 1);
+    boot_test_util_write_hash(&hdr, 1);
+
+    boot_vect_write_test(FLASH_AREA_IMAGE_1);
+    rc = boot_go(&req, &rsp);
+    TEST_ASSERT(rc == 0);
+
+    TEST_ASSERT(memcmp(rsp.br_hdr, &hdr, sizeof hdr) == 0);
+    TEST_ASSERT(rsp.br_flash_id == boot_test_img_addrs[0].flash_id);
+    TEST_ASSERT(rsp.br_image_addr == boot_test_img_addrs[0].address);
+
+    boot_test_util_verify_flash(&hdr, 1, NULL, 0xff);
+    boot_test_util_verify_status_clear();
+}
+
+TEST_CASE(boot_test_nv_ns_11)
+{
+    struct boot_rsp rsp;
+    int rc;
+
+    struct image_header hdr0 = {
+        .ih_magic = IMAGE_MAGIC,
+        .ih_tlv_size = 4 + 32,
+        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
+        .ih_img_size = 5 * 1024,
+        .ih_flags = IMAGE_F_SHA256,
+        .ih_ver = { 0, 5, 21, 432 },
+    };
+
+    struct image_header hdr1 = {
+        .ih_magic = IMAGE_MAGIC,
+        .ih_tlv_size = 4 + 32,
+        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
+        .ih_img_size = 32 * 1024,
+        .ih_flags = IMAGE_F_SHA256,
+        .ih_ver = { 1, 2, 3, 432 },
+    };
+
+    struct boot_req req = {
+        .br_area_descs = boot_test_area_descs,
+        .br_slot_areas = boot_test_slot_areas,
+        .br_num_image_areas = BOOT_TEST_AREA_IDX_SCRATCH + 1,
+        .br_scratch_area_idx = BOOT_TEST_AREA_IDX_SCRATCH,
+        .br_img_sz = (384 * 1024),
+    };
+
+    boot_test_util_init_flash();
+    boot_test_util_write_image(&hdr0, 0);
+    boot_test_util_write_hash(&hdr0, 0);
+    boot_test_util_write_image(&hdr1, 1);
+    boot_test_util_write_hash(&hdr1, 1);
+
+    rc = boot_go(&req, &rsp);
+    TEST_ASSERT(rc == 0);
+
+    TEST_ASSERT(memcmp(rsp.br_hdr, &hdr0, sizeof hdr0) == 0);
+    TEST_ASSERT(rsp.br_flash_id == boot_test_img_addrs[0].flash_id);
+    TEST_ASSERT(rsp.br_image_addr == boot_test_img_addrs[0].address);
+
+    boot_test_util_verify_flash(&hdr0, 0, &hdr1, 1);
+    boot_test_util_verify_status_clear();
+}
+
+TEST_CASE(boot_test_vm_ns_10)
+{
+    struct boot_rsp rsp;
+    int rc;
+
+
+    struct image_header hdr = {
+        .ih_magic = IMAGE_MAGIC,
+        .ih_tlv_size = 4 + 32,
+        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
+        .ih_img_size = 12 * 1024,
+        .ih_flags = IMAGE_F_SHA256,
+        .ih_ver = { 0, 2, 3, 4 },
+    };
+
+    struct boot_req req = {
+        .br_area_descs = boot_test_area_descs,
+        .br_slot_areas = boot_test_slot_areas,
+        .br_num_image_areas = BOOT_TEST_AREA_IDX_SCRATCH + 1,
+        .br_scratch_area_idx = BOOT_TEST_AREA_IDX_SCRATCH,
+        .br_img_sz = (384 * 1024),
+    };
+
+    boot_test_util_init_flash();
+    boot_test_util_write_image(&hdr, 0);
+    boot_test_util_write_hash(&hdr, 0);
+
+    rc = boot_go(&req, &rsp);
+    TEST_ASSERT(rc == 0);
+
+    TEST_ASSERT(memcmp(rsp.br_hdr, &hdr, sizeof hdr) == 0);
+    TEST_ASSERT(rsp.br_flash_id == boot_test_img_addrs[0].flash_id);
+    TEST_ASSERT(rsp.br_image_addr == boot_test_img_addrs[0].address);
+
+    boot_test_util_verify_flash(&hdr, 0, NULL, 0xff);
+    boot_test_util_verify_status_clear();
+}
+
+TEST_CASE(boot_test_vm_ns_01)
+{
+    struct boot_rsp rsp;
+    int rc;
+
+    struct image_header hdr = {
+        .ih_magic = IMAGE_MAGIC,
+        .ih_tlv_size = 4 + 32,
+        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
+        .ih_img_size = 10 * 1024,
+        .ih_flags = IMAGE_F_SHA256,
+        .ih_ver = { 1, 2, 3, 432 },
+    };
+
+    struct boot_req req = {
+        .br_area_descs = boot_test_area_descs,
+        .br_slot_areas = boot_test_slot_areas,
+        .br_num_image_areas = BOOT_TEST_AREA_IDX_SCRATCH + 1,
+        .br_scratch_area_idx = BOOT_TEST_AREA_IDX_SCRATCH,
+        .br_img_sz = (384 * 1024),
+    };
+
+    boot_test_util_init_flash();
+    boot_test_util_write_image(&hdr, 1);
+    boot_test_util_write_hash(&hdr, 1);
+
+    rc = boot_vect_write_test(FLASH_AREA_IMAGE_1);
+    TEST_ASSERT(rc == 0);
+
+    rc = boot_go(&req, &rsp);
+    TEST_ASSERT(rc == 0);
+
+    TEST_ASSERT(memcmp(rsp.br_hdr, &hdr, sizeof hdr) == 0);
+    TEST_ASSERT(rsp.br_flash_id == boot_test_img_addrs[0].flash_id);
+    TEST_ASSERT(rsp.br_image_addr == boot_test_img_addrs[0].address);
+
+    boot_test_util_verify_flash(&hdr, 1, NULL, 0xff);
+    boot_test_util_verify_status_clear();
+}
+
+TEST_CASE(boot_test_vm_ns_11_a)
+{
+    struct boot_rsp rsp;
+    int rc;
+
+    struct image_header hdr0 = {
+        .ih_magic = IMAGE_MAGIC,
+        .ih_tlv_size = 4 + 32,
+        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
+        .ih_img_size = 5 * 1024,
+        .ih_flags = IMAGE_F_SHA256,
+        .ih_ver = { 0, 5, 21, 432 },
+    };
+
+    struct image_header hdr1 = {
+        .ih_magic = IMAGE_MAGIC,
+        .ih_tlv_size = 4 + 32,
+        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
+        .ih_img_size = 32 * 1024,
+        .ih_flags = IMAGE_F_SHA256,
+        .ih_ver = { 1, 2, 3, 432 },
+    };
+
+    struct boot_req req = {
+        .br_area_descs = boot_test_area_descs,
+        .br_slot_areas = boot_test_slot_areas,
+        .br_num_image_areas = BOOT_TEST_AREA_IDX_SCRATCH + 1,
+        .br_scratch_area_idx = BOOT_TEST_AREA_IDX_SCRATCH,
+        .br_img_sz = (384 * 1024),
+    };
+
+    boot_test_util_init_flash();
+    boot_test_util_write_image(&hdr0, 0);
+    boot_test_util_write_hash(&hdr0, 0);
+    boot_test_util_write_image(&hdr1, 1);
+    boot_test_util_write_hash(&hdr1, 1);
+
+    rc = boot_go(&req, &rsp);
+    TEST_ASSERT(rc == 0);
+
+    TEST_ASSERT(memcmp(rsp.br_hdr, &hdr0, sizeof hdr0) == 0);
+    TEST_ASSERT(rsp.br_flash_id == boot_test_img_addrs[0].flash_id);
+    TEST_ASSERT(rsp.br_image_addr == boot_test_img_addrs[0].address);
+
+    boot_test_util_verify_flash(&hdr0, 0, &hdr1, 1);
+    boot_test_util_verify_status_clear();
+}
+
+TEST_CASE(boot_test_vm_ns_11_b)
+{
+    struct boot_rsp rsp;
+    int rc;
+
+    struct image_header hdr0 = {
+        .ih_magic = IMAGE_MAGIC,
+        .ih_tlv_size = 4 + 32,
+        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
+        .ih_img_size = 5 * 1024,
+        .ih_flags = IMAGE_F_SHA256,
+        .ih_ver = { 0, 5, 21, 432 },
+    };
+
+    struct image_header hdr1 = {
+        .ih_magic = IMAGE_MAGIC,
+        .ih_tlv_size = 4 + 32,
+        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
+        .ih_img_size = 32 * 1024,
+        .ih_flags = IMAGE_F_SHA256,
+        .ih_ver = { 1, 2, 3, 432 },
+    };
+
+    struct boot_req req = {
+        .br_area_descs = boot_test_area_descs,
+        .br_slot_areas = boot_test_slot_areas,
+        .br_num_image_areas = BOOT_TEST_AREA_IDX_SCRATCH + 1,
+        .br_scratch_area_idx = BOOT_TEST_AREA_IDX_SCRATCH,
+        .br_img_sz = (384 * 1024),
+    };
+
+    boot_test_util_init_flash();
+    boot_test_util_write_image(&hdr0, 0);
+    boot_test_util_write_hash(&hdr0, 0);
+    boot_test_util_write_image(&hdr1, 1);
+    boot_test_util_write_hash(&hdr1, 1);
+
+    rc = boot_vect_write_test(FLASH_AREA_IMAGE_1);
+    TEST_ASSERT(rc == 0);
+
+    rc = boot_go(&req, &rsp);
+    TEST_ASSERT(rc == 0);
+
+    TEST_ASSERT(memcmp(rsp.br_hdr, &hdr1, sizeof hdr1) == 0);
+    TEST_ASSERT(rsp.br_flash_id == boot_test_img_addrs[0].flash_id);
+    TEST_ASSERT(rsp.br_image_addr == boot_test_img_addrs[0].address);
+
+    boot_test_util_verify_flash(&hdr1, 1, &hdr0, 0);
+    boot_test_util_verify_status_clear();
+}
+
+TEST_CASE(boot_test_vm_ns_11_2areas)
+{
+    struct boot_rsp rsp;
+    int rc;
+
+    struct image_header hdr0 = {
+        .ih_magic = IMAGE_MAGIC,
+        .ih_tlv_size = 4 + 32,
+        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
+        .ih_img_size = 5 * 1024,
+        .ih_flags = IMAGE_F_SHA256,
+        .ih_ver = { 0, 5, 21, 432 },
+    };
+
+    struct image_header hdr1 = {
+        .ih_magic = IMAGE_MAGIC,
+        .ih_tlv_size = 4 + 32,
+        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
+        .ih_img_size = 196 * 1024,
+        .ih_flags = IMAGE_F_SHA256,
+        .ih_ver = { 1, 2, 3, 432 },
+    };
+
+    struct boot_req req = {
+        .br_area_descs = boot_test_area_descs,
+        .br_slot_areas = boot_test_slot_areas,
+        .br_num_image_areas = BOOT_TEST_AREA_IDX_SCRATCH + 1,
+        .br_scratch_area_idx = BOOT_TEST_AREA_IDX_SCRATCH,
+        .br_img_sz = (384 * 1024),
+    };
+
+    boot_test_util_init_flash();
+    boot_test_util_write_image(&hdr0, 0);
+    boot_test_util_write_hash(&hdr0, 0);
+    boot_test_util_write_image(&hdr1, 1);
+    boot_test_util_write_hash(&hdr1, 1);
+
+    rc = boot_vect_write_test(FLASH_AREA_IMAGE_1);
+    TEST_ASSERT(rc == 0);
+
+    rc = boot_go(&req, &rsp);
+    TEST_ASSERT(rc == 0);
+
+    TEST_ASSERT(memcmp(rsp.br_hdr, &hdr1, sizeof hdr1) == 0);
+    TEST_ASSERT(rsp.br_flash_id == boot_test_img_addrs[0].flash_id);
+    TEST_ASSERT(rsp.br_image_addr == boot_test_img_addrs[0].address);
+
+    boot_test_util_verify_flash(&hdr1, 1, &hdr0, 0);
+    boot_test_util_verify_status_clear();
+}
+
+TEST_CASE(boot_test_nv_bs_10)
+{
+    struct boot_status status;
+    struct boot_rsp rsp;
+    int rc;
+
+    struct image_header hdr = {
+        .ih_magic = IMAGE_MAGIC,
+        .ih_tlv_size = 4 + 32,
+        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
+        .ih_img_size = 12 * 1024,
+        .ih_flags = IMAGE_F_SHA256,
+        .ih_ver = { 0, 2, 3, 4 },
+    };
+
+    struct boot_req req = {
+        .br_area_descs = boot_test_area_descs,
+        .br_slot_areas = boot_test_slot_areas,
+        .br_num_image_areas = BOOT_TEST_AREA_IDX_SCRATCH + 1,
+        .br_scratch_area_idx = BOOT_TEST_AREA_IDX_SCRATCH,
+        .br_img_sz = (384 * 1024),
+    };
+
+    boot_test_util_init_flash();
+    boot_test_util_write_image(&hdr, 0);
+    boot_test_util_write_hash(&hdr, 0);
+    boot_test_util_swap_areas(boot_test_slot_areas[1],
+      BOOT_TEST_AREA_IDX_SCRATCH);
+#if 0
+    status.length = hdr.ih_hdr_size + hdr.ih_img_size + hdr.ih_tlv_size;
+    status.state = 1;
+
+    rc = boot_write_status(&status);
+    TEST_ASSERT(rc == 0);
+    conf_load();
+#else
+    (void)status;
+#endif
+    rc = boot_go(&req, &rsp);
+    TEST_ASSERT(rc == 0);
+
+    TEST_ASSERT(memcmp(rsp.br_hdr, &hdr, sizeof hdr) == 0);
+    TEST_ASSERT(rsp.br_flash_id == boot_test_img_addrs[0].flash_id);
+    TEST_ASSERT(rsp.br_image_addr == boot_test_img_addrs[0].address);
+
+    boot_test_util_verify_flash(&hdr, 0, NULL, 0xff);
+    boot_test_util_verify_status_clear();
+}
+
+TEST_CASE(boot_test_nv_bs_11)
+{
+    struct boot_status status;
+    struct boot_rsp rsp;
+    int rc;
+
+    struct image_header hdr0 = {
+        .ih_magic = IMAGE_MAGIC,
+        .ih_tlv_size = 4 + 32,
+        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
+        .ih_img_size = 12 * 1024,
+        .ih_flags = IMAGE_F_SHA256,
+        .ih_ver = { 0, 2, 3, 4 },
+    };
+
+    struct image_header hdr1 = {
+        .ih_magic = IMAGE_MAGIC,
+        .ih_tlv_size = 4 + 32,
+        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
+        .ih_img_size = 17 * 1024,
+        .ih_flags = IMAGE_F_SHA256,
+        .ih_ver = { 1, 1, 5, 5 },
+    };
+
+    struct boot_req req = {
+        .br_area_descs = boot_test_area_descs,
+        .br_slot_areas = boot_test_slot_areas,
+        .br_num_image_areas = BOOT_TEST_AREA_IDX_SCRATCH + 1,
+        .br_scratch_area_idx = BOOT_TEST_AREA_IDX_SCRATCH,
+        .br_img_sz = (384 * 1024),
+    };
+
+    boot_test_util_init_flash();
+    boot_test_util_write_image(&hdr0, 0);
+    boot_test_util_write_hash(&hdr0, 0);
+    boot_test_util_write_image(&hdr1, 1);
+    boot_test_util_write_hash(&hdr1, 1);
+    rc = boot_vect_write_test(FLASH_AREA_IMAGE_1);
+    boot_test_util_copy_area(5,
+      BOOT_TEST_AREA_IDX_SCRATCH);
+
+    boot_req_set(&req);
+    status.idx = 0;
+    status.elem_sz = 1;
+    status.state = 1;
+
+    rc = boot_write_status(&status);
+    TEST_ASSERT(rc == 0);
+
+    rc = boot_go(&req, &rsp);
+    TEST_ASSERT(rc == 0);
+
+    TEST_ASSERT(memcmp(rsp.br_hdr, &hdr1, sizeof hdr1) == 0);
+    TEST_ASSERT(rsp.br_flash_id == boot_test_img_addrs[0].flash_id);
+    TEST_ASSERT(rsp.br_image_addr == boot_test_img_addrs[0].address);
+
+    boot_test_util_verify_flash(&hdr1, 1, &hdr0, 0);
+    boot_test_util_verify_status_clear();
+}
+
+TEST_CASE(boot_test_nv_bs_11_2areas)
+{
+    struct boot_status status;
+    struct boot_rsp rsp;
+    int rc;
+
+    struct image_header hdr0 = {
+        .ih_magic = IMAGE_MAGIC,
+        .ih_tlv_size = 4 + 32,
+        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
+        .ih_img_size = 150 * 1024,
+        .ih_flags = IMAGE_F_SHA256,
+        .ih_ver = { 0, 5, 21, 432 },
+    };
+
+    struct image_header hdr1 = {
+        .ih_magic = IMAGE_MAGIC,
+        .ih_tlv_size = 4 + 32,
+        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
+        .ih_img_size = 190 * 1024,
+        .ih_flags = IMAGE_F_SHA256,
+        .ih_ver = { 1, 2, 3, 432 },
+    };
+
+    struct boot_req req = {
+        .br_area_descs = boot_test_area_descs,
+        .br_slot_areas = boot_test_slot_areas,
+        .br_num_image_areas = BOOT_TEST_AREA_IDX_SCRATCH + 1,
+        .br_scratch_area_idx = BOOT_TEST_AREA_IDX_SCRATCH,
+        .br_img_sz = (384 * 1024),
+    };
+
+    boot_test_util_init_flash();
+    boot_test_util_write_image(&hdr0, 0);
+    boot_test_util_write_hash(&hdr0, 0);
+    boot_test_util_write_image(&hdr1, 1);
+    boot_test_util_write_hash(&hdr1, 1);
+    rc = boot_vect_write_test(FLASH_AREA_IMAGE_1);
+
+    boot_test_util_swap_areas(2, 5);
+
+    status.idx = 1;
+    status.elem_sz = 1;
+    status.state = 0;
+
+    rc = boot_write_status(&status);
+    TEST_ASSERT(rc == 0);
+
+    rc = boot_go(&req, &rsp);
+    TEST_ASSERT(rc == 0);
+
+    TEST_ASSERT(memcmp(rsp.br_hdr, &hdr1, sizeof hdr1) == 0);
+    TEST_ASSERT(rsp.br_flash_id == boot_test_img_addrs[0].flash_id);
+    TEST_ASSERT(rsp.br_image_addr == boot_test_img_addrs[0].address);
+
+    boot_test_util_verify_flash(&hdr1, 1, &hdr0, 0);
+    boot_test_util_verify_status_clear();
+}
+
+TEST_CASE(boot_test_vb_ns_11)
+{
+    const struct flash_area *fap;
+    struct boot_img_trailer bit;
+    struct boot_rsp rsp;
+    int rc;
+    int i;
+
+    struct image_header hdr0 = {
+        .ih_magic = IMAGE_MAGIC,
+        .ih_tlv_size = 4 + 32,
+        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
+        .ih_img_size = 5 * 1024,
+        .ih_flags = IMAGE_F_SHA256,
+        .ih_ver = { 0, 5, 21, 432 },
+    };
+
+    struct image_header hdr1 = {
+        .ih_magic = IMAGE_MAGIC,
+        .ih_tlv_size = 4 + 32,
+        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
+        .ih_img_size = 32 * 1024,
+        .ih_flags = IMAGE_F_SHA256,
+        .ih_ver = { 1, 2, 3, 432 },
+    };
+
+    struct boot_req req = {
+        .br_area_descs = boot_test_area_descs,
+        .br_slot_areas = boot_test_slot_areas,
+        .br_num_image_areas = BOOT_TEST_AREA_IDX_SCRATCH + 1,
+        .br_scratch_area_idx = BOOT_TEST_AREA_IDX_SCRATCH,
+        .br_img_sz = (384 * 1024),
+    };
+
+    boot_test_util_init_flash();
+    boot_test_util_write_image(&hdr0, 0);
+    boot_test_util_write_hash(&hdr0, 0);
+    boot_test_util_write_image(&hdr1, 1);
+    boot_test_util_write_hash(&hdr1, 1);
+
+    rc = flash_area_open(FLASH_AREA_IMAGE_0, &fap);
+    TEST_ASSERT(rc == 0);
+
+    memset(&bit, 0xff, sizeof(bit));
+    bit.bit_copy_start = BOOT_IMG_MAGIC;
+    bit.bit_copy_done = 0;
+    bit.bit_img_ok = 1;
+
+    rc = flash_area_write(fap, fap->fa_size - sizeof(bit), &bit, sizeof(bit));
+    TEST_ASSERT(rc == 0);
+
+    rc = boot_vect_write_test(FLASH_AREA_IMAGE_1);
+    TEST_ASSERT(rc == 0);
+
+    /* First boot should use the test image. */
+    rc = boot_go(&req, &rsp);
+    TEST_ASSERT(rc == 0);
+
+    TEST_ASSERT(memcmp(rsp.br_hdr, &hdr1, sizeof hdr1) == 0);
+    TEST_ASSERT(rsp.br_flash_id == boot_test_img_addrs[0].flash_id);
+    TEST_ASSERT(rsp.br_image_addr == boot_test_img_addrs[0].address);
+
+    boot_test_util_verify_flash(&hdr1, 1, &hdr0, 0);
+    boot_test_util_verify_status_clear();
+
+    /* Ensure all subsequent boots use the main image. */
+    for (i = 0; i < 10; i++) {
+        rc = boot_go(&req, &rsp);
+        TEST_ASSERT(rc == 0);
+
+        TEST_ASSERT(memcmp(rsp.br_hdr, &hdr0, sizeof hdr0) == 0);
+        TEST_ASSERT(rsp.br_flash_id == boot_test_img_addrs[0].flash_id);
+        TEST_ASSERT(rsp.br_image_addr == boot_test_img_addrs[0].address);
+
+        boot_test_util_verify_flash(&hdr0, 0, &hdr1, 1);
+        boot_test_util_verify_status_clear();
+        boot_vect_write_main();
+    }
+}
+
+TEST_CASE(boot_test_no_hash)
+{
+    struct boot_rsp rsp;
+    int rc;
+
+    struct image_header hdr0 = {
+        .ih_magic = IMAGE_MAGIC,
+        .ih_tlv_size = 4 + 32,
+        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
+        .ih_img_size = 12 * 1024,
+        .ih_flags = IMAGE_F_SHA256,
+        .ih_ver = { 0, 2, 3, 4 },
+    };
+    struct image_header hdr1 = {
+        .ih_magic = IMAGE_MAGIC,
+        .ih_tlv_size = 0,
+        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
+        .ih_img_size = 32 * 1024,
+        .ih_flags = 0,
+        .ih_ver = { 1, 2, 3, 432 },
+    };
+
+    struct boot_req req = {
+        .br_area_descs = boot_test_area_descs,
+        .br_slot_areas = boot_test_slot_areas,
+        .br_num_image_areas = BOOT_TEST_AREA_IDX_SCRATCH + 1,
+        .br_scratch_area_idx = BOOT_TEST_AREA_IDX_SCRATCH,
+        .br_img_sz = (384 * 1024),
+    };
+
+    boot_test_util_init_flash();
+    boot_test_util_write_image(&hdr0, 0);
+    boot_test_util_write_hash(&hdr0, 0);
+    boot_test_util_write_image(&hdr1, 1);
+
+    rc = boot_vect_write_test(FLASH_AREA_IMAGE_1);
+    TEST_ASSERT(rc == 0);
+
+    rc = boot_go(&req, &rsp);
+    TEST_ASSERT(rc == 0);
+
+    TEST_ASSERT(memcmp(rsp.br_hdr, &hdr0, sizeof hdr0) == 0);
+
+    boot_test_util_verify_flash(&hdr0, 0, NULL, 0xff);
+    boot_test_util_verify_status_clear();
+}
+
+TEST_CASE(boot_test_no_flag_has_hash)
+{
+    struct boot_rsp rsp;
+    int rc;
+
+    struct image_header hdr0 = {
+        .ih_magic = IMAGE_MAGIC,
+        .ih_tlv_size = 4 + 32,
+        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
+        .ih_img_size = 12 * 1024,
+        .ih_flags = IMAGE_F_SHA256,
+        .ih_ver = { 0, 2, 3, 4 },
+    };
+    struct image_header hdr1 = {
+        .ih_magic = IMAGE_MAGIC,
+        .ih_tlv_size = 4 + 32,
+        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
+        .ih_img_size = 32 * 1024,
+        .ih_flags = 0,
+        .ih_ver = { 1, 2, 3, 432 },
+    };
+
+    struct boot_req req = {
+        .br_area_descs = boot_test_area_descs,
+        .br_slot_areas = boot_test_slot_areas,
+        .br_num_image_areas = BOOT_TEST_AREA_IDX_SCRATCH + 1,
+        .br_scratch_area_idx = BOOT_TEST_AREA_IDX_SCRATCH,
+        .br_img_sz = (384 * 1024),
+    };
+
+    boot_test_util_init_flash();
+    boot_test_util_write_image(&hdr0, 0);
+    boot_test_util_write_hash(&hdr0, 0);
+    boot_test_util_write_image(&hdr1, 1);
+    boot_test_util_write_hash(&hdr1, 1);
+
+    rc = boot_vect_write_test(FLASH_AREA_IMAGE_1);
+    TEST_ASSERT(rc == 0);
+
+    rc = boot_go(&req, &rsp);
+    TEST_ASSERT(rc == 0);
+
+    TEST_ASSERT(memcmp(rsp.br_hdr, &hdr0, sizeof hdr0) == 0);
+
+    boot_test_util_verify_flash(&hdr0, 0, NULL, 0xff);
+    boot_test_util_verify_status_clear();
+}
+
+TEST_CASE(boot_test_invalid_hash)
+{
+    struct boot_rsp rsp;
+    int rc;
+
+    struct image_header hdr0 = {
+        .ih_magic = IMAGE_MAGIC,
+        .ih_tlv_size = 4 + 32,
+        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
+        .ih_img_size = 12 * 1024,
+        .ih_flags = IMAGE_F_SHA256,
+        .ih_ver = { 0, 2, 3, 4 },
+    };
+    struct image_header hdr1 = {
+        .ih_magic = IMAGE_MAGIC,
+        .ih_tlv_size = 4 + 32,
+        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
+        .ih_img_size = 32 * 1024,
+        .ih_flags = 0,
+        .ih_ver = { 1, 2, 3, 432 },
+    };
+
+    struct boot_req req = {
+        .br_area_descs = boot_test_area_descs,
+        .br_slot_areas = boot_test_slot_areas,
+        .br_num_image_areas = BOOT_TEST_AREA_IDX_SCRATCH + 1,
+        .br_scratch_area_idx = BOOT_TEST_AREA_IDX_SCRATCH,
+        .br_img_sz = (384 * 1024),
+    };
+
+    struct image_tlv tlv = {
+        .it_type = IMAGE_TLV_SHA256,
+        .it_len = 32
+    };
+    boot_test_util_init_flash();
+    boot_test_util_write_image(&hdr0, 0);
+    boot_test_util_write_hash(&hdr0, 0);
+    boot_test_util_write_image(&hdr1, 1);
+    rc = hal_flash_write(boot_test_img_addrs[1].flash_id,
+      boot_test_img_addrs[1].address + hdr1.ih_hdr_size + hdr1.ih_img_size,
+      &tlv, sizeof(tlv));
+    TEST_ASSERT(rc == 0);
+
+    rc = boot_vect_write_test(FLASH_AREA_IMAGE_1);
+    TEST_ASSERT(rc == 0);
+
+    rc = boot_go(&req, &rsp);
+    TEST_ASSERT(rc == 0);
+
+    TEST_ASSERT(memcmp(rsp.br_hdr, &hdr0, sizeof hdr0) == 0);
+
+    boot_test_util_verify_flash(&hdr0, 0, NULL, 0xff);
+    boot_test_util_verify_status_clear();
+}
+
+TEST_SUITE(boot_test_main)
+{
+    boot_test_nv_ns_10();
+    boot_test_nv_ns_01();
+    boot_test_nv_ns_11();
+    boot_test_vm_ns_10();
+    boot_test_vm_ns_01();
+    boot_test_vm_ns_11_a();
+    boot_test_vm_ns_11_b();
+    boot_test_vm_ns_11_2areas();
+    boot_test_nv_bs_10();
+    boot_test_nv_bs_11();
+    boot_test_nv_bs_11_2areas();
+    boot_test_vb_ns_11();
+    boot_test_no_hash();
+    boot_test_no_flag_has_hash();
+    boot_test_invalid_hash();
+}
+
+int
+boot_test_all(void)
+{
+    boot_test_main();
+    return tu_any_failed;
+}
+
+#if MYNEWT_VAL(SELFTEST)
+
+int
+main(int argc, char **argv)
+{
+    tu_config.tc_print_results = 1;
+    tu_parse_args(argc, argv);
+
+    tu_init();
+
+    boot_test_all();
+
+    return tu_any_failed;
+}
+
+#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/boot/split/README.md
----------------------------------------------------------------------
diff --git a/boot/split/README.md b/boot/split/README.md
new file mode 100644
index 0000000..1ef4cc5
--- /dev/null
+++ b/boot/split/README.md
@@ -0,0 +1,63 @@
+
+
+<img src="http://mynewt.apache.org/img/logo.svg" width="250" alt="Apache Mynewt">
+
+## Overview
+
+`libs/split` is a library required to build split applications.  When building a split application you must include `libs/split` in your loader and your application
+
+## Split Image
+
+Split applications allow the user to build the application content separate from the library content by splitting an application into two pieces:
+
+* A "loader" which contains a separate application that can perform upgrades and manage split images
+* A "split app" which contains the main application content and references the libraries in the loader by static linkage
+
+See [split image architecture](http://mynewt.apache.org/latest/os/modules/split/split/) for the details of split image design.
+
+
+## Contents
+
+`libs/split` contains the following components
+
+* The split app configuration which tells the system whether to run the "loader" or the "app"
+* The newrmgr commands to access split functionality
+* The functions used by the loader to check and run a split application
+
+## Examples
+
+### Split App
+
+Your split application and loader must initialize the library by calling
+
+```
+#include "split/split.h"
+void split_app_init(void);
+```
+
+This registers the configuration and commands for split applications.
+
+### Loader
+
+Your loader can call 
+
+```
+int split_app_go(void **entry, int toBoot);
+```
+
+to check whether the split application can be run.  A example is shown below
+
+```
+#include "split/split.h"
+#include "bootutil/bootutil.h"
+    {
+        void *entry;
+        rc = split_app_go(&entry, true);
+        if(rc == 0) {
+            system_start(entry);
+        }
+    }
+```
+
+
+

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/boot/split/include/split/split.h
----------------------------------------------------------------------
diff --git a/boot/split/include/split/split.h b/boot/split/include/split/split.h
new file mode 100644
index 0000000..0cf78e3
--- /dev/null
+++ b/boot/split/include/split/split.h
@@ -0,0 +1,57 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 _SPLIT_H__
+#define _SPLIT_H__
+
+#define SPLIT_NMGR_OP_SPLIT 0
+
+typedef enum {
+    SPLIT_NONE,
+    SPLIT_TEST,
+    SPLIT_RUN,
+} split_mode_t;
+
+
+typedef enum {
+    SPLIT_INVALID,
+    SPLIT_NOT_MATCHING,
+    SPLIT_MATCHING,
+} split_status_t;
+
+/*
+  * Initializes the split application library */
+void split_app_init(void);
+
+/**
+  * checks the split application state.
+  * If the application is configured to be run (and valid)
+  * returns zero and puts the entry data into entry. NOTE:
+  * Entry data is not a function pointer, but a pointer
+  * suitable to call system_start
+  *
+  * If toBoot is true, also performs the necessary steps
+  * to prepare to boot.  An application may set toBoot to
+  * false and call this function to check whether the split
+  * application is bootable.
+ *
+ * @Returns zero on success, non-zero on failures */
+int split_app_go(void **entry, int toboot);
+
+#endif /* _SPLIT_H__ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/boot/split/include/split/split_priv.h
----------------------------------------------------------------------
diff --git a/boot/split/include/split/split_priv.h b/boot/split/include/split/split_priv.h
new file mode 100644
index 0000000..0478b75
--- /dev/null
+++ b/boot/split/include/split/split_priv.h
@@ -0,0 +1,30 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 SPLIT_PRIV_H
+#define SPLIT_PRIV_H
+
+int split_conf_init(void);
+int split_nmgr_register(void);
+int split_read_split(split_mode_t *split);
+int split_write_split(split_mode_t mode);
+split_status_t split_check_status(void);
+
+#endif /* SPLIT_PRIV_H */
+

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/boot/split/pkg.yml
----------------------------------------------------------------------
diff --git a/boot/split/pkg.yml b/boot/split/pkg.yml
new file mode 100644
index 0000000..44574fa
--- /dev/null
+++ b/boot/split/pkg.yml
@@ -0,0 +1,30 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+#
+
+pkg.name: boot/split
+pkg.description: The split image library helps manage and configure split image operation
+pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
+pkg.homepage: "http://mynewt.apache.org/"
+pkg.keywords:
+    - split
+
+
+pkg.deps: 
+    - boot/bootutil
+

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/boot/split/src/split.c
----------------------------------------------------------------------
diff --git a/boot/split/src/split.c b/boot/split/src/split.c
new file mode 100644
index 0000000..cd0e528
--- /dev/null
+++ b/boot/split/src/split.c
@@ -0,0 +1,77 @@
+
+#include <assert.h>
+#include <bootutil/bootutil_misc.h>
+#include <bootutil/image.h>
+#include <bootutil/loader.h>
+#include <split/split.h>
+#include <split/split_priv.h>
+
+#define LOADER_IMAGE_SLOT    0
+#define SPLIT_IMAGE_SLOT    1
+#define SPLIT_TOTAL_IMAGES  2
+
+void
+split_app_init(void)
+{
+    int rc;
+
+    rc = split_conf_init();
+    assert(rc==0);
+
+    rc = split_nmgr_register();
+    assert(rc==0);
+}
+
+split_status_t
+split_check_status(void)
+{
+    void *entry;
+    int rc;
+
+    rc = split_go(LOADER_IMAGE_SLOT, SPLIT_IMAGE_SLOT, &entry);
+
+    if(rc == SPLIT_GO_ERR) {
+        return SPLIT_INVALID;
+    } else if (rc) {
+    }
+
+    return SPLIT_MATCHING;
+}
+
+/**
+ * This validates and provides the loader image data
+ *
+ * @param req                   Contains information about the flash layout.
+ * @param rsp                   On success, indicates how booting should occur.
+ *
+ * @return                      0 on success; nonzero on failure.
+ */
+int
+split_app_go(void **entry, int toboot)
+{
+    split_mode_t split;
+    int rc;
+
+    if (toboot) {
+        /* if we can't read this, then we don't boot an app */
+        rc = split_read_split(&split);
+        if(rc) {
+            return -1;
+        }
+
+        /* if we are told not to, then we don't boot an app */
+        if (split == SPLIT_NONE) {
+            return -1;
+        }
+
+        /* if this is a one-time test, reset the split mode */
+        if (split == SPLIT_TEST) {
+            split_write_split(SPLIT_NONE);
+        }
+    }
+
+    rc = split_go(LOADER_IMAGE_SLOT, SPLIT_IMAGE_SLOT, entry);
+
+    return (rc);
+}
+

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/boot/split/src/split_config.c
----------------------------------------------------------------------
diff --git a/boot/split/src/split_config.c b/boot/split/src/split_config.c
new file mode 100644
index 0000000..57332da
--- /dev/null
+++ b/boot/split/src/split_config.c
@@ -0,0 +1,95 @@
+
+#include <assert.h>
+#include <string.h>
+#include <config/config.h>
+#include <split/split.h>
+#include <split/split_priv.h>
+
+#define LOADER_IMAGE_SLOT    0
+#define SPLIT_IMAGE_SLOT    1
+#define SPLIT_TOTAL_IMAGES  2
+
+
+static char *split_conf_get(int argc, char **argv, char *buf, int max_len);
+static int split_conf_set(int argc, char **argv, char *val);
+static int split_conf_commit(void);
+static int split_conf_export(void (*func)(char *name, char *val), enum conf_export_tgt tgt);
+
+static struct conf_handler split_conf_handler = {
+    .ch_name = "split",
+    .ch_get =split_conf_get,
+    .ch_set = split_conf_set,
+    .ch_commit = split_conf_commit,
+    .ch_export = split_conf_export
+};
+
+static int8_t split_status;
+
+int
+split_conf_init(void)
+{
+    int rc;
+
+    rc = conf_register(&split_conf_handler);
+
+    return rc;
+}
+
+
+static char *
+split_conf_get(int argc, char **argv, char *buf, int max_len)
+{
+    if (argc == 1) {
+        if (!strcmp(argv[0], "status")) {
+            return conf_str_from_value(CONF_INT8, &split_status, buf, max_len);
+        }
+    }
+    return NULL;
+}
+
+static int
+split_conf_set(int argc, char **argv, char *val)
+{
+    if (argc == 1) {
+        if (!strcmp(argv[0], "status")) {
+            return CONF_VALUE_SET(val, CONF_INT8, split_status);
+        }
+    }
+    return -1;
+}
+
+static int
+split_conf_commit(void)
+{
+    return 0;
+}
+
+static int
+split_conf_export(void (*func)(char *name, char *val), enum conf_export_tgt tgt)
+{
+    char buf[4];
+
+    conf_str_from_value(CONF_INT8, &split_status, buf, sizeof(buf));
+    func("split/status", buf);
+    return 0;
+}
+
+int
+split_read_split(split_mode_t *split)
+{
+    *split = (split_mode_t) split_status;
+    return 0;
+}
+
+int
+split_write_split(split_mode_t split)
+{
+    char str[CONF_STR_FROM_BYTES_LEN(sizeof(split_mode_t))];
+
+    split_status = (int8_t) split;
+    if (!conf_str_from_value(CONF_INT8, &split_status, str, sizeof(str))) {
+        return -1;
+    }
+    return conf_save_one("split/status", str);
+}
+

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/boot/split/src/split_netmgr.c
----------------------------------------------------------------------
diff --git a/boot/split/src/split_netmgr.c b/boot/split/src/split_netmgr.c
new file mode 100644
index 0000000..7d2e7dc
--- /dev/null
+++ b/boot/split/src/split_netmgr.c
@@ -0,0 +1,149 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include <json/json.h>
+#include <newtmgr/newtmgr.h>
+#include <bootutil/bootutil_misc.h>
+#include <bootutil/image.h>
+#include <split/split.h>
+#include <split/split_priv.h>
+
+
+static int imgr_splitapp_read(struct nmgr_jbuf *njb);
+static int imgr_splitapp_write(struct nmgr_jbuf *njb);
+
+static const struct nmgr_handler split_nmgr_handlers[] = {
+    [SPLIT_NMGR_OP_SPLIT] = {
+        .nh_read = imgr_splitapp_read,
+        .nh_write = imgr_splitapp_write
+    },
+};
+
+static struct nmgr_group split_nmgr_group = {
+    .ng_handlers = (struct nmgr_handler *)split_nmgr_handlers,
+    .ng_handlers_count =
+        sizeof(split_nmgr_handlers) / sizeof(split_nmgr_handlers[0]),
+    .ng_group_id = NMGR_GROUP_ID_SPLIT,
+};
+
+int
+split_nmgr_register(void)
+{
+    int rc;
+    rc = nmgr_group_register(&split_nmgr_group);
+    return (rc);
+}
+
+int
+imgr_splitapp_read(struct nmgr_jbuf *njb)
+{
+    int rc;
+    int x;
+    split_mode_t split;
+    struct json_encoder *enc;
+    struct json_value jv;
+
+    enc = &njb->njb_enc;
+
+    json_encode_object_start(enc);
+
+    rc = split_read_split(&split);
+    if (!rc) {
+        x = split;
+    } else {
+        x = SPLIT_NONE;
+    }
+    JSON_VALUE_INT(&jv, x)
+    json_encode_object_entry(enc, "splitMode", &jv);
+
+    x = split_check_status();
+    JSON_VALUE_INT(&jv, x)
+    json_encode_object_entry(enc, "splitStatus", &jv);
+
+    JSON_VALUE_INT(&jv, NMGR_ERR_EOK);
+    json_encode_object_entry(enc, "rc", &jv);
+
+    json_encode_object_finish(enc);
+
+    return 0;
+}
+
+int
+imgr_splitapp_write(struct nmgr_jbuf *njb)
+{
+    long long int split_mode;
+    long long int send_split_status;  /* ignored */
+    long long int sent_rc; /* ignored */
+    const struct json_attr_t split_write_attr[4] = {
+        [0] =
+        {
+            .attribute = "splitMode",
+            .type = t_integer,
+            .addr.integer = &split_mode,
+            .nodefault = true,
+        },
+        [1] =
+        {
+            .attribute = "splitStatus",
+            .type = t_integer,
+            .addr.integer = &send_split_status,
+            .nodefault = true,
+        },
+        [2] =
+        {
+            .attribute = "rc",
+            .type = t_integer,
+            .addr.integer = &sent_rc,
+            .nodefault = true,
+        },
+        [3] =
+        {
+            .attribute = NULL
+        }
+    };
+    struct json_encoder *enc;
+    struct json_value jv;
+    int rc;
+
+    rc = json_read_object(&njb->njb_buf, split_write_attr);
+    if (rc) {
+        rc = NMGR_ERR_EINVAL;
+        goto err;
+    }
+
+    rc = split_write_split((split_mode_t) split_mode);
+    if (rc) {
+        rc = NMGR_ERR_EINVAL;
+        goto err;
+    }
+
+    enc = &njb->njb_enc;
+
+    json_encode_object_start(enc);
+
+    JSON_VALUE_INT(&jv, NMGR_ERR_EOK);
+    json_encode_object_entry(enc, "rc", &jv);
+
+    json_encode_object_finish(enc);
+
+    return 0;
+err:
+    nmgr_jbuf_setoerr(njb, rc);
+    return 0;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/drivers/adc/adc_stm32f4/include/adc_stm32f4/adc_stm32f4.h
----------------------------------------------------------------------
diff --git a/drivers/adc/adc_stm32f4/include/adc_stm32f4/adc_stm32f4.h b/drivers/adc/adc_stm32f4/include/adc_stm32f4/adc_stm32f4.h
deleted file mode 100644
index 31f0bb4..0000000
--- a/drivers/adc/adc_stm32f4/include/adc_stm32f4/adc_stm32f4.h
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 __ADC_STM32F4_H__
-#define __ADC_STM32F4_H__
-
-#include <adc/adc.h>
-
-/* Mynewt HAL Port pin mapping */
-#define ADC123_CH0_PIN    0
-#define ADC123_CH1_PIN    1
-#define ADC123_CH2_PIN    2
-#define ADC123_CH3_PIN    3
-#define ADC12_CH4_PIN     4
-#define ADC12_CH5_PIN     5
-#define ADC12_CH6_PIN     6
-#define ADC12_CH7_PIN     7
-#define ADC12_CH8_PIN     16
-#define ADC12_CH9_PIN     17
-#define ADC3_CH4_PIN      86
-#define ADC3_CH5_PIN      87
-#define ADC3_CH6_PIN      88
-#define ADC3_CH7_PIN      89
-#define ADC3_CH8_PIN      90
-#define ADC3_CH9_PIN      83
-#define ADC123_CH10_PIN   32
-#define ADC123_CH11_PIN   33
-#define ADC123_CH12_PIN   34
-#define ADC123_CH13_PIN   35
-#define ADC12_CH14_PIN    36
-#define ADC12_CH15_PIN    37
-#define ADC3_CH14_PIN     84
-#define ADC3_CH15_PIN     85
-
-struct stm32f4_adc_dev_cfg {
-    uint8_t sac_chan_count;
-    void *sac_chans;
-    void *primarybuf;
-    void *secondarybuf;
-    int buflen;
-    ADC_HandleTypeDef *sac_adc_handle;
-};
-
-int stm32f4_adc_dev_init(struct os_dev *, void *);
-
-#endif /* __ADC_H__ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/drivers/adc/adc_stm32f4/pkg.yml
----------------------------------------------------------------------
diff --git a/drivers/adc/adc_stm32f4/pkg.yml b/drivers/adc/adc_stm32f4/pkg.yml
deleted file mode 100644
index 25a2c71..0000000
--- a/drivers/adc/adc_stm32f4/pkg.yml
+++ /dev/null
@@ -1,34 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you 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.
-#
-
-pkg.name: drivers/adc/adc_stm32f4
-pkg.description: ADC driver for the STM32F4 series of processors.
-pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
-pkg.homepage: "http://mynewt.apache.org/"
-pkg.keywords:
-pkg.features:
-    - ADC_STM32F4
-pkg.apis:
-    - ADC_HW_IMPL
-pkg.deps:
-   - drivers/adc
-pkg.deps.TEST:
-   - hw/hal
-   - hw/mcu/stm/stm32f4xx
-   - libs/testutil

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/drivers/adc/adc_stm32f4/src/adc_stm32f4.c
----------------------------------------------------------------------
diff --git a/drivers/adc/adc_stm32f4/src/adc_stm32f4.c b/drivers/adc/adc_stm32f4/src/adc_stm32f4.c
deleted file mode 100644
index fba9dd2..0000000
--- a/drivers/adc/adc_stm32f4/src/adc_stm32f4.c
+++ /dev/null
@@ -1,735 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-
-#include <hal/hal_bsp.h>
-#include <assert.h>
-#include <os/os.h>
-#include <bsp/cmsis_nvic.h>
-#include "stm32f4xx_hal_dma.h"
-#include "stm32f4xx_hal_adc.h"
-#include "stm32f4xx_hal_rcc.h"
-#include "stm32f4xx_hal_cortex.h"
-#include "stm32f4xx_hal.h"
-#include "adc_stm32f4/adc_stm32f4.h"
-#include "stm32f4xx_hal_dma.h"
-#include "mcu/stm32f4xx_mynewt_hal.h"
-#include "syscfg/syscfg.h"
-
-#if MYNEWT_VAL(ADC_1)||MYNEWT_VAL(ADC_2)||MYNEWT_VAL(ADC_3)
-#include <adc/adc.h>
-#endif
-
-#define STM32F4_IS_DMA_ADC_CHANNEL(CHANNEL) ((CHANNEL) <= DMA_CHANNEL_2)
-
-static DMA_HandleTypeDef *dma_handle[5];
-static struct adc_dev *adc_dma[5];
-
-struct stm32f4_adc_stats {
-    uint16_t adc_events;
-    uint16_t adc_error;
-    uint16_t adc_dma_xfer_failed;
-    uint16_t adc_dma_xfer_aborted;
-    uint16_t adc_dma_xfer_complete;
-    uint16_t adc_dma_start_error;
-    uint16_t adc_dma_overrun;
-    uint16_t adc_internal_error;
-};
-
-static struct stm32f4_adc_stats stm32f4_adc_stats;
-
-static void
-stm32f4_adc_clk_enable(ADC_HandleTypeDef *hadc) {
-    uintptr_t adc_addr = (uintptr_t)hadc->Instance;
-
-    switch (adc_addr) {
-        case (uintptr_t)ADC1:
-            __HAL_RCC_ADC1_CLK_ENABLE();
-            break;
-        case (uintptr_t)ADC2:
-            __HAL_RCC_ADC2_CLK_ENABLE();
-            break;
-        case (uintptr_t)ADC3:
-            __HAL_RCC_ADC3_CLK_ENABLE();
-            break;
-        default:
-            assert(0);
-    }
-}
-
-static void
-stm32f4_adc_clk_disable(ADC_HandleTypeDef *hadc) {
-    uintptr_t adc_addr = (uintptr_t)hadc->Instance;
-
-    switch (adc_addr) {
-        case (uintptr_t)ADC1:
-            __HAL_RCC_ADC1_CLK_DISABLE();
-            break;
-        case (uintptr_t)ADC2:
-            __HAL_RCC_ADC2_CLK_DISABLE();
-            break;
-        case (uintptr_t)ADC3:
-            __HAL_RCC_ADC3_CLK_DISABLE();
-            break;
-        default:
-            assert(0);
-    }
-}
-
-static int
-stm32f4_resolve_adc_gpio(ADC_HandleTypeDef *adc, uint8_t cnum, GPIO_InitTypeDef *gpio)
-{
-    uintptr_t adc_addr = (uintptr_t)adc->Instance;
-    uint32_t pin;
-    int rc;
-
-    rc = OS_OK;
-    switch (adc_addr) {
-        case (uintptr_t)ADC1:
-        case (uintptr_t)ADC2:
-            switch(cnum) {
-                case ADC_CHANNEL_4:
-                    pin = ADC12_CH4_PIN;
-                    goto done;
-                case ADC_CHANNEL_5:
-                    pin = ADC12_CH5_PIN;
-                    goto done;
-                case ADC_CHANNEL_6:
-                    pin = ADC12_CH6_PIN;
-                    goto done;
-                case ADC_CHANNEL_7:
-                    pin = ADC12_CH7_PIN;
-                    goto done;
-                case ADC_CHANNEL_8:
-                    pin = ADC12_CH8_PIN;
-                    goto done;
-                case ADC_CHANNEL_9:
-                    pin = ADC12_CH9_PIN;
-                    goto done;
-                case ADC_CHANNEL_14:
-                    pin = ADC12_CH14_PIN;
-                    goto done;
-                case ADC_CHANNEL_15:
-                    pin = ADC12_CH15_PIN;
-                    goto done;
-            }
-        /*
-         * Falling through intentionally as ADC_3 contains seperate pins for
-         * Channels that ADC_1 and ADC_2 contain as well.
-         */
-        case (uintptr_t)ADC3:
-            switch(cnum) {
-                case ADC_CHANNEL_0:
-                    pin = ADC123_CH0_PIN;
-                    goto done;
-                case ADC_CHANNEL_1:
-                    pin = ADC123_CH1_PIN;
-                    goto done;
-                case ADC_CHANNEL_2:
-                    pin = ADC123_CH2_PIN;
-                    goto done;
-                case ADC_CHANNEL_3:
-                    pin = ADC123_CH3_PIN;
-                    goto done;
-                case ADC_CHANNEL_4:
-                    pin = ADC3_CH4_PIN;
-                    goto done;
-                case ADC_CHANNEL_5:
-                    pin = ADC3_CH5_PIN;
-                    goto done;
-                case ADC_CHANNEL_6:
-                    pin = ADC3_CH6_PIN;
-                    goto done;
-                case ADC_CHANNEL_7:
-                    pin = ADC3_CH7_PIN;
-                    goto done;
-                case ADC_CHANNEL_8:
-                    pin = ADC3_CH8_PIN;
-                    goto done;
-                case ADC_CHANNEL_9:
-                    pin = ADC3_CH9_PIN;
-                    goto done;
-                case ADC_CHANNEL_10:
-                    pin = ADC123_CH10_PIN;
-                    goto done;
-                case ADC_CHANNEL_11:
-                    pin = ADC123_CH11_PIN;
-                    goto done;
-                case ADC_CHANNEL_12:
-                    pin = ADC123_CH12_PIN;
-                    goto done;
-                case ADC_CHANNEL_13:
-                    pin = ADC123_CH13_PIN;
-                    goto done;
-                case ADC_CHANNEL_14:
-                    pin = ADC3_CH14_PIN;
-                    goto done;
-                case ADC_CHANNEL_15:
-                    pin = ADC3_CH15_PIN;
-                    goto done;
-            }
-        default:
-            rc = OS_EINVAL;
-            return rc;
-    }
-done:
-    *gpio = (GPIO_InitTypeDef) {
-        .Pin = pin,
-        .Mode = GPIO_MODE_ANALOG,
-        .Pull = GPIO_NOPULL,
-        .Alternate = pin
-    };
-    return rc;
-}
-
-static IRQn_Type
-stm32f4_resolve_adc_dma_irq(DMA_HandleTypeDef *hdma)
-{
-    uintptr_t stream_addr = (uintptr_t)hdma->Instance;
-
-    assert(STM32F4_IS_DMA_ADC_CHANNEL(hdma->Init.Channel));
-
-    switch(stream_addr) {
-        /* DMA2 */
-        case (uintptr_t)DMA2_Stream0:
-            return DMA2_Stream0_IRQn;
-        case (uintptr_t)DMA2_Stream1:
-            return DMA2_Stream1_IRQn;
-        case (uintptr_t)DMA2_Stream2:
-            return DMA2_Stream2_IRQn;
-        case (uintptr_t)DMA2_Stream3:
-            return DMA2_Stream3_IRQn;
-        case (uintptr_t)DMA2_Stream4:
-            return DMA2_Stream4_IRQn;
-        default:
-            assert(0);
-    }
-}
-
-static void
-dma2_stream0_irq_handler(void)
-{
-    HAL_DMA_IRQHandler(dma_handle[0]);
-}
-
-static void
-dma2_stream1_irq_handler(void)
-{
-    HAL_DMA_IRQHandler(dma_handle[1]);
-}
-
-static void
-dma2_stream2_irq_handler(void)
-{
-    HAL_DMA_IRQHandler(dma_handle[2]);
-}
-
-static void
-dma2_stream3_irq_handler(void)
-{
-    HAL_DMA_IRQHandler(dma_handle[3]);
-}
-
-static void
-dma2_stream4_irq_handler(void)
-{
-    HAL_DMA_IRQHandler(dma_handle[4]);
-}
-
-uint32_t
-stm32f4_resolve_adc_dma_irq_handler(DMA_HandleTypeDef *hdma)
-{
-    switch((uintptr_t)hdma->Instance) {
-        /* DMA2 */
-        case (uintptr_t)DMA2_Stream0:
-            return (uint32_t)&dma2_stream0_irq_handler;
-        case (uintptr_t)DMA2_Stream1:
-            return (uint32_t)&dma2_stream1_irq_handler;
-        case (uintptr_t)DMA2_Stream2:
-            return (uint32_t)&dma2_stream2_irq_handler;
-        case (uintptr_t)DMA2_Stream3:
-            return (uint32_t)&dma2_stream3_irq_handler;
-        case (uintptr_t)DMA2_Stream4:
-            return (uint32_t)&dma2_stream4_irq_handler;
-        default:
-            assert(0);
-    }
-}
-
-static int
-stm32f4_resolve_dma_handle_idx(DMA_HandleTypeDef *hdma)
-{
-    uintptr_t stream_addr = (uintptr_t)hdma->Instance;
-    return ((stream_addr & 0xFF) - ((uintptr_t)DMA2_Stream0_BASE & 0xFF))/0x18;
-}
-
-void
-HAL_ADC_ErrorCallback(ADC_HandleTypeDef *hadc)
-{
-    ++stm32f4_adc_stats.adc_error;
-
-    if (hadc->ErrorCode & HAL_ADC_ERROR_DMA) {
-        /* DMA transfer error */
-        ++stm32f4_adc_stats.adc_dma_xfer_failed;
-    } else if (hadc->ErrorCode & HAL_ADC_ERROR_OVR) {
-        /* DMA transfer overrun */
-        ++stm32f4_adc_stats.adc_dma_overrun;
-    } else if (hadc->ErrorCode & HAL_ADC_ERROR_INTERNAL) {
-       /* ADC IP Internal Error */
-        ++stm32f4_adc_stats.adc_internal_error;
-    }
-}
-
-/**
- * Callback that gets called by the HAL when ADC conversion is complete and
- * the DMA buffer is full. If a secondary buffer exists it will the buffers.
- *
- * @param ADC Handle
- */
-void
-HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef *hadc)
-{
-    int rc;
-    struct adc_dev *adc;
-    DMA_HandleTypeDef *hdma;
-    struct stm32f4_adc_dev_cfg *cfg;
-    void *buf;
-
-    assert(hadc);
-    hdma = hadc->DMA_Handle;
-
-    ++stm32f4_adc_stats.adc_dma_xfer_complete;
-
-    adc = adc_dma[stm32f4_resolve_dma_handle_idx(hdma)];
-    cfg  = (struct stm32f4_adc_dev_cfg *)adc->ad_dev.od_init_arg;
-
-    buf = cfg->primarybuf;
-    /**
-     * If primary buffer gets full and secondary buffer exists, swap the
-     * buffers and start ADC conversion with DMA with the now primary
-     * buffer(former secondary buffer)
-     * If the secondary buffer(former primary buffer) doesn't get processed
-     * by the application in sampling period required for the primary/secondary buffer
-     * i,e; (sample itvl * ADC_NUMBER_SAMPLES), the buffers would get swapped resulting
-     * in new sample data.
-     */
-    if (cfg->secondarybuf) {
-        cfg->primarybuf = cfg->secondarybuf;
-        cfg->secondarybuf = buf;
-
-        if (HAL_ADC_Start_DMA(hadc, cfg->primarybuf, cfg->buflen) != HAL_OK) {
-            ++stm32f4_adc_stats.adc_dma_start_error;
-        }
-    }
-
-    rc = adc->ad_event_handler_func(adc, NULL, ADC_EVENT_RESULT, buf,
-                                    cfg->buflen);
-
-    if (rc) {
-        ++stm32f4_adc_stats.adc_error;
-    }
-}
-
-static void
-stm32f4_adc_dma_init(ADC_HandleTypeDef* hadc)
-{
-
-    DMA_HandleTypeDef *hdma;
-
-    assert(hadc);
-    hdma = hadc->DMA_Handle;
-
-    stm32f4_adc_clk_enable(hadc);
-    __HAL_RCC_DMA2_CLK_ENABLE();
-
-    HAL_DMA_Init(hdma);
-    dma_handle[stm32f4_resolve_dma_handle_idx(hdma)] = hdma;
-
-    NVIC_SetPriority(stm32f4_resolve_adc_dma_irq(hdma),
-                     NVIC_EncodePriority(NVIC_GetPriorityGrouping(), 0, 0));
-    NVIC_SetVector(stm32f4_resolve_adc_dma_irq(hdma),
-                   stm32f4_resolve_adc_dma_irq_handler(hdma));
-    NVIC_EnableIRQ(stm32f4_resolve_adc_dma_irq(hdma));
-
-}
-
-static void
-stm32f4_adc_init(struct adc_dev *dev)
-{
-    struct stm32f4_adc_dev_cfg *adc_config;
-    ADC_HandleTypeDef *hadc;
-
-    assert(dev);
-
-    adc_config = (struct stm32f4_adc_dev_cfg *)dev->ad_dev.od_init_arg;
-    hadc = adc_config->sac_adc_handle;
-
-    stm32f4_adc_dma_init(hadc);
-
-    if (HAL_ADC_Init(hadc) != HAL_OK) {
-        assert(0);
-    }
-}
-
-static void
-stm32f4_adc_uninit(struct adc_dev *dev)
-{
-    GPIO_InitTypeDef gpio_td;
-    DMA_HandleTypeDef *hdma;
-    ADC_HandleTypeDef *hadc;
-    struct stm32f4_adc_dev_cfg *cfg;
-    uint8_t cnum;
-
-    assert(dev);
-    cfg  = (struct stm32f4_adc_dev_cfg *)dev->ad_dev.od_init_arg;
-    hadc = cfg->sac_adc_handle;
-    hdma = hadc->DMA_Handle;
-    cnum = dev->ad_chans->c_cnum;
-
-    __HAL_RCC_DMA2_CLK_DISABLE();
-    if (HAL_DMA_DeInit(hdma) != HAL_OK) {
-        assert(0);
-    }
-    stm32f4_adc_clk_disable(hadc);
-
-    NVIC_DisableIRQ(stm32f4_resolve_adc_dma_irq(hdma));
-
-    if (stm32f4_resolve_adc_gpio(hadc, cnum, &gpio_td)) {
-        goto err;
-    }
-
-    if(hal_gpio_deinit_stm(gpio_td.Pin, &gpio_td)) {
-        goto err;
-    }
-
-err:
-    return;
-}
-
-/**
- * Open the STM32F4 ADC device
- *
- * This function locks the device for access from other tasks.
- *
- * @param odev The OS device to open
- * @param wait The time in MS to wait.  If 0 specified, returns immediately
- *             if resource unavailable.  If OS_WAIT_FOREVER specified, blocks
- *             until resource is available.
- * @param arg  Argument provided by higher layer to open.
- *
- * @return 0 on success, non-zero on failure.
- */
-static int
-stm32f4_adc_open(struct os_dev *odev, uint32_t wait, void *arg)
-{
-    DMA_HandleTypeDef *hdma;
-    ADC_HandleTypeDef *hadc;
-    struct stm32f4_adc_dev_cfg *cfg;
-    struct adc_dev *dev;
-    int rc;
-
-    assert(odev);
-    rc = OS_OK;
-    dev = (struct adc_dev *) odev;
-
-    if (os_started()) {
-        rc = os_mutex_pend(&dev->ad_lock, wait);
-        if (rc != OS_OK) {
-            goto err;
-        }
-    }
-
-    if (odev->od_flags & OS_DEV_F_STATUS_OPEN) {
-        os_mutex_release(&dev->ad_lock);
-        rc = OS_EBUSY;
-        goto err;
-    }
-
-    stm32f4_adc_init(dev);
-
-    cfg  = (struct stm32f4_adc_dev_cfg *)dev->ad_dev.od_init_arg;
-    hadc = cfg->sac_adc_handle;
-    hdma = hadc->DMA_Handle;
-
-    adc_dma[stm32f4_resolve_dma_handle_idx(hdma)] = dev;
-
-    return (OS_OK);
-err:
-    return (rc);
-}
-
-
-/**
- * Close the STM32F4 ADC device.
- *
- * This function unlocks the device.
- *
- * @param odev The device to close.
- */
-static int
-stm32f4_adc_close(struct os_dev *odev)
-{
-    struct adc_dev *dev;
-
-    dev = (struct adc_dev *) odev;
-
-    stm32f4_adc_uninit(dev);
-
-    if (os_started()) {
-        os_mutex_release(&dev->ad_lock);
-    }
-
-    return (OS_OK);
-}
-
-/**
- * Configure an ADC channel on the STM32F4 ADC.
- *
- * @param dev The ADC device to configure
- * @param cnum The channel on the ADC device to configure
- * @param cfgdata An opaque pointer to channel config, expected to be
- *                a ADC_ChannelConfTypeDef
- *
- * @return 0 on success, non-zero on failure.
- */
-static int
-stm32f4_adc_configure_channel(struct adc_dev *dev, uint8_t cnum,
-        void *cfgdata)
-{
-    int rc;
-    ADC_HandleTypeDef *hadc;
-    struct stm32f4_adc_dev_cfg *cfg;
-    struct adc_chan_config *chan_cfg;
-    GPIO_InitTypeDef gpio_td;
-
-    rc = OS_EINVAL;
-
-    if (dev == NULL && !IS_ADC_CHANNEL(cnum)) {
-        goto err;
-    }
-
-    cfg  = (struct stm32f4_adc_dev_cfg *)dev->ad_dev.od_init_arg;
-    hadc = cfg->sac_adc_handle;
-    chan_cfg = &((struct adc_chan_config *)cfg->sac_chans)[cnum];
-
-    cfgdata = (ADC_ChannelConfTypeDef *)cfgdata;
-
-    if ((HAL_ADC_ConfigChannel(hadc, cfgdata)) != HAL_OK) {
-        goto err;
-    }
-
-    dev->ad_chans[cnum].c_res = chan_cfg->c_res;
-    dev->ad_chans[cnum].c_refmv = chan_cfg->c_refmv;
-    dev->ad_chans[cnum].c_configured = 1;
-    dev->ad_chans[cnum].c_cnum = cnum;
-
-    if (stm32f4_resolve_adc_gpio(hadc, cnum, &gpio_td)) {
-        goto err;
-    }
-
-    hal_gpio_init_stm(gpio_td.Pin, &gpio_td);
-
-#if 0
-    if (HAL_ADC_Start_IT(hadc) != HAL_OK) {
-        goto err;
-    }
-#endif
-
-    return (OS_OK);
-err:
-    return (rc);
-}
-
-/**
- * Set buffer to read data into.  Implementation of setbuffer handler.
- * Sets both the primary and secondary buffers for DMA.
- *
- * For our current implementation we are using DMA in circular mode
- *
- */
-static int
-stm32f4_adc_set_buffer(struct adc_dev *dev, void *buf1, void *buf2,
-        int buflen)
-{
-    struct stm32f4_adc_dev_cfg *cfg;
-    int rc;
-
-
-    assert(dev != NULL && buf1 != NULL);
-    rc = OS_OK;
-    buflen /= sizeof(uint32_t);
-
-    cfg  = (struct stm32f4_adc_dev_cfg *)dev->ad_dev.od_init_arg;
-
-    cfg->primarybuf = buf1;
-    cfg->secondarybuf = buf2;
-    cfg->buflen = buflen;
-
-    return rc;
-}
-
-static int
-stm32f4_adc_release_buffer(struct adc_dev *dev, void *buf, int buf_len)
-{
-    ADC_HandleTypeDef *hadc;
-    struct stm32f4_adc_dev_cfg *cfg;
-
-    assert(dev);
-    cfg  = (struct stm32f4_adc_dev_cfg *)dev->ad_dev.od_init_arg;
-    hadc = cfg->sac_adc_handle;
-
-    HAL_ADC_Stop_DMA(hadc);
-
-    return (0);
-}
-
-/**
- * Trigger an ADC sample.
- *
- * @param ADC device structure
- * @return OS_OK on success, non OS_OK on failure
- */
-static int
-stm32f4_adc_sample(struct adc_dev *dev)
-{
-    int rc;
-    ADC_HandleTypeDef *hadc;
-    struct stm32f4_adc_dev_cfg *cfg;
-
-    assert(dev);
-    cfg  = (struct stm32f4_adc_dev_cfg *)dev->ad_dev.od_init_arg;
-    hadc = cfg->sac_adc_handle;
-
-    rc = OS_EINVAL;
-
-    if (HAL_ADC_Start_DMA(hadc, cfg->primarybuf, cfg->buflen) != HAL_OK) {
-        ++stm32f4_adc_stats.adc_dma_start_error;
-        goto err;
-    }
-
-    rc = OS_OK;
-
-err:
-    return rc;
-}
-
-/**
- * Blocking read of an ADC channel, returns result as an integer.
- *
- * @param1 ADC device structure
- * @param2 channel number
- * @param3 ADC result ptr
- */
-static int
-stm32f4_adc_read_channel(struct adc_dev *dev, uint8_t cnum, int *result)
-{
-    ADC_HandleTypeDef *hadc;
-    struct stm32f4_adc_dev_cfg *cfg;
-
-    assert(dev != NULL && result != NULL);
-    cfg  = (struct stm32f4_adc_dev_cfg *)dev->ad_dev.od_init_arg;
-    hadc = cfg->sac_adc_handle;
-
-    *result = HAL_ADC_GetValue(hadc);
-
-    return (OS_OK);
-}
-
-static int
-stm32f4_adc_read_buffer(struct adc_dev *dev, void *buf, int buf_len, int off,
-                        int *result)
-{
-
-    assert(off < buf_len);
-
-    /*
-     * If secondary buffer exists the primary buf is going to be cached
-     * in the secondary buffer if the primary buffer is full and we
-     * would be reading that instead since the buffer is specified by
-     * the application
-     */
-    *result = *((uint32_t *)buf + off);
-
-    return (OS_OK);
-}
-
-/**
- * Callback to return size of buffer
- *
- * @param1 ADC device ptr
- * @param2 Total number of channels
- * @param3 Total number of samples
- * @return Length of buffer in bytes
- */
-static int
-stm32f4_adc_size_buffer(struct adc_dev *dev, int chans, int samples)
-{
-    return (sizeof(uint32_t) * chans * samples);
-}
-
-#if 0
-void ADC_IRQHandler(void)
-{
-    HAL_ADC_IRQHandler(adc_handle);
-}
-#endif
-
-
-/**
- * Callback to initialize an adc_dev structure from the os device
- * initialization callback.  This sets up a stm32f4_adc_device(), so
- * that subsequent lookups to this device allow us to manipulate it.
- *
- * @param1 os device ptr
- * @param2 stm32f4 ADC device cfg ptr
- * @return OS_OK on success
- */
-int
-stm32f4_adc_dev_init(struct os_dev *odev, void *arg)
-{
-    struct stm32f4_adc_dev_cfg *sac;
-    struct adc_dev *dev;
-    struct adc_driver_funcs *af;
-
-    sac = (struct stm32f4_adc_dev_cfg *) arg;
-
-    assert(sac != NULL);
-
-    dev = (struct adc_dev *)odev;
-
-    os_mutex_init(&dev->ad_lock);
-
-    dev->ad_chans = (void *) sac->sac_chans;
-    dev->ad_chan_count = sac->sac_chan_count;
-
-    OS_DEV_SETHANDLERS(odev, stm32f4_adc_open, stm32f4_adc_close);
-
-    af = &dev->ad_funcs;
-
-    af->af_configure_channel = stm32f4_adc_configure_channel;
-    af->af_sample = stm32f4_adc_sample;
-    af->af_read_channel = stm32f4_adc_read_channel;
-    af->af_set_buffer = stm32f4_adc_set_buffer;
-    af->af_release_buffer = stm32f4_adc_release_buffer;
-    af->af_read_buffer = stm32f4_adc_read_buffer;
-    af->af_size_buffer = stm32f4_adc_size_buffer;
-
-    return (OS_OK);
-}
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/encoding/base64/include/base64/base64.h
----------------------------------------------------------------------
diff --git a/encoding/base64/include/base64/base64.h b/encoding/base64/include/base64/base64.h
new file mode 100644
index 0000000..8e0c045
--- /dev/null
+++ b/encoding/base64/include/base64/base64.h
@@ -0,0 +1,32 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 __UTIL_BASE64_H
+#define __UTIL_BASE64_H
+
+#include <stdint.h>
+#include <string.h>
+
+int base64_encode(const void *, int, char *, uint8_t);
+int base64_decode(const char *, void *buf);
+int base64_pad(char *, int);
+int base64_decode_len(const char *str);
+
+#define BASE64_ENCODE_SIZE(__size) ((((__size) * 4) / 3) + 4)
+
+#endif /* __UTIL_BASE64_H__ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/encoding/base64/include/base64/hex.h
----------------------------------------------------------------------
diff --git a/encoding/base64/include/base64/hex.h b/encoding/base64/include/base64/hex.h
new file mode 100644
index 0000000..1e9d8c8
--- /dev/null
+++ b/encoding/base64/include/base64/hex.h
@@ -0,0 +1,25 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 _UTIL_HEX_H_
+#define _UTIL_HEX_H_
+
+char *hex_format(void *src_v, int src_len, char *dst, int dst_len);
+int hex_parse(char *src, int src_len, void *dst_v, int dst_len);
+
+#endif /* _UTIL_HEX_H_ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/encoding/base64/pkg.yml
----------------------------------------------------------------------
diff --git a/encoding/base64/pkg.yml b/encoding/base64/pkg.yml
new file mode 100644
index 0000000..7cbe47b
--- /dev/null
+++ b/encoding/base64/pkg.yml
@@ -0,0 +1,26 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+#
+
+pkg.name: encoding/base64
+pkg.description: Library containing encoding functions
+pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
+pkg.homepage: "http://mynewt.apache.org/"
+pkg.keywords:
+    - base64
+    - hex

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/encoding/base64/src/base64.c
----------------------------------------------------------------------
diff --git a/encoding/base64/src/base64.c b/encoding/base64/src/base64.c
new file mode 100644
index 0000000..0587835
--- /dev/null
+++ b/encoding/base64/src/base64.c
@@ -0,0 +1,181 @@
+/*
+ * This file is based on roken from the FreeBSD source.  It has been modified
+ * to not use malloc() and instead expect static buffers, and tabs have been
+ * replaced with spaces.  Also, instead of strlen() on the resulting string,
+ * pointer arithmitic is done, as p represents the end of the buffer.
+ */
+
+/*
+ * Copyright (c) 1995-2001 Kungliga Tekniska H�gskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * 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.
+ *
+ * 3. Neither the name of the Institute 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 INSTITUTE 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 INSTITUTE 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 <stdlib.h>
+#include <string.h>
+
+#include <stdio.h>
+
+#include <base64/base64.h>
+
+static const char base64_chars[] =
+    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+
+static int
+pos(char c)
+{
+    const char *p;
+    for (p = base64_chars; *p; p++)
+        if (*p == c)
+            return p - base64_chars;
+    return -1;
+}
+
+int
+base64_encode(const void *data, int size, char *s, uint8_t should_pad)
+{
+    char *p;
+    int i;
+    int c;
+    const unsigned char *q;
+    char *last;
+    int diff;
+
+    p = s;
+
+    q = (const unsigned char *) data;
+    last = NULL;
+    i = 0;
+    while (i < size) {
+        c = q[i++];
+        c *= 256;
+        if (i < size)
+            c += q[i];
+        i++;
+        c *= 256;
+        if (i < size)
+            c += q[i];
+        i++;
+        p[0] = base64_chars[(c & 0x00fc0000) >> 18];
+        p[1] = base64_chars[(c & 0x0003f000) >> 12];
+        p[2] = base64_chars[(c & 0x00000fc0) >> 6];
+        p[3] = base64_chars[(c & 0x0000003f) >> 0];
+        last = p;
+        p += 4;
+    }
+
+    if (last) {
+        diff = i - size;
+        if (diff > 0) {
+            if (should_pad) {
+                memset(last + (4 - diff), '=', diff);
+            } else {
+                p = last + (4 - diff);
+            }
+        }
+    }
+
+    *p = 0;
+
+    return (p - s);
+}
+
+int
+base64_pad(char *buf, int len)
+{
+    int remainder;
+
+    remainder = len % 4;
+    if (remainder == 0) {
+        return (0);
+    }
+
+    memset(buf, '=', 4 - remainder);
+
+    return (4 - remainder);
+}
+
+#define DECODE_ERROR -1
+
+static unsigned int
+token_decode(const char *token)
+{
+    int i;
+    unsigned int val = 0;
+    int marker = 0;
+    if (strlen(token) < 4)
+        return DECODE_ERROR;
+    for (i = 0; i < 4; i++) {
+        val *= 64;
+        if (token[i] == '=')
+            marker++;
+        else if (marker > 0)
+            return DECODE_ERROR;
+        else
+            val += pos(token[i]);
+    }
+    if (marker > 2)
+        return DECODE_ERROR;
+    return (marker << 24) | val;
+}
+
+int
+base64_decode(const char *str, void *data)
+{
+    const char *p;
+    unsigned char *q;
+
+    q = data;
+    for (p = str; *p && (*p == '=' || strchr(base64_chars, *p)); p += 4) {
+        unsigned int val = token_decode(p);
+        unsigned int marker = (val >> 24) & 0xff;
+        if (val == DECODE_ERROR)
+            return -1;
+        *q++ = (val >> 16) & 0xff;
+        if (marker < 2)
+            *q++ = (val >> 8) & 0xff;
+        if (marker < 1)
+            *q++ = val & 0xff;
+    }
+    return q - (unsigned char *) data;
+}
+
+
+int
+base64_decode_len(const char *str)
+{
+    int len;
+
+    len = strlen(str);
+    while (len && str[len - 1] == '=') {
+        len--;
+    }
+    return len * 3 / 4;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/encoding/base64/src/hex.c
----------------------------------------------------------------------
diff --git a/encoding/base64/src/hex.c b/encoding/base64/src/hex.c
new file mode 100644
index 0000000..44162c2
--- /dev/null
+++ b/encoding/base64/src/hex.c
@@ -0,0 +1,101 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include <inttypes.h>
+#include <ctype.h>
+#include <stddef.h>
+
+#include "base64/hex.h"
+
+static const char hex_bytes[] = "0123456789abcdef";
+
+/*
+ * Turn byte array into a printable array. I.e. "\x01" -> "01"
+ *
+ * @param src_v		Data to convert
+ * @param src_len	Number of bytes of input
+ * @param dst		String where to place the results
+ * @param dst_len	Size of the target string
+ *
+ * @return		Pointer to 'dst' if successful; NULL on failure
+ */
+char *
+hex_format(void *src_v, int src_len, char *dst, int dst_len)
+{
+    int i;
+    uint8_t *src = (uint8_t *)src_v;
+    char *tgt = dst;
+
+    if (dst_len <= src_len * 2) {
+        return NULL;
+    }
+    for (i = 0; i < src_len; i++) {
+        tgt[0] = hex_bytes[(src[i] >> 4) & 0xf];
+        tgt[1] = hex_bytes[src[i] & 0xf];
+        tgt += 2;
+        dst_len -= 2;
+    }
+    *tgt = '\0';
+    return dst;
+}
+
+/*
+ * Turn string of hex decimals into a byte array. I.e. "01" -> "\x01
+ *
+ * @param src		String to convert
+ * @param src_len	Number of bytes in input string
+ * @param dst_v		Memory location to place the result
+ * @param dst_len	Amount of space for the result
+ *
+ * @return		-1 on failure; number of bytes of input
+ */
+int
+hex_parse(char *src, int src_len, void *dst_v, int dst_len)
+{
+    int i;
+    uint8_t *dst = (uint8_t *)dst_v;
+    char c;
+
+    if (src_len & 0x1) {
+        return -1;
+    }
+    if (dst_len * 2 < src_len) {
+        return -1;
+    }
+    for (i = 0; i < src_len; i++, src++) {
+        c = *src;
+        if (isdigit(c)) {
+            c -= '0';
+        } else if (c >= 'a' && c <= 'f') {
+            c -= ('a' - 10);
+        } else if (c >= 'A' && c <= 'F') {
+            c -= ('A' - 10);
+        } else {
+            return -1;
+        }
+        if (i & 1) {
+            *dst |= c;
+            dst++;
+            dst_len--;
+        } else {
+            *dst = c << 4;
+        }
+    }
+    return src_len >> 1;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/encoding/base64/test/pkg.yml
----------------------------------------------------------------------
diff --git a/encoding/base64/test/pkg.yml b/encoding/base64/test/pkg.yml
new file mode 100644
index 0000000..9ecd063
--- /dev/null
+++ b/encoding/base64/test/pkg.yml
@@ -0,0 +1,30 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+#
+pkg.name: encoding/base64/test
+pkg.type: unittest
+pkg.description: "Crypto encoding unit tests."
+pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
+pkg.homepage: "http://mynewt.apache.org/"
+pkg.keywords:
+
+pkg.deps: 
+    - libs/testutil
+    - libs/util
+
+pkg.deps.SELFTEST:
+    - libs/console/stub

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/encoding/base64/test/src/encoding_test.c
----------------------------------------------------------------------
diff --git a/encoding/base64/test/src/encoding_test.c b/encoding/base64/test/src/encoding_test.c
new file mode 100644
index 0000000..b21fee8
--- /dev/null
+++ b/encoding/base64/test/src/encoding_test.c
@@ -0,0 +1,46 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include <assert.h>
+#include <stddef.h>
+#include "syscfg/syscfg.h"
+#include "testutil/testutil.h"
+#include "encoding_test_priv.h"
+
+
+int
+hex_fmt_test_all(void)
+{
+    hex_fmt_test_suite();
+    return tu_case_failed;
+}
+
+#if MYNEWT_VAL(SELFTEST)
+
+int
+main(int argc, char **argv)
+{
+    tu_config.tc_print_results = 1;
+    tu_init();
+
+    hex_fmt_test_all();
+    return tu_any_failed;
+}
+
+#endif



[21/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/ldo.c
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/ldo.c b/libs/elua/elua_base/src/ldo.c
deleted file mode 100644
index 6fcda02..0000000
--- a/libs/elua/elua_base/src/ldo.c
+++ /dev/null
@@ -1,537 +0,0 @@
-/*
-** $Id: ldo.c,v 2.38.1.3 2008/01/18 22:31:22 roberto Exp $
-** Stack and Call structure of Lua
-** See Copyright Notice in lua.h
-*/
-
-
-#include <setjmp.h>
-#include <stdlib.h>
-#include <string.h>
-
-#define ldo_c
-#define LUA_CORE
-
-#include "lua.h"
-
-#include "ldebug.h"
-#include "ldo.h"
-#include "lfunc.h"
-#include "lgc.h"
-#include "lmem.h"
-#include "lobject.h"
-#include "lopcodes.h"
-#include "lparser.h"
-#include "lstate.h"
-#include "lstring.h"
-#include "ltable.h"
-#include "ltm.h"
-#include "lundump.h"
-#include "lvm.h"
-#include "lzio.h"
-
-
-
-
-/*
-** {======================================================
-** Error-recovery functions
-** =======================================================
-*/
-
-
-/* chain list of long jump buffers */
-struct lua_longjmp {
-  struct lua_longjmp *previous;
-  luai_jmpbuf b;
-  volatile int status;  /* error code */
-};
-
-
-void luaD_seterrorobj (lua_State *L, int errcode, StkId oldtop) {
-  switch (errcode) {
-    case LUA_ERRMEM: {
-      ptrdiff_t oldtopr = savestack(L, oldtop);
-      setsvalue2s(L, restorestack(L, oldtopr), luaS_newliteral(L, MEMERRMSG));
-      break;
-    }
-    case LUA_ERRERR: {
-      ptrdiff_t oldtopr = savestack(L, oldtop);
-      setsvalue2s(L, restorestack(L, oldtopr), luaS_newliteral(L, "error in error handling"));
-      break;
-    }
-    case LUA_ERRSYNTAX:
-    case LUA_ERRRUN: {
-      setobjs2s(L, oldtop, L->top - 1);  /* error message on current top */
-      break;
-    }
-  }
-  L->top = oldtop + 1;
-}
-
-
-static void restore_stack_limit (lua_State *L) {
-  lua_assert(L->stack_last - L->stack == L->stacksize - EXTRA_STACK - 1);
-  if (L->size_ci > LUAI_MAXCALLS) {  /* there was an overflow? */
-    int inuse = cast_int(L->ci - L->base_ci);
-    if (inuse + 1 < LUAI_MAXCALLS)  /* can `undo' overflow? */
-      luaD_reallocCI(L, LUAI_MAXCALLS);
-  }
-}
-
-
-static void resetstack (lua_State *L, int status) {
-  L->ci = L->base_ci;
-  L->base = L->ci->base;
-  luaF_close(L, L->base);  /* close eventual pending closures */
-  luaD_seterrorobj(L, status, L->base);
-  L->nCcalls = L->baseCcalls;
-  L->allowhook = 1;
-  restore_stack_limit(L);
-  L->errfunc = 0;
-  L->errorJmp = NULL;
-}
-
-
-void luaD_throw (lua_State *L, int errcode) {
-  unfixedstack(L); /* make sure the fixedstack & block_gc flags get reset. */
-  unset_block_gc(L);
-  if (L->errorJmp) {
-    L->errorJmp->status = errcode;
-    LUAI_THROW(L, L->errorJmp);
-  }
-  else {
-    L->status = cast_byte(errcode);
-    if (G(L)->panic) {
-      resetstack(L, errcode);
-      lua_unlock(L);
-      G(L)->panic(L);
-    }
-    exit(EXIT_FAILURE);
-  }
-}
-
-
-int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud) {
-  struct lua_longjmp lj;
-  lj.status = 0;
-  lj.previous = L->errorJmp;  /* chain new error handler */
-  L->errorJmp = &lj;
-  LUAI_TRY(L, &lj,
-    (*f)(L, ud);
-  );
-  L->errorJmp = lj.previous;  /* restore old error handler */
-  return lj.status;
-}
-
-/* }====================================================== */
-
-
-static void correctstack (lua_State *L, TValue *oldstack) {
-  CallInfo *ci;
-  GCObject *up;
-  L->top = (L->top - oldstack) + L->stack;
-  for (up = L->openupval; up != NULL; up = up->gch.next)
-    gco2uv(up)->v = (gco2uv(up)->v - oldstack) + L->stack;
-  for (ci = L->base_ci; ci <= L->ci; ci++) {
-    ci->top = (ci->top - oldstack) + L->stack;
-    ci->base = (ci->base - oldstack) + L->stack;
-    ci->func = (ci->func - oldstack) + L->stack;
-  }
-  L->base = (L->base - oldstack) + L->stack;
-}
-
-
-void luaD_reallocstack (lua_State *L, int newsize) {
-  TValue *oldstack = L->stack;
-  int realsize = newsize + 1 + EXTRA_STACK;
-  lua_assert(L->stack_last - L->stack == L->stacksize - EXTRA_STACK - 1);
-  luaM_reallocvector(L, L->stack, L->stacksize, realsize, TValue);
-  L->stacksize = realsize;
-  L->stack_last = L->stack+newsize;
-  correctstack(L, oldstack);
-}
-
-
-void luaD_reallocCI (lua_State *L, int newsize) {
-  CallInfo *oldci = L->base_ci;
-  luaM_reallocvector(L, L->base_ci, L->size_ci, newsize, CallInfo);
-  L->size_ci = newsize;
-  L->ci = (L->ci - oldci) + L->base_ci;
-  L->end_ci = L->base_ci + L->size_ci - 1;
-}
-
-
-void luaD_growstack (lua_State *L, int n) {
-  if (n <= L->stacksize)  /* double size is enough? */
-    luaD_reallocstack(L, 2*L->stacksize);
-  else
-    luaD_reallocstack(L, L->stacksize + n);
-}
-
-
-static CallInfo *growCI (lua_State *L) {
-  if (L->size_ci > LUAI_MAXCALLS)  /* overflow while handling overflow? */
-    luaD_throw(L, LUA_ERRERR);
-  else {
-    luaD_reallocCI(L, 2*L->size_ci);
-    if (L->size_ci > LUAI_MAXCALLS)
-      luaG_runerror(L, "stack overflow");
-  }
-  return ++L->ci;
-}
-
-
-void luaD_callhook (lua_State *L, int event, int line) {
-  lua_Hook hook = L->hook;
-  if (hook && L->allowhook) {
-    ptrdiff_t top = savestack(L, L->top);
-    ptrdiff_t ci_top = savestack(L, L->ci->top);
-    lua_Debug ar;
-    ar.event = event;
-    ar.currentline = line;
-    if (event == LUA_HOOKTAILRET)
-      ar.i_ci = 0;  /* tail call; no debug information about it */
-    else
-      ar.i_ci = cast_int(L->ci - L->base_ci);
-    luaD_checkstack(L, LUA_MINSTACK);  /* ensure minimum stack size */
-    L->ci->top = L->top + LUA_MINSTACK;
-    lua_assert(L->ci->top <= L->stack_last);
-    L->allowhook = 0;  /* cannot call hooks inside a hook */
-    lua_unlock(L);
-    (*hook)(L, &ar);
-    lua_lock(L);
-    lua_assert(!L->allowhook);
-    L->allowhook = 1;
-    L->ci->top = restorestack(L, ci_top);
-    L->top = restorestack(L, top);
-  }
-}
-
-
-static StkId adjust_varargs (lua_State *L, Proto *p, int actual) {
-  int i;
-  int nfixargs = p->numparams;
-#if defined(LUA_COMPAT_VARARG)
-  Table *htab = NULL;
-#endif
-  StkId base, fixed;
-  for (; actual < nfixargs; ++actual)
-    setnilvalue(L->top++);
-#if defined(LUA_COMPAT_VARARG)
-  if (p->is_vararg & VARARG_NEEDSARG) { /* compat. with old-style vararg? */
-    int nvar = actual - nfixargs;  /* number of extra arguments */
-    lua_assert(p->is_vararg & VARARG_HASARG);
-    luaC_checkGC(L);
-    htab = luaH_new(L, nvar, 1);  /* create `arg' table */
-    sethvalue2s(L, L->top, htab); /* put table on stack */
-    incr_top(L);
-    fixedstack(L);
-    for (i=0; i<nvar; i++)  /* put extra arguments into `arg' table */
-      setobj2n(L, luaH_setnum(L, htab, i+1), L->top - 1 - nvar + i);
-    unfixedstack(L);
-    /* store counter in field `n' */
-    setnvalue(luaH_setstr(L, htab, luaS_newliteral(L, "n")), cast_num(nvar));
-    L->top--; /* remove table from stack */
-  }
-#endif
-  /* move fixed parameters to final position */
-  fixed = L->top - actual;  /* first fixed argument */
-  base = L->top;  /* final position of first argument */
-  for (i=0; i<nfixargs; i++) {
-    setobjs2s(L, L->top++, fixed+i);
-    setnilvalue(fixed+i);
-  }
-#if defined(LUA_COMPAT_VARARG)
-  /* add `arg' parameter */
-  if (htab) {
-    sethvalue(L, L->top++, htab);
-    lua_assert(iswhite(obj2gco(htab)));
-  }
-#endif
-  return base;
-}
-
-
-static StkId tryfuncTM (lua_State *L, StkId func) {
-  const TValue *tm = luaT_gettmbyobj(L, func, TM_CALL);
-  StkId p;
-  ptrdiff_t funcr = savestack(L, func);
-  if (!ttisfunction(tm))
-    luaG_typeerror(L, func, "call");
-  /* Open a hole inside the stack at `func' */
-  for (p = L->top; p > func; p--) setobjs2s(L, p, p-1);
-  incr_top(L);
-  func = restorestack(L, funcr);  /* previous call may change stack */
-  setobj2s(L, func, tm);  /* tag method is the new function to be called */
-  return func;
-}
-
-
-
-#define inc_ci(L) \
-  ((L->ci == L->end_ci) ? growCI(L) : \
-   (condhardstacktests(luaD_reallocCI(L, L->size_ci)), ++L->ci))
-
-
-int luaD_precall (lua_State *L, StkId func, int nresults) {
-  ptrdiff_t funcr;
-  LClosure *cl = NULL;
-  if (!ttisfunction(func) && !ttislightfunction(func)) /* `func' is not a function? */
-    func = tryfuncTM(L, func);  /* check the `function' tag method */
-  funcr = savestack(L, func);
-  if (ttisfunction(func))
-    cl = &clvalue(func)->l;
-  L->ci->savedpc = L->savedpc;
-  if (cl && !cl->isC) {  /* Lua function? prepare its call */
-    CallInfo *ci;
-    StkId st, base;
-    Proto *p = cl->p;
-    luaD_checkstack(L, p->maxstacksize);
-    func = restorestack(L, funcr);
-    if (!p->is_vararg) {  /* no varargs? */
-      base = func + 1;
-      if (L->top > base + p->numparams)
-        L->top = base + p->numparams;
-    }
-    else {  /* vararg function */
-      int nargs = cast_int(L->top - func) - 1;
-      base = adjust_varargs(L, p, nargs);
-      func = restorestack(L, funcr);  /* previous call may change the stack */
-    }
-    ci = inc_ci(L);  /* now `enter' new function */
-    ci->func = func;
-    L->base = ci->base = base;
-    ci->top = L->base + p->maxstacksize;
-    lua_assert(ci->top <= L->stack_last);
-    L->savedpc = p->code;  /* starting point */
-    ci->tailcalls = 0;
-    ci->nresults = nresults;
-    for (st = L->top; st < ci->top; st++)
-      setnilvalue(st);
-    L->top = ci->top;
-    if (L->hookmask & LUA_MASKCALL) {
-      L->savedpc++;  /* hooks assume 'pc' is already incremented */
-      luaD_callhook(L, LUA_HOOKCALL, -1);
-      L->savedpc--;  /* correct 'pc' */
-    }
-    return PCRLUA;
-  }
-  else {  /* if is a C function, call it */
-    CallInfo *ci;
-    int n;
-    luaD_checkstack(L, LUA_MINSTACK);  /* ensure minimum stack size */
-    ci = inc_ci(L);  /* now `enter' new function */
-    ci->func = restorestack(L, funcr);
-    L->base = ci->base = ci->func + 1;
-    ci->top = L->top + LUA_MINSTACK;
-    lua_assert(ci->top <= L->stack_last);
-    ci->nresults = nresults;
-    if (L->hookmask & LUA_MASKCALL)
-      luaD_callhook(L, LUA_HOOKCALL, -1);
-    lua_unlock(L);
-    if (ttisfunction(ci->func))
-      n = (*curr_func(L)->c.f)(L);  /* do the actual call */
-    else
-      n = ((lua_CFunction)fvalue(ci->func))(L);  /* do the actual call */
-    lua_lock(L);
-    if (n < 0)  /* yielding? */
-      return PCRYIELD;
-    else {
-      luaD_poscall(L, L->top - n);
-      return PCRC;
-    }
-  }
-}
-
-
-static StkId callrethooks (lua_State *L, StkId firstResult) {
-  ptrdiff_t fr = savestack(L, firstResult);  /* next call may change stack */
-  luaD_callhook(L, LUA_HOOKRET, -1);
-  if (f_isLua(L->ci)) {  /* Lua function? */
-    while ((L->hookmask & LUA_MASKRET) && L->ci->tailcalls--) /* tail calls */
-      luaD_callhook(L, LUA_HOOKTAILRET, -1);
-  }
-  return restorestack(L, fr);
-}
-
-
-int luaD_poscall (lua_State *L, StkId firstResult) {
-  StkId res;
-  int wanted, i;
-  CallInfo *ci;
-  if (L->hookmask & LUA_MASKRET)
-    firstResult = callrethooks(L, firstResult);
-  ci = L->ci--;
-  res = ci->func;  /* res == final position of 1st result */
-  wanted = ci->nresults;
-  L->base = (ci - 1)->base;  /* restore base */
-  L->savedpc = (ci - 1)->savedpc;  /* restore savedpc */
-  /* move results to correct place */
-  for (i = wanted; i != 0 && firstResult < L->top; i--)
-    setobjs2s(L, res++, firstResult++);
-  while (i-- > 0)
-    setnilvalue(res++);
-  L->top = res;
-  return (wanted - LUA_MULTRET);  /* 0 iff wanted == LUA_MULTRET */
-}
-
-
-/*
-** Call a function (C or Lua). The function to be called is at *func.
-** The arguments are on the stack, right after the function.
-** When returns, all the results are on the stack, starting at the original
-** function position.
-*/ 
-void luaD_call (lua_State *L, StkId func, int nResults) {
-  if (++L->nCcalls >= LUAI_MAXCCALLS) {
-    if (L->nCcalls == LUAI_MAXCCALLS)
-      luaG_runerror(L, "C stack overflow");
-    else if (L->nCcalls >= (LUAI_MAXCCALLS + (LUAI_MAXCCALLS>>3)))
-      luaD_throw(L, LUA_ERRERR);  /* error while handing stack error */
-  }
-  if (luaD_precall(L, func, nResults) == PCRLUA)  /* is a Lua function? */
-    luaV_execute(L, 1);  /* call it */
-  L->nCcalls--;
-  luaC_checkGC(L);
-}
-
-
-static void resume (lua_State *L, void *ud) {
-  StkId firstArg = cast(StkId, ud);
-  CallInfo *ci = L->ci;
-  if (L->status == 0) {  /* start coroutine? */
-    lua_assert(ci == L->base_ci && firstArg > L->base);
-    if (luaD_precall(L, firstArg - 1, LUA_MULTRET) != PCRLUA)
-      return;
-  }
-  else {  /* resuming from previous yield */
-    lua_assert(L->status == LUA_YIELD);
-    L->status = 0;
-    if (!f_isLua(ci)) {  /* `common' yield? */
-      /* finish interrupted execution of `OP_CALL' */
-      lua_assert(GET_OPCODE(*((ci-1)->savedpc - 1)) == OP_CALL ||
-                 GET_OPCODE(*((ci-1)->savedpc - 1)) == OP_TAILCALL);
-      if (luaD_poscall(L, firstArg))  /* complete it... */
-        L->top = L->ci->top;  /* and correct top if not multiple results */
-    }
-    else  /* yielded inside a hook: just continue its execution */
-      L->base = L->ci->base;
-  }
-  luaV_execute(L, cast_int(L->ci - L->base_ci));
-}
-
-
-static int resume_error (lua_State *L, const char *msg) {
-  L->top = L->ci->base;
-  setsvalue2s(L, L->top, luaS_new(L, msg));
-  incr_top(L);
-  lua_unlock(L);
-  return LUA_ERRRUN;
-}
-
-
-LUA_API int lua_resume (lua_State *L, int nargs) {
-  int status;
-  lua_lock(L);
-  if (L->status != LUA_YIELD && (L->status != 0 || L->ci != L->base_ci))
-      return resume_error(L, "cannot resume non-suspended coroutine");
-  if (L->nCcalls >= LUAI_MAXCCALLS)
-    return resume_error(L, "C stack overflow");
-  luai_userstateresume(L, nargs);
-  lua_assert(L->errfunc == 0);
-  L->baseCcalls = ++L->nCcalls;
-  status = luaD_rawrunprotected(L, resume, L->top - nargs);
-  if (status != 0) {  /* error? */
-    L->status = cast_byte(status);  /* mark thread as `dead' */
-    luaD_seterrorobj(L, status, L->top);
-    L->ci->top = L->top;
-  }
-  else {
-    lua_assert(L->nCcalls == L->baseCcalls);
-    status = L->status;
-  }
-  --L->nCcalls;
-  lua_unlock(L);
-  return status;
-}
-
-
-LUA_API int lua_yield (lua_State *L, int nresults) {
-  luai_userstateyield(L, nresults);
-  lua_lock(L);
-  if (L->nCcalls > L->baseCcalls)
-    luaG_runerror(L, "attempt to yield across metamethod/C-call boundary");
-  L->base = L->top - nresults;  /* protect stack slots below */
-  L->status = LUA_YIELD;
-  lua_unlock(L);
-  return -1;
-}
-
-
-int luaD_pcall (lua_State *L, Pfunc func, void *u,
-                ptrdiff_t old_top, ptrdiff_t ef) {
-  int status;
-  unsigned short oldnCcalls = L->nCcalls;
-  ptrdiff_t old_ci = saveci(L, L->ci);
-  lu_byte old_allowhooks = L->allowhook;
-  ptrdiff_t old_errfunc = L->errfunc;
-  L->errfunc = ef;
-  status = luaD_rawrunprotected(L, func, u);
-  if (status != 0) {  /* an error occurred? */
-    StkId oldtop = restorestack(L, old_top);
-    luaF_close(L, oldtop);  /* close eventual pending closures */
-    luaD_seterrorobj(L, status, oldtop);
-    L->nCcalls = oldnCcalls;
-    L->ci = restoreci(L, old_ci);
-    L->base = L->ci->base;
-    L->savedpc = L->ci->savedpc;
-    L->allowhook = old_allowhooks;
-    restore_stack_limit(L);
-  }
-  L->errfunc = old_errfunc;
-  return status;
-}
-
-
-
-/*
-** Execute a protected parser.
-*/
-struct SParser {  /* data to `f_parser' */
-  ZIO *z;
-  Mbuffer buff;  /* buffer to be used by the scanner */
-  const char *name;
-};
-
-static void f_parser (lua_State *L, void *ud) {
-  int i;
-  Proto *tf;
-  Closure *cl;
-  struct SParser *p = cast(struct SParser *, ud);
-  int c = luaZ_lookahead(p->z);
-  luaC_checkGC(L);
-  set_block_gc(L);  /* stop collector during parsing */
-  tf = ((c == LUA_SIGNATURE[0]) ? luaU_undump : luaY_parser)(L, p->z,
-                                                             &p->buff, p->name);
-  cl = luaF_newLclosure(L, tf->nups, hvalue(gt(L)));
-  cl->l.p = tf;
-  for (i = 0; i < tf->nups; i++)  /* initialize eventual upvalues */
-    cl->l.upvals[i] = luaF_newupval(L);
-  setclvalue(L, L->top, cl);
-  incr_top(L);
-  unset_block_gc(L);
-}
-
-
-int luaD_protectedparser (lua_State *L, ZIO *z, const char *name) {
-  struct SParser p;
-  int status;
-  p.z = z; p.name = name;
-  luaZ_initbuffer(L, &p.buff);
-  status = luaD_pcall(L, f_parser, &p, savestack(L, L->top), L->errfunc);
-  luaZ_freebuffer(L, &p.buff);
-  return status;
-}
-
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/ldo.h
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/ldo.h b/libs/elua/elua_base/src/ldo.h
deleted file mode 100644
index 98fddac..0000000
--- a/libs/elua/elua_base/src/ldo.h
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
-** $Id: ldo.h,v 2.7.1.1 2007/12/27 13:02:25 roberto Exp $
-** Stack and Call structure of Lua
-** See Copyright Notice in lua.h
-*/
-
-#ifndef ldo_h
-#define ldo_h
-
-
-#include "lobject.h"
-#include "lstate.h"
-#include "lzio.h"
-
-
-#define luaD_checkstack(L,n)	\
-  if ((char *)L->stack_last - (char *)L->top <= (n)*(int)sizeof(TValue)) \
-    luaD_growstack(L, n); \
-  else condhardstacktests(luaD_reallocstack(L, L->stacksize - EXTRA_STACK - 1));
-
-
-#define incr_top(L) {luaD_checkstack(L,1); L->top++;}
-
-#define savestack(L,p)		((char *)(p) - (char *)L->stack)
-#define restorestack(L,n)	((TValue *)((char *)L->stack + (n)))
-
-#define saveci(L,p)		((char *)(p) - (char *)L->base_ci)
-#define restoreci(L,n)		((CallInfo *)((char *)L->base_ci + (n)))
-
-
-/* results from luaD_precall */
-#define PCRLUA		0	/* initiated a call to a Lua function */
-#define PCRC		1	/* did a call to a C function */
-#define PCRYIELD	2	/* C funtion yielded */
-
-
-/* type of protected functions, to be ran by `runprotected' */
-typedef void (*Pfunc) (lua_State *L, void *ud);
-
-LUAI_FUNC int luaD_protectedparser (lua_State *L, ZIO *z, const char *name);
-LUAI_FUNC void luaD_callhook (lua_State *L, int event, int line);
-LUAI_FUNC int luaD_precall (lua_State *L, StkId func, int nresults);
-LUAI_FUNC void luaD_call (lua_State *L, StkId func, int nResults);
-LUAI_FUNC int luaD_pcall (lua_State *L, Pfunc func, void *u,
-                                        ptrdiff_t oldtop, ptrdiff_t ef);
-LUAI_FUNC int luaD_poscall (lua_State *L, StkId firstResult);
-LUAI_FUNC void luaD_reallocCI (lua_State *L, int newsize);
-LUAI_FUNC void luaD_reallocstack (lua_State *L, int newsize);
-LUAI_FUNC void luaD_growstack (lua_State *L, int n);
-
-LUAI_FUNC void luaD_throw (lua_State *L, int errcode);
-LUAI_FUNC int luaD_rawrunprotected (lua_State *L, Pfunc f, void *ud);
-
-LUAI_FUNC void luaD_seterrorobj (lua_State *L, int errcode, StkId oldtop);
-
-#endif
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/ldump.c
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/ldump.c b/libs/elua/elua_base/src/ldump.c
deleted file mode 100644
index 7930940..0000000
--- a/libs/elua/elua_base/src/ldump.c
+++ /dev/null
@@ -1,321 +0,0 @@
-/*
-** $Id: ldump.c,v 2.8.1.1 2007/12/27 13:02:25 roberto Exp $
-** save precompiled Lua chunks
-** See Copyright Notice in lua.h
-*/
-
-#include <stddef.h>
-#include <sys/types.h>
-#include <string.h>
-
-#define ldump_c
-#define LUA_CORE
-
-#include "lua.h"
-
-#include "lobject.h"
-#include "lstate.h"
-#include "lundump.h"
-
-typedef struct {
- lua_State* L;
- lua_Writer writer;
- void* data;
- int strip;
- int status;
- DumpTargetInfo target;
- size_t wrote;
-} DumpState;
-
-#define DumpMem(b,n,size,D)	DumpBlock(b,(n)*(size),D)
-#define DumpVar(x,D)	 	DumpMem(&x,1,sizeof(x),D)
-
-static void DumpBlock(const void* b, size_t size, DumpState* D)
-{
- if (D->status==0)
- {
-  lua_unlock(D->L);
-  D->status=(*D->writer)(D->L,b,size,D->data);
-  D->wrote+=size;
-  lua_lock(D->L);
- }
-}
-
-static void DumpChar(int y, DumpState* D)
-{
- char x=(char)y;
- DumpVar(x,D);
-}
-
-static void Align4(DumpState *D)
-{
- while(D->wrote&3)
-  DumpChar(0,D);
-}
-
-static void MaybeByteSwap(char *number, size_t numbersize, DumpState *D)
-{
- int x=1;
- int platform_little_endian = *(char*)&x;
- if (platform_little_endian != D->target.little_endian)
- {
-  unsigned long i;
-  for (i=0; i<numbersize/2; i++)
-  {
-   char temp = number[i];
-   number[i] = number[numbersize-1-i];
-   number[numbersize-1-i] = temp;
-  }
- }
-}
-
-static void DumpIntWithSize(int x, int sizeof_int, DumpState* D)
-{
- /* dump signed integer */
- switch(sizeof_int) {
-  case 1: {
-   if (x>0x7F || x<(-0x80)) D->status=LUA_ERR_CC_INTOVERFLOW; 
-   DumpChar(x,D);
-  } break;
-  case 2: {
-   if (x>0x7FFF || x<(-0x8000)) D->status=LUA_ERR_CC_INTOVERFLOW; 
-   int16_t y=(int16_t)x;
-   MaybeByteSwap((char*)&y,2,D);
-   DumpVar(y,D);
-  } break;
-  case 4: {
-   /* Need to reduce bounds by 1 to avoid messing 32-bit compilers up */
-   if (x>0x7FFFFFFE || x<(-0x7FFFFFFF)) D->status=LUA_ERR_CC_INTOVERFLOW; 
-   int32_t y=(int32_t)x;
-   MaybeByteSwap((char*)&y,4,D);
-   DumpVar(y,D);
-  } break;
-  default: lua_assert(0);
- }
-}
-
-static void DumpInt(int x, DumpState* D)
-{
- DumpIntWithSize(x,D->target.sizeof_int,D);
-}
-
-static void DumpSize(uint32_t x, DumpState* D)
-{
- /* dump unsigned integer */
- switch(D->target.sizeof_strsize_t) {
-  case 1: {
-   if (x>0xFF) D->status=LUA_ERR_CC_INTOVERFLOW; 
-   DumpChar(x,D);
-  } break;
-  case 2: {
-   if (x>0xFFFF) D->status=LUA_ERR_CC_INTOVERFLOW;
-   uint16_t y=(uint16_t)x;
-   MaybeByteSwap((char*)&y,2,D);
-   DumpVar(y,D);
-  } break;
-  case 4: {
-   /* Reduce bounds to avoid messing 32-bit compilers up */
-   if (x>0xFFFFFFFE) D->status=LUA_ERR_CC_INTOVERFLOW;
-   uint32_t y=x;
-   MaybeByteSwap((char*)&y,4,D);
-   DumpVar(y,D);
-  } break;
-  default: lua_assert(0);
- }
-}
-
-static void DumpNumber(lua_Number x, DumpState* D)
-{
-#if defined( LUA_NUMBER_INTEGRAL ) && !defined( LUA_CROSS_COMPILER )
-  DumpIntWithSize(x,D->target.sizeof_lua_Number,D);
-#else // #if defined( LUA_NUMBER_INTEGRAL ) && !defined( LUA_CROSS_COMPILER )
- if (D->target.lua_Number_integral)
- {
-  if (((float)(int)x)!=x) D->status=LUA_ERR_CC_NOTINTEGER;
-  DumpIntWithSize(x,D->target.sizeof_lua_Number,D);
- }
- else
- {
-  switch(D->target.sizeof_lua_Number)
-  {
-   /* do we need bounds checking? */
-   case 4: {
-    float y=x;
-    MaybeByteSwap((char*)&y,4,D);
-    DumpVar(y,D);
-   } break;
-   case 8: {
-    double y=x;
-    // ARM FPA mode: keep endianness, but swap high and low parts of the 
-    // memory representation. This is the default compilation mode for ARM 
-    // targets with non-EABI gcc
-    if(D->target.is_arm_fpa)
-    {
-      char *pnum=(char*)&y, temp[4];
-      memcpy(temp,pnum,4);
-      memcpy(pnum,pnum+4,4);
-      memcpy(pnum+4,temp,4);
-    }    
-    MaybeByteSwap((char*)&y,8,D);
-    DumpVar(y,D);
-   } break;
-   default: lua_assert(0);
-  }
- }
-#endif // #if defined( LUA_NUMBER_INTEGRAL ) && !defined( LUA_CROSS_COMPILER )
-}
-
-static void DumpCode(const Proto *f, DumpState* D)
-{
- DumpInt(f->sizecode,D);
- char buf[10];
- int i;
- Align4(D);
- for (i=0; i<f->sizecode; i++)
- {
-  memcpy(buf,&f->code[i],sizeof(Instruction));
-  MaybeByteSwap(buf,sizeof(Instruction),D);
-  DumpBlock(buf,sizeof(Instruction),D);
- }
-}
-
-static void DumpString(const TString* s, DumpState* D)
-{
- if (s==NULL || getstr(s)==NULL)
- {
-  strsize_t size=0;
-  DumpSize(size,D);
- }
- else
- {
-  strsize_t size=( strsize_t )s->tsv.len+1;		/* include trailing '\0' */
-  DumpSize(size,D);
-  DumpBlock(getstr(s),size,D);
- }
-}
-
-static void DumpFunction(const Proto* f, const TString* p, DumpState* D);
-
-static void DumpConstants(const Proto* f, DumpState* D)
-{
- int i,n=f->sizek;
- DumpInt(n,D);
- for (i=0; i<n; i++)
- {
-  const TValue* o=&f->k[i];
-  DumpChar(ttype(o),D);
-  switch (ttype(o))
-  {
-   case LUA_TNIL:
-	break;
-   case LUA_TBOOLEAN:
-	DumpChar(bvalue(o),D);
-	break;
-   case LUA_TNUMBER:
-	DumpNumber(nvalue(o),D);
-	break;
-   case LUA_TSTRING:
-	DumpString(rawtsvalue(o),D);
-	break;
-   default:
-	lua_assert(0);			/* cannot happen */
-	break;
-  }
- }
- n=f->sizep;
- DumpInt(n,D);
- for (i=0; i<n; i++) DumpFunction(f->p[i],f->source,D);
-}
-
-static void DumpDebug(const Proto* f, DumpState* D)
-{
- int i,n;
- n= (D->strip) ? 0 : f->sizelineinfo;
- DumpInt(n,D);
- Align4(D);
- for (i=0; i<n; i++)
- {
-  DumpInt(f->lineinfo[i],D);
- }
- 
- n= (D->strip) ? 0 : f->sizelocvars;
- DumpInt(n,D);
- for (i=0; i<n; i++)
- {
-  DumpString(f->locvars[i].varname,D);
-  DumpInt(f->locvars[i].startpc,D);
-  DumpInt(f->locvars[i].endpc,D);
- }
-
- n= (D->strip) ? 0 : f->sizeupvalues;
- DumpInt(n,D);
- for (i=0; i<n; i++) DumpString(f->upvalues[i],D);
-}
-
-static void DumpFunction(const Proto* f, const TString* p, DumpState* D)
-{
- DumpString((f->source==p || D->strip) ? NULL : f->source,D);
- DumpInt(f->linedefined,D);
- DumpInt(f->lastlinedefined,D);
- DumpChar(f->nups,D);
- DumpChar(f->numparams,D);
- DumpChar(f->is_vararg,D);
- DumpChar(f->maxstacksize,D);
- DumpCode(f,D);
- DumpConstants(f,D);
- DumpDebug(f,D);
-}
-
-static void DumpHeader(DumpState* D)
-{
- char buf[LUAC_HEADERSIZE];
- char *h=buf;
- 
- /* This code must be kept in sync wiht luaU_header */
- memcpy(h,LUA_SIGNATURE,sizeof(LUA_SIGNATURE)-1);
- h+=sizeof(LUA_SIGNATURE)-1;
- *h++=(char)LUAC_VERSION;
- *h++=(char)LUAC_FORMAT;
- *h++=(char)D->target.little_endian;
- *h++=(char)D->target.sizeof_int;
- *h++=(char)D->target.sizeof_strsize_t;
- *h++=(char)sizeof(Instruction);
- *h++=(char)D->target.sizeof_lua_Number;
- *h++=(char)D->target.lua_Number_integral;
- 
- DumpBlock(buf,LUAC_HEADERSIZE,D);
-}
-
-/*
-** dump Lua function as precompiled chunk with specified target
-*/
-int luaU_dump_crosscompile (lua_State* L, const Proto* f, lua_Writer w, void* data, int strip, DumpTargetInfo target)
-{
- DumpState D;
- D.L=L;
- D.writer=w;
- D.data=data;
- D.strip=strip;
- D.status=0;
- D.target=target;
- D.wrote=0;
- DumpHeader(&D);
- DumpFunction(f,NULL,&D);
- return D.status;
-}
-
-/*
- ** dump Lua function as precompiled chunk with local machine as target
- */
-int luaU_dump (lua_State* L, const Proto* f, lua_Writer w, void* data, int strip)
-{
- DumpTargetInfo target;
- int test=1;
- target.little_endian=*(char*)&test;
- target.sizeof_int=sizeof(int);
- target.sizeof_strsize_t=sizeof(strsize_t);
- target.sizeof_lua_Number=sizeof(lua_Number);
- target.lua_Number_integral=(((lua_Number)0.5)==0);
- target.is_arm_fpa=0;
- return luaU_dump_crosscompile(L,f,w,data,strip,target);
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/legc.c
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/legc.c b/libs/elua/elua_base/src/legc.c
deleted file mode 100644
index bbef290..0000000
--- a/libs/elua/elua_base/src/legc.c
+++ /dev/null
@@ -1,12 +0,0 @@
-// Lua EGC (Emergeny Garbage Collector) interface
-
-#include "legc.h"
-#include "lstate.h"
-
-void legc_set_mode(lua_State *L, int mode, unsigned limit) {
-   global_State *g = G(L); 
-   
-   g->egcmode = mode;
-   g->memlimit = limit;
-}
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/legc.h
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/legc.h b/libs/elua/elua_base/src/legc.h
deleted file mode 100644
index a0d9dde..0000000
--- a/libs/elua/elua_base/src/legc.h
+++ /dev/null
@@ -1,17 +0,0 @@
-// Lua EGC (Emergeny Garbage Collector) interface
-
-#ifndef __LEGC_H__
-#define __LEGC_H__
-
-#include "lstate.h"
-
-// EGC operations modes
-#define EGC_NOT_ACTIVE        0   // EGC disabled
-#define EGC_ON_ALLOC_FAILURE  1   // run EGC on allocation failure
-#define EGC_ON_MEM_LIMIT      2   // run EGC when an upper memory limit is hit
-#define EGC_ALWAYS            4   // always run EGC before an allocation
-
-void legc_set_mode(lua_State *L, int mode, unsigned limit);
-
-#endif
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/lfunc.c
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/lfunc.c b/libs/elua/elua_base/src/lfunc.c
deleted file mode 100644
index 3f7a785..0000000
--- a/libs/elua/elua_base/src/lfunc.c
+++ /dev/null
@@ -1,176 +0,0 @@
-/*
-** $Id: lfunc.c,v 2.12.1.2 2007/12/28 14:58:43 roberto Exp $
-** Auxiliary functions to manipulate prototypes and closures
-** See Copyright Notice in lua.h
-*/
-
-
-#include <stddef.h>
-
-#define lfunc_c
-#define LUA_CORE
-
-#include "lua.h"
-
-#include "lfunc.h"
-#include "lgc.h"
-#include "lmem.h"
-#include "lobject.h"
-#include "lstate.h"
-
-
-
-Closure *luaF_newCclosure (lua_State *L, int nelems, Table *e) {
-  Closure *c = cast(Closure *, luaM_malloc(L, sizeCclosure(nelems)));
-  luaC_link(L, obj2gco(c), LUA_TFUNCTION);
-  c->c.isC = 1;
-  c->c.env = e;
-  c->c.nupvalues = cast_byte(nelems);
-  return c;
-}
-
-
-Closure *luaF_newLclosure (lua_State *L, int nelems, Table *e) {
-  Closure *c = cast(Closure *, luaM_malloc(L, sizeLclosure(nelems)));
-  luaC_link(L, obj2gco(c), LUA_TFUNCTION);
-  c->l.isC = 0;
-  c->l.env = e;
-  c->l.nupvalues = cast_byte(nelems);
-  while (nelems--) c->l.upvals[nelems] = NULL;
-  return c;
-}
-
-
-UpVal *luaF_newupval (lua_State *L) {
-  UpVal *uv = luaM_new(L, UpVal);
-  luaC_link(L, obj2gco(uv), LUA_TUPVAL);
-  uv->v = &uv->u.value;
-  setnilvalue(uv->v);
-  return uv;
-}
-
-
-UpVal *luaF_findupval (lua_State *L, StkId level) {
-  global_State *g = G(L);
-  GCObject **pp = &L->openupval;
-  UpVal *p;
-  UpVal *uv;
-  while (*pp != NULL && (p = ngcotouv(*pp))->v >= level) {
-    lua_assert(p->v != &p->u.value);
-    if (p->v == level) {  /* found a corresponding upvalue? */
-      if (isdead(g, obj2gco(p)))  /* is it dead? */
-        changewhite(obj2gco(p));  /* ressurect it */
-      return p;
-    }
-    pp = &p->next;
-  }
-  uv = luaM_new(L, UpVal);  /* not found: create a new one */
-  uv->tt = LUA_TUPVAL;
-  uv->v = level;  /* current value lives in the stack */
-  uv->next = *pp;  /* chain it in the proper position */
-  *pp = obj2gco(uv);
-  uv->u.l.prev = &g->uvhead;  /* double link it in `uvhead' list */
-  uv->u.l.next = g->uvhead.u.l.next;
-  uv->u.l.next->u.l.prev = uv;
-  g->uvhead.u.l.next = uv;
-  luaC_marknew(L, obj2gco(uv));
-  lua_assert(uv->u.l.next->u.l.prev == uv && uv->u.l.prev->u.l.next == uv);
-  return uv;
-}
-
-
-static void unlinkupval (UpVal *uv) {
-  lua_assert(uv->u.l.next->u.l.prev == uv && uv->u.l.prev->u.l.next == uv);
-  uv->u.l.next->u.l.prev = uv->u.l.prev;  /* remove from `uvhead' list */
-  uv->u.l.prev->u.l.next = uv->u.l.next;
-}
-
-
-void luaF_freeupval (lua_State *L, UpVal *uv) {
-  if (uv->v != &uv->u.value)  /* is it open? */
-    unlinkupval(uv);  /* remove from open list */
-  luaM_free(L, uv);  /* free upvalue */
-}
-
-
-void luaF_close (lua_State *L, StkId level) {
-  UpVal *uv;
-  global_State *g = G(L);
-  while (L->openupval != NULL && (uv = ngcotouv(L->openupval))->v >= level) {
-    GCObject *o = obj2gco(uv);
-    lua_assert(!isblack(o) && uv->v != &uv->u.value);
-    L->openupval = uv->next;  /* remove from `open' list */
-    if (isdead(g, o))
-      luaF_freeupval(L, uv);  /* free upvalue */
-    else {
-      unlinkupval(uv);
-      setobj(L, &uv->u.value, uv->v);
-      uv->v = &uv->u.value;  /* now current value lives here */
-      luaC_linkupval(L, uv);  /* link upvalue into `gcroot' list */
-    }
-  }
-}
-
-
-Proto *luaF_newproto (lua_State *L) {
-  Proto *f = luaM_new(L, Proto);
-  luaC_link(L, obj2gco(f), LUA_TPROTO);
-  f->k = NULL;
-  f->sizek = 0;
-  f->p = NULL;
-  f->sizep = 0;
-  f->code = NULL;
-  f->sizecode = 0;
-  f->sizelineinfo = 0;
-  f->sizeupvalues = 0;
-  f->nups = 0;
-  f->upvalues = NULL;
-  f->numparams = 0;
-  f->is_vararg = 0;
-  f->maxstacksize = 0;
-  f->lineinfo = NULL;
-  f->sizelocvars = 0;
-  f->locvars = NULL;
-  f->linedefined = 0;
-  f->lastlinedefined = 0;
-  f->source = NULL;
-  return f;
-}
-
-
-void luaF_freeproto (lua_State *L, Proto *f) {
-  luaM_freearray(L, f->p, f->sizep, Proto *);
-  luaM_freearray(L, f->k, f->sizek, TValue);
-  luaM_freearray(L, f->locvars, f->sizelocvars, struct LocVar);
-  luaM_freearray(L, f->upvalues, f->sizeupvalues, TString *);
-  if (!proto_is_readonly(f)) {
-    luaM_freearray(L, f->code, f->sizecode, Instruction);
-    luaM_freearray(L, f->lineinfo, f->sizelineinfo, int);
-  }
-  luaM_free(L, f);
-}
-
-
-void luaF_freeclosure (lua_State *L, Closure *c) {
-  int size = (c->c.isC) ? sizeCclosure(c->c.nupvalues) :
-                          sizeLclosure(c->l.nupvalues);
-  luaM_freemem(L, c, size);
-}
-
-
-/*
-** Look for n-th local variable at line `line' in function `func'.
-** Returns NULL if not found.
-*/
-const char *luaF_getlocalname (const Proto *f, int local_number, int pc) {
-  int i;
-  for (i = 0; i<f->sizelocvars && f->locvars[i].startpc <= pc; i++) {
-    if (pc < f->locvars[i].endpc) {  /* is variable active? */
-      local_number--;
-      if (local_number == 0)
-        return getstr(f->locvars[i].varname);
-    }
-  }
-  return NULL;  /* not found */
-}
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/lfunc.h
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/lfunc.h b/libs/elua/elua_base/src/lfunc.h
deleted file mode 100644
index 1450bb7..0000000
--- a/libs/elua/elua_base/src/lfunc.h
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
-** $Id: lfunc.h,v 2.4.1.1 2007/12/27 13:02:25 roberto Exp $
-** Auxiliary functions to manipulate prototypes and closures
-** See Copyright Notice in lua.h
-*/
-
-#ifndef lfunc_h
-#define lfunc_h
-
-
-#include "lobject.h"
-
-#include "lgc.h"
-
-#define sizeCclosure(n)	(cast(int, sizeof(CClosure)) + \
-                         cast(int, sizeof(TValue)*((n)-1)))
-
-#define sizeLclosure(n)	(cast(int, sizeof(LClosure)) + \
-                         cast(int, sizeof(TValue *)*((n)-1)))
-
-#define proto_readonly(p) l_setbit((p)->marked, READONLYBIT)
-#define proto_is_readonly(p) testbit((p)->marked, READONLYBIT)
-
-LUAI_FUNC Proto *luaF_newproto (lua_State *L);
-LUAI_FUNC Closure *luaF_newCclosure (lua_State *L, int nelems, Table *e);
-LUAI_FUNC Closure *luaF_newLclosure (lua_State *L, int nelems, Table *e);
-LUAI_FUNC UpVal *luaF_newupval (lua_State *L);
-LUAI_FUNC UpVal *luaF_findupval (lua_State *L, StkId level);
-LUAI_FUNC void luaF_close (lua_State *L, StkId level);
-LUAI_FUNC void luaF_freeproto (lua_State *L, Proto *f);
-LUAI_FUNC void luaF_freeclosure (lua_State *L, Closure *c);
-LUAI_FUNC void luaF_freeupval (lua_State *L, UpVal *uv);
-LUAI_FUNC const char *luaF_getlocalname (const Proto *func, int local_number,
-                                         int pc);
-
-
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/lgc.c
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/lgc.c b/libs/elua/elua_base/src/lgc.c
deleted file mode 100644
index 360533a..0000000
--- a/libs/elua/elua_base/src/lgc.c
+++ /dev/null
@@ -1,743 +0,0 @@
-/*
-** $Id: lgc.c,v 2.38.1.1 2007/12/27 13:02:25 roberto Exp $
-** Garbage Collector
-** See Copyright Notice in lua.h
-*/
-
-#include <string.h>
-
-#define lgc_c
-#define LUA_CORE
-
-#include "lua.h"
-
-#include "ldebug.h"
-#include "ldo.h"
-#include "lfunc.h"
-#include "lgc.h"
-#include "lmem.h"
-#include "lobject.h"
-#include "lstate.h"
-#include "lstring.h"
-#include "ltable.h"
-#include "ltm.h"
-#include "lrotable.h"
-
-#define GCSTEPSIZE	1024u
-#define GCSWEEPMAX	40
-#define GCSWEEPCOST	10
-#define GCFINALIZECOST	100
-
-
-#define maskmarks	cast_byte(~(bitmask(BLACKBIT)|WHITEBITS))
-
-#define makewhite(g,x)	\
-   ((x)->gch.marked = cast_byte(((x)->gch.marked & maskmarks) | luaC_white(g)))
-
-#define white2gray(x)	reset2bits((x)->gch.marked, WHITE0BIT, WHITE1BIT)
-#define black2gray(x)	resetbit((x)->gch.marked, BLACKBIT)
-
-#define stringmark(s)	reset2bits((s)->tsv.marked, WHITE0BIT, WHITE1BIT)
-
-
-#define isfinalized(u)		testbit((u)->marked, FINALIZEDBIT)
-#define markfinalized(u)	l_setbit((u)->marked, FINALIZEDBIT)
-
-
-#define KEYWEAK         bitmask(KEYWEAKBIT)
-#define VALUEWEAK       bitmask(VALUEWEAKBIT)
-
-
-
-#define markvalue(g,o) { checkconsistency(o); \
-  if (iscollectable(o) && iswhite(gcvalue(o))) reallymarkobject(g,gcvalue(o)); }
-
-#define markobject(g,t) { if (iswhite(obj2gco(t))) \
-		reallymarkobject(g, obj2gco(t)); }
-
-
-#define setthreshold(g)  (g->GCthreshold = (g->estimate/100) * g->gcpause)
-
-
-static void removeentry (Node *n) {
-  lua_assert(ttisnil(gval(n)));
-  if (iscollectable(gkey(n)))
-    setttype(gkey(n), LUA_TDEADKEY);  /* dead key; remove it */
-}
-
-
-static void reallymarkobject (global_State *g, GCObject *o) {
-  lua_assert(iswhite(o) && !isdead(g, o));
-  white2gray(o);
-  switch (o->gch.tt) {
-    case LUA_TSTRING: {
-      return;
-    }
-    case LUA_TUSERDATA: {
-      Table *mt = gco2u(o)->metatable;
-      gray2black(o);  /* udata are never gray */
-      if (mt && !luaR_isrotable(mt)) markobject(g, mt);
-      markobject(g, gco2u(o)->env);
-      return;
-    }
-    case LUA_TUPVAL: {
-      UpVal *uv = gco2uv(o);
-      markvalue(g, uv->v);
-      if (uv->v == &uv->u.value)  /* closed? */
-        gray2black(o);  /* open upvalues are never black */
-      return;
-    }
-    case LUA_TFUNCTION: {
-      gco2cl(o)->c.gclist = g->gray;
-      g->gray = o;
-      break;
-    }
-    case LUA_TTABLE: {
-      gco2h(o)->gclist = g->gray;
-      g->gray = o;
-      break;
-    }
-    case LUA_TTHREAD: {
-      gco2th(o)->gclist = g->gray;
-      g->gray = o;
-      break;
-    }
-    case LUA_TPROTO: {
-      gco2p(o)->gclist = g->gray;
-      g->gray = o;
-      break;
-    }
-    default: lua_assert(0);
-  }
-}
-
-
-static void marktmu (global_State *g) {
-  GCObject *u = g->tmudata;
-  if (u) {
-    do {
-      u = u->gch.next;
-      makewhite(g, u);  /* may be marked, if left from previous GC */
-      reallymarkobject(g, u);
-    } while (u != g->tmudata);
-  }
-}
-
-
-/* move `dead' udata that need finalization to list `tmudata' */
-size_t luaC_separateudata (lua_State *L, int all) {
-  global_State *g = G(L);
-  size_t deadmem = 0;
-  GCObject **p = &g->mainthread->next;
-  GCObject *curr;
-  while ((curr = *p) != NULL) {
-    if (!(iswhite(curr) || all) || isfinalized(gco2u(curr)))
-      p = &curr->gch.next;  /* don't bother with them */
-    else if (fasttm(L, gco2u(curr)->metatable, TM_GC) == NULL) {
-      markfinalized(gco2u(curr));  /* don't need finalization */
-      p = &curr->gch.next;
-    }
-    else {  /* must call its gc method */
-      deadmem += sizeudata(gco2u(curr));
-      markfinalized(gco2u(curr));
-      *p = curr->gch.next;
-      /* link `curr' at the end of `tmudata' list */
-      if (g->tmudata == NULL)  /* list is empty? */
-        g->tmudata = curr->gch.next = curr;  /* creates a circular list */
-      else {
-        curr->gch.next = g->tmudata->gch.next;
-        g->tmudata->gch.next = curr;
-        g->tmudata = curr;
-      }
-    }
-  }
-  return deadmem;
-}
-
-
-static int traversetable (global_State *g, Table *h) {
-  int i;
-  int weakkey = 0;
-  int weakvalue = 0;
-  const TValue *mode;
-  if (h->metatable && !luaR_isrotable(h->metatable))
-    markobject(g, h->metatable);
-  mode = gfasttm(g, h->metatable, TM_MODE);
-  if (mode && ttisstring(mode)) {  /* is there a weak mode? */
-    weakkey = (strchr(svalue(mode), 'k') != NULL);
-    weakvalue = (strchr(svalue(mode), 'v') != NULL);
-    if (weakkey || weakvalue) {  /* is really weak? */
-      h->marked &= ~(KEYWEAK | VALUEWEAK);  /* clear bits */
-      h->marked |= cast_byte((weakkey << KEYWEAKBIT) |
-                             (weakvalue << VALUEWEAKBIT));
-      h->gclist = g->weak;  /* must be cleared after GC, ... */
-      g->weak = obj2gco(h);  /* ... so put in the appropriate list */
-    }
-  }
-  if (weakkey && weakvalue) return 1;
-  if (!weakvalue) {
-    i = h->sizearray;
-    while (i--)
-      markvalue(g, &h->array[i]);
-  }
-  i = sizenode(h);
-  while (i--) {
-    Node *n = gnode(h, i);
-    lua_assert(ttype(gkey(n)) != LUA_TDEADKEY || ttisnil(gval(n)));
-    if (ttisnil(gval(n)))
-      removeentry(n);  /* remove empty entries */
-    else {
-      lua_assert(!ttisnil(gkey(n)));
-      if (!weakkey) markvalue(g, gkey(n));
-      if (!weakvalue) markvalue(g, gval(n));
-    }
-  }
-  return weakkey || weakvalue;
-}
-
-
-/*
-** All marks are conditional because a GC may happen while the
-** prototype is still being created
-*/
-static void traverseproto (global_State *g, Proto *f) {
-  int i;
-  if (f->source) stringmark(f->source);
-  for (i=0; i<f->sizek; i++)  /* mark literals */
-    markvalue(g, &f->k[i]);
-  for (i=0; i<f->sizeupvalues; i++) {  /* mark upvalue names */
-    if (f->upvalues[i])
-      stringmark(f->upvalues[i]);
-  }
-  for (i=0; i<f->sizep; i++) {  /* mark nested protos */
-    if (f->p[i])
-      markobject(g, f->p[i]);
-  }
-  for (i=0; i<f->sizelocvars; i++) {  /* mark local-variable names */
-    if (f->locvars[i].varname)
-      stringmark(f->locvars[i].varname);
-  }
-}
-
-
-
-static void traverseclosure (global_State *g, Closure *cl) {
-  markobject(g, cl->c.env);
-  if (cl->c.isC) {
-    int i;
-    for (i=0; i<cl->c.nupvalues; i++)  /* mark its upvalues */
-      markvalue(g, &cl->c.upvalue[i]);
-  }
-  else {
-    int i;
-    lua_assert(cl->l.nupvalues == cl->l.p->nups);
-    markobject(g, cl->l.p);
-    for (i=0; i<cl->l.nupvalues; i++) { /* mark its upvalues */
-      if(cl->l.upvals[i])
-        markobject(g, cl->l.upvals[i]);
-    }
-  }
-}
-
-
-static void checkstacksizes (lua_State *L, StkId max) {
-  int ci_used = cast_int(L->ci - L->base_ci);  /* number of `ci' in use */
-  int s_used = cast_int(max - L->stack);  /* part of stack in use */
-  if (L->size_ci > LUAI_MAXCALLS)  /* handling overflow? */
-    return;  /* do not touch the stacks */
-  if (4*ci_used < L->size_ci && 2*BASIC_CI_SIZE < L->size_ci)
-    luaD_reallocCI(L, L->size_ci/2);  /* still big enough... */
-  condhardstacktests(luaD_reallocCI(L, ci_used + 1));
-  if (4*s_used < L->stacksize &&
-      2*(BASIC_STACK_SIZE+EXTRA_STACK) < L->stacksize)
-    luaD_reallocstack(L, L->stacksize/2);  /* still big enough... */
-  condhardstacktests(luaD_reallocstack(L, s_used));
-}
-
-
-static void traversestack (global_State *g, lua_State *l) {
-  StkId o, lim;
-  CallInfo *ci;
-  markvalue(g, gt(l));
-  lim = l->top;
-  if(l->stack == NULL) return; /* no stack to traverse */
-  for (ci = l->base_ci; ci <= l->ci; ci++) {
-    lua_assert(ci->top <= l->stack_last);
-    if (lim < ci->top) lim = ci->top;
-  }
-  for (o = l->stack; o < l->top; o++)
-    markvalue(g, o);
-  for (; o <= lim; o++)
-    setnilvalue(o);
-  if (!isfixedstack(l)) /* if stack size is fixed, can't resize it. */
-    checkstacksizes(l, lim);
-}
-
-
-/*
-** traverse one gray object, turning it to black.
-** Returns `quantity' traversed.
-*/
-static l_mem propagatemark (global_State *g) {
-  GCObject *o = g->gray;
-  lua_assert(isgray(o));
-  gray2black(o);
-  switch (o->gch.tt) {
-    case LUA_TTABLE: {
-      Table *h = gco2h(o);
-      g->gray = h->gclist;
-      if (traversetable(g, h))  /* table is weak? */
-        black2gray(o);  /* keep it gray */
-      return sizeof(Table) + sizeof(TValue) * h->sizearray +
-                             sizeof(Node) * sizenode(h);
-    }
-    case LUA_TFUNCTION: {
-      Closure *cl = gco2cl(o);
-      g->gray = cl->c.gclist;
-      traverseclosure(g, cl);
-      return (cl->c.isC) ? sizeCclosure(cl->c.nupvalues) :
-                           sizeLclosure(cl->l.nupvalues);
-    }
-    case LUA_TTHREAD: {
-      lua_State *th = gco2th(o);
-      g->gray = th->gclist;
-      th->gclist = g->grayagain;
-      g->grayagain = o;
-      black2gray(o);
-      traversestack(g, th);
-      return sizeof(lua_State) + sizeof(TValue) * th->stacksize +
-                                 sizeof(CallInfo) * th->size_ci;
-    }
-    case LUA_TPROTO: {
-      Proto *p = gco2p(o);
-      g->gray = p->gclist;
-      traverseproto(g, p);
-      return sizeof(Proto) + sizeof(Proto *) * p->sizep +
-                             sizeof(TValue) * p->sizek + 
-                             sizeof(LocVar) * p->sizelocvars +
-                             sizeof(TString *) * p->sizeupvalues +
-                             (proto_is_readonly(p) ? 0 : sizeof(Instruction) * p->sizecode +
-                                                         sizeof(int) * p->sizelineinfo);
-    }
-    default: lua_assert(0); return 0;
-  }
-}
-
-
-static size_t propagateall (global_State *g) {
-  size_t m = 0;
-  while (g->gray) m += propagatemark(g);
-  return m;
-}
-
-
-/*
-** The next function tells whether a key or value can be cleared from
-** a weak table. Non-collectable objects are never removed from weak
-** tables. Strings behave as `values', so are never removed too. for
-** other objects: if really collected, cannot keep them; for userdata
-** being finalized, keep them in keys, but not in values
-*/
-static int iscleared (const TValue *o, int iskey) {
-  if (!iscollectable(o)) return 0;
-  if (ttisstring(o)) {
-    stringmark(rawtsvalue(o));  /* strings are `values', so are never weak */
-    return 0;
-  }
-  return iswhite(gcvalue(o)) ||
-    (ttisuserdata(o) && (!iskey && isfinalized(uvalue(o))));
-}
-
-
-/*
-** clear collected entries from weaktables
-*/
-static void cleartable (GCObject *l) {
-  while (l) {
-    Table *h = gco2h(l);
-    int i = h->sizearray;
-    lua_assert(testbit(h->marked, VALUEWEAKBIT) ||
-               testbit(h->marked, KEYWEAKBIT));
-    if (testbit(h->marked, VALUEWEAKBIT)) {
-      while (i--) {
-        TValue *o = &h->array[i];
-        if (iscleared(o, 0))  /* value was collected? */
-          setnilvalue(o);  /* remove value */
-      }
-    }
-    i = sizenode(h);
-    while (i--) {
-      Node *n = gnode(h, i);
-      if (!ttisnil(gval(n)) &&  /* non-empty entry? */
-          (iscleared(key2tval(n), 1) || iscleared(gval(n), 0))) {
-        setnilvalue(gval(n));  /* remove value ... */
-        removeentry(n);  /* remove entry from table */
-      }
-    }
-    l = h->gclist;
-  }
-}
-
-
-static void freeobj (lua_State *L, GCObject *o) {
-  switch (o->gch.tt) {
-    case LUA_TPROTO: luaF_freeproto(L, gco2p(o)); break;
-    case LUA_TFUNCTION: luaF_freeclosure(L, gco2cl(o)); break;
-    case LUA_TUPVAL: luaF_freeupval(L, gco2uv(o)); break;
-    case LUA_TTABLE: luaH_free(L, gco2h(o)); break;
-    case LUA_TTHREAD: {
-      lua_assert(gco2th(o) != L && gco2th(o) != G(L)->mainthread);
-      luaE_freethread(L, gco2th(o));
-      break;
-    }
-    case LUA_TSTRING: {
-      G(L)->strt.nuse--;
-      luaM_freemem(L, o, sizestring(gco2ts(o)));
-      break;
-    }
-    case LUA_TUSERDATA: {
-      luaM_freemem(L, o, sizeudata(gco2u(o)));
-      break;
-    }
-    default: lua_assert(0);
-  }
-}
-
-
-
-#define sweepwholelist(L,p)	sweeplist(L,p,MAX_LUMEM)
-
-
-static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count) {
-  GCObject *curr;
-  global_State *g = G(L);
-  int deadmask = otherwhite(g);
-  while ((curr = *p) != NULL && count-- > 0) {
-    if (curr->gch.tt == LUA_TTHREAD)  /* sweep open upvalues of each thread */
-      sweepwholelist(L, &gco2th(curr)->openupval);
-    if ((curr->gch.marked ^ WHITEBITS) & deadmask) {  /* not dead? */
-      lua_assert(!isdead(g, curr) || testbit(curr->gch.marked, FIXEDBIT));
-      makewhite(g, curr);  /* make it white (for next cycle) */
-      p = &curr->gch.next;
-    }
-    else {  /* must erase `curr' */
-      lua_assert(isdead(g, curr) || deadmask == bitmask(SFIXEDBIT));
-      *p = curr->gch.next;
-      freeobj(L, curr);
-    }
-  }
-  return p;
-}
-
-
-static void checkSizes (lua_State *L) {
-  global_State *g = G(L);
-  /* check size of string hash */
-  if (g->strt.nuse < cast(lu_int32, g->strt.size/4) &&
-      g->strt.size > MINSTRTABSIZE*2)
-    luaS_resize(L, g->strt.size/2);  /* table is too big */
-  /* it is not safe to re-size the buffer if it is in use. */
-  if (luaZ_bufflen(&g->buff) > 0) return;
-  /* check size of buffer */
-  if (luaZ_sizebuffer(&g->buff) > LUA_MINBUFFER*2) {  /* buffer too big? */
-    size_t newsize = luaZ_sizebuffer(&g->buff) / 2;
-    luaZ_resizebuffer(L, &g->buff, newsize);
-  }
-}
-
-
-static void GCTM (lua_State *L) {
-  global_State *g = G(L);
-  GCObject *o = g->tmudata->gch.next;  /* get first element */
-  Udata *udata = rawgco2u(o);
-  const TValue *tm;
-  /* remove udata from `tmudata' */
-  if (o == g->tmudata)  /* last element? */
-    g->tmudata = NULL;
-  else
-    g->tmudata->gch.next = udata->uv.next;
-  udata->uv.next = g->mainthread->next;  /* return it to `root' list */
-  g->mainthread->next = o;
-  makewhite(g, o);
-  tm = fasttm(L, udata->uv.metatable, TM_GC);
-  if (tm != NULL) {
-    lu_byte oldah = L->allowhook;
-    lu_mem oldt = g->GCthreshold;
-    L->allowhook = 0;  /* stop debug hooks during GC tag method */
-    g->GCthreshold = 2*g->totalbytes;  /* avoid GC steps */
-    setobj2s(L, L->top, tm);
-    setuvalue(L, L->top+1, udata);
-    L->top += 2;
-    luaD_call(L, L->top - 2, 0);
-    L->allowhook = oldah;  /* restore hooks */
-    g->GCthreshold = oldt;  /* restore threshold */
-  }
-}
-
-
-/*
-** Call all GC tag methods
-*/
-void luaC_callGCTM (lua_State *L) {
-  while (G(L)->tmudata)
-    GCTM(L);
-}
-
-
-void luaC_freeall (lua_State *L) {
-  global_State *g = G(L);
-  int i;
-  g->currentwhite = WHITEBITS | bitmask(SFIXEDBIT);  /* mask to collect all elements */
-  sweepwholelist(L, &g->rootgc);
-  for (i = 0; i < g->strt.size; i++)  /* free all string lists */
-    sweepwholelist(L, &g->strt.hash[i]);
-}
-
-
-static void markmt (global_State *g) {
-  int i;
-  for (i=0; i<NUM_TAGS; i++)
-    if (g->mt[i] && !luaR_isrotable(g->mt[i])) markobject(g, g->mt[i]);
-}
-
-
-/* mark root set */
-static void markroot (lua_State *L) {
-  global_State *g = G(L);
-  g->gray = NULL;
-  g->grayagain = NULL;
-  g->weak = NULL;
-  markobject(g, g->mainthread);
-  /* make global table be traversed before main stack */
-  markvalue(g, gt(g->mainthread));
-  markvalue(g, registry(L));
-  markmt(g);
-  g->gcstate = GCSpropagate;
-}
-
-
-static void remarkupvals (global_State *g) {
-  UpVal *uv;
-  for (uv = g->uvhead.u.l.next; uv != &g->uvhead; uv = uv->u.l.next) {
-    lua_assert(uv->u.l.next->u.l.prev == uv && uv->u.l.prev->u.l.next == uv);
-    if (isgray(obj2gco(uv)))
-      markvalue(g, uv->v);
-  }
-}
-
-
-static void atomic (lua_State *L) {
-  global_State *g = G(L);
-  size_t udsize;  /* total size of userdata to be finalized */
-  /* remark occasional upvalues of (maybe) dead threads */
-  remarkupvals(g);
-  /* traverse objects cautch by write barrier and by 'remarkupvals' */
-  propagateall(g);
-  /* remark weak tables */
-  g->gray = g->weak;
-  g->weak = NULL;
-  lua_assert(!iswhite(obj2gco(g->mainthread)));
-  markobject(g, L);  /* mark running thread */
-  markmt(g);  /* mark basic metatables (again) */
-  propagateall(g);
-  /* remark gray again */
-  g->gray = g->grayagain;
-  g->grayagain = NULL;
-  propagateall(g);
-  udsize = luaC_separateudata(L, 0);  /* separate userdata to be finalized */
-  marktmu(g);  /* mark `preserved' userdata */
-  udsize += propagateall(g);  /* remark, to propagate `preserveness' */
-  cleartable(g->weak);  /* remove collected objects from weak tables */
-  /* flip current white */
-  g->currentwhite = cast_byte(otherwhite(g));
-  g->sweepstrgc = 0;
-  g->sweepgc = &g->rootgc;
-  g->gcstate = GCSsweepstring;
-  g->estimate = g->totalbytes - udsize;  /* first estimate */
-}
-
-static void sweepstrstep (global_State *g, lua_State *L) {
-  lu_mem old = g->totalbytes;
-  sweepwholelist(L, &g->strt.hash[g->sweepstrgc++]);
-  if (g->sweepstrgc >= g->strt.size)  /* nothing more to sweep? */
-    g->gcstate = GCSsweep;  /* end sweep-string phase */
-  lua_assert(old >= g->totalbytes);
-  g->estimate -= old - g->totalbytes;
-}
-
-
-static l_mem singlestep (lua_State *L) {
-  global_State *g = G(L);
-  /*lua_checkmemory(L);*/
-  switch (g->gcstate) {
-    case GCSpause: {
-      markroot(L);  /* start a new collection */
-      return 0;
-    }
-    case GCSpropagate: {
-      if (g->gray)
-        return propagatemark(g);
-      else {  /* no more `gray' objects */
-        atomic(L);  /* finish mark phase */
-        return 0;
-      }
-    }
-    case GCSsweepstring: {
-      sweepstrstep(g, L);
-      return GCSWEEPCOST;
-    }
-    case GCSsweep: {
-      lu_mem old = g->totalbytes;
-      g->sweepgc = sweeplist(L, g->sweepgc, GCSWEEPMAX);
-      if (*g->sweepgc == NULL) {  /* nothing more to sweep? */
-        checkSizes(L);
-        g->gcstate = GCSfinalize;  /* end sweep phase */
-      }
-      lua_assert(old >= g->totalbytes);
-      g->estimate -= old - g->totalbytes;
-      return GCSWEEPMAX*GCSWEEPCOST;
-    }
-    case GCSfinalize: {
-      if (g->tmudata) {
-        GCTM(L);
-        if (g->estimate > GCFINALIZECOST)
-          g->estimate -= GCFINALIZECOST;
-        return GCFINALIZECOST;
-      }
-      else {
-        g->gcstate = GCSpause;  /* end collection */
-        g->gcdept = 0;
-        return 0;
-      }
-    }
-    default: lua_assert(0); return 0;
-  }
-}
-
-
-void luaC_step (lua_State *L) {
-  global_State *g = G(L);
-  if(is_block_gc(L)) return;
-  set_block_gc(L);
-  l_mem lim = (GCSTEPSIZE/100) * g->gcstepmul;
-  if (lim == 0)
-    lim = (MAX_LUMEM-1)/2;  /* no limit */
-  g->gcdept += g->totalbytes - g->GCthreshold;
-  if (g->estimate > g->totalbytes)
-    g->estimate = g->totalbytes;
-  do {
-    lim -= singlestep(L);
-    if (g->gcstate == GCSpause)
-      break;
-  } while (lim > 0);
-  if (g->gcstate != GCSpause) {
-    if (g->gcdept < GCSTEPSIZE)
-      g->GCthreshold = g->totalbytes + GCSTEPSIZE;  /* - lim/g->gcstepmul;*/
-    else {
-      g->gcdept -= GCSTEPSIZE;
-      g->GCthreshold = g->totalbytes;
-    }
-  }
-  else {
-    lua_assert(g->totalbytes >= g->estimate);
-    setthreshold(g);
-  }
-  unset_block_gc(L);
-}
-
-int luaC_sweepstrgc (lua_State *L) {
-  global_State *g = G(L);
-  if (g->gcstate == GCSsweepstring) {
-    sweepstrstep(g, L);
-    return (g->gcstate == GCSsweepstring) ? 1 : 0;
-  }
-  return 0;
-}
-
-void luaC_fullgc (lua_State *L) {
-  global_State *g = G(L);
-  if(is_block_gc(L)) return;
-  set_block_gc(L);
-  if (g->gcstate <= GCSpropagate) {
-    /* reset sweep marks to sweep all elements (returning them to white) */
-    g->sweepstrgc = 0;
-    g->sweepgc = &g->rootgc;
-    /* reset other collector lists */
-    g->gray = NULL;
-    g->grayagain = NULL;
-    g->weak = NULL;
-    g->gcstate = GCSsweepstring;
-  }
-  lua_assert(g->gcstate != GCSpause && g->gcstate != GCSpropagate);
-  /* finish any pending sweep phase */
-  while (g->gcstate != GCSfinalize) {
-    lua_assert(g->gcstate == GCSsweepstring || g->gcstate == GCSsweep);
-    singlestep(L);
-  }
-  markroot(L);
-  while (g->gcstate != GCSpause) {
-    singlestep(L);
-  }
-  setthreshold(g);
-  unset_block_gc(L);
-}
-
-
-void luaC_barrierf (lua_State *L, GCObject *o, GCObject *v) {
-  global_State *g = G(L);
-  lua_assert(isblack(o) && iswhite(v) && !isdead(g, v) && !isdead(g, o));
-  lua_assert(g->gcstate != GCSfinalize && g->gcstate != GCSpause);
-  lua_assert(ttype(&o->gch) != LUA_TTABLE);
-  /* must keep invariant? */
-  if (g->gcstate == GCSpropagate)
-    reallymarkobject(g, v);  /* restore invariant */
-  else  /* don't mind */
-    makewhite(g, o);  /* mark as white just to avoid other barriers */
-}
-
-
-void luaC_barrierback (lua_State *L, Table *t) {
-  global_State *g = G(L);
-  GCObject *o = obj2gco(t);
-  lua_assert(isblack(o) && !isdead(g, o));
-  lua_assert(g->gcstate != GCSfinalize && g->gcstate != GCSpause);
-  black2gray(o);  /* make table gray (again) */
-  t->gclist = g->grayagain;
-  g->grayagain = o;
-}
-
-
-void luaC_marknew (lua_State *L, GCObject *o) {
-  global_State *g = G(L);
-  o->gch.marked = luaC_white(g);
-  if (g->gcstate == GCSpropagate)
-    reallymarkobject(g, o);  /* mark new objects as gray during propagate state. */
-}
-
-
-void luaC_link (lua_State *L, GCObject *o, lu_byte tt) {
-  global_State *g = G(L);
-  o->gch.next = g->rootgc;
-  g->rootgc = o;
-  o->gch.marked = luaC_white(g);
-  o->gch.tt = tt;
-}
-
-
-void luaC_linkupval (lua_State *L, UpVal *uv) {
-  global_State *g = G(L);
-  GCObject *o = obj2gco(uv);
-  o->gch.next = g->rootgc;  /* link upvalue into `rootgc' list */
-  g->rootgc = o;
-  if (isgray(o)) { 
-    if (g->gcstate == GCSpropagate) {
-      gray2black(o);  /* closed upvalues need barrier */
-      luaC_barrier(L, uv, uv->v);
-    }
-    else {  /* sweep phase: sweep it (turning it into white) */
-      makewhite(g, o);
-      lua_assert(g->gcstate != GCSfinalize && g->gcstate != GCSpause);
-    }
-  }
-}
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/lgc.h
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/lgc.h b/libs/elua/elua_base/src/lgc.h
deleted file mode 100644
index 9c26932..0000000
--- a/libs/elua/elua_base/src/lgc.h
+++ /dev/null
@@ -1,136 +0,0 @@
-/*
-** $Id: lgc.h,v 2.15.1.1 2007/12/27 13:02:25 roberto Exp $
-** Garbage Collector
-** See Copyright Notice in lua.h
-*/
-
-#ifndef lgc_h
-#define lgc_h
-
-
-#include "lobject.h"
-
-
-/*
-** Possible states of the Garbage Collector
-*/
-#define GCSpause	0
-#define GCSpropagate	1
-#define GCSsweepstring	2
-#define GCSsweep	3
-#define GCSfinalize	4
-
-
-/*
-** some userful bit tricks
-*/
-#define resetbits(x,m)	((x) &= cast(lu_byte, ~(m)))
-#define setbits(x,m)	((x) |= (m))
-#define testbits(x,m)	((x) & (m))
-#define bitmask(b)	(1<<(b))
-#define bit2mask(b1,b2)	(bitmask(b1) | bitmask(b2))
-#define l_setbit(x,b)	setbits(x, bitmask(b))
-#define resetbit(x,b)	resetbits(x, bitmask(b))
-#define testbit(x,b)	testbits(x, bitmask(b))
-#define set2bits(x,b1,b2)	setbits(x, (bit2mask(b1, b2)))
-#define reset2bits(x,b1,b2)	resetbits(x, (bit2mask(b1, b2)))
-#define test2bits(x,b1,b2)	testbits(x, (bit2mask(b1, b2)))
-
-
-/*
-** Possible Garbage Collector flags.
-** Layout for bit use in 'gsflags' field in global_State structure.
-** bit 0 - Protect GC from recursive calls.
-** bit 1 - Don't try to shrink string table if EGC was called during a string table resize.
-*/
-#define GCFlagsNone          0
-#define GCBlockGCBit         0
-#define GCResizingStringsBit 1
-
-
-#define is_block_gc(L)    testbit(G(L)->gcflags, GCBlockGCBit)
-#define set_block_gc(L)   l_setbit(G(L)->gcflags, GCBlockGCBit)
-#define unset_block_gc(L) resetbit(G(L)->gcflags, GCBlockGCBit)
-#define is_resizing_strings_gc(L)    testbit(G(L)->gcflags, GCResizingStringsBit)
-#define set_resizing_strings_gc(L)   l_setbit(G(L)->gcflags, GCResizingStringsBit)
-#define unset_resizing_strings_gc(L) resetbit(G(L)->gcflags, GCResizingStringsBit)
-
-/*
-** Layout for bit use in `marked' field:
-** bit 0 - object is white (type 0)
-** bit 1 - object is white (type 1)
-** bit 2 - object is black
-** bit 3 - for thread: Don't resize thread's stack
-** bit 3 - for userdata: has been finalized
-** bit 3 - for tables: has weak keys
-** bit 4 - for tables: has weak values
-** bit 5 - object is fixed (should not be collected)
-** bit 6 - object is "super" fixed (only the main thread)
-** bit 7 - object is (partially) stored in read-only memory
-*/
-
-
-#define WHITE0BIT	0
-#define WHITE1BIT	1
-#define BLACKBIT	2
-#define FIXEDSTACKBIT	3
-#define FINALIZEDBIT	3
-#define KEYWEAKBIT	3
-#define VALUEWEAKBIT	4
-#define FIXEDBIT	5
-#define SFIXEDBIT	6
-#define READONLYBIT 7
-#define WHITEBITS	bit2mask(WHITE0BIT, WHITE1BIT)
-
-
-#define iswhite(x)      test2bits((x)->gch.marked, WHITE0BIT, WHITE1BIT)
-#define isblack(x)      testbit((x)->gch.marked, BLACKBIT)
-#define isgray(x)	(!isblack(x) && !iswhite(x))
-
-#define otherwhite(g)	(g->currentwhite ^ WHITEBITS)
-#define isdead(g,v)	((v)->gch.marked & otherwhite(g) & WHITEBITS)
-
-#define changewhite(x)	((x)->gch.marked ^= WHITEBITS)
-#define gray2black(x)	l_setbit((x)->gch.marked, BLACKBIT)
-
-#define valiswhite(x)	(iscollectable(x) && iswhite(gcvalue(x)))
-
-#define luaC_white(g)	cast(lu_byte, (g)->currentwhite & WHITEBITS)
-
-#define isfixedstack(x)	testbit((x)->marked, FIXEDSTACKBIT)
-#define fixedstack(x)	l_setbit((x)->marked, FIXEDSTACKBIT)
-#define unfixedstack(x)	resetbit((x)->marked, FIXEDSTACKBIT)
-
-#define luaC_checkGC(L) { \
-  condhardstacktests(luaD_reallocstack(L, L->stacksize - EXTRA_STACK - 1)); \
-  if (G(L)->totalbytes >= G(L)->GCthreshold) \
-	luaC_step(L); }
-
-
-#define luaC_barrier(L,p,v) { if (valiswhite(v) && isblack(obj2gco(p)))  \
-	luaC_barrierf(L,obj2gco(p),gcvalue(v)); }
-
-#define luaC_barriert(L,t,v) { if (valiswhite(v) && isblack(obj2gco(t)))  \
-	luaC_barrierback(L,t); }
-
-#define luaC_objbarrier(L,p,o)  \
-	{ if (iswhite(obj2gco(o)) && isblack(obj2gco(p))) \
-		luaC_barrierf(L,obj2gco(p),obj2gco(o)); }
-
-#define luaC_objbarriert(L,t,o)  \
-   { if (iswhite(obj2gco(o)) && isblack(obj2gco(t))) luaC_barrierback(L,t); }
-
-LUAI_FUNC size_t luaC_separateudata (lua_State *L, int all);
-LUAI_FUNC void luaC_callGCTM (lua_State *L);
-LUAI_FUNC void luaC_freeall (lua_State *L);
-LUAI_FUNC void luaC_step (lua_State *L);
-LUAI_FUNC void luaC_fullgc (lua_State *L);
-LUAI_FUNC int luaC_sweepstrgc (lua_State *L);
-LUAI_FUNC void luaC_marknew (lua_State *L, GCObject *o);
-LUAI_FUNC void luaC_link (lua_State *L, GCObject *o, lu_byte tt);
-LUAI_FUNC void luaC_linkupval (lua_State *L, UpVal *uv);
-LUAI_FUNC void luaC_barrierf (lua_State *L, GCObject *o, GCObject *v);
-LUAI_FUNC void luaC_barrierback (lua_State *L, Table *t);
-
-
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/linit.c
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/linit.c b/libs/elua/elua_base/src/linit.c
deleted file mode 100644
index 5e7290c..0000000
--- a/libs/elua/elua_base/src/linit.c
+++ /dev/null
@@ -1,154 +0,0 @@
-/*
-** $Id: linit.c,v 1.14.1.1 2007/12/27 13:02:25 roberto Exp $
-** Initialization of libraries for lua.c
-** See Copyright Notice in lua.h
-*/
-
-
-#define linit_c
-#define LUA_LIB
-
-#include "lua.h"
-
-#include "lualib.h"
-#include "lauxlib.h"
-#include "lrotable.h"
-#include "luaconf.h"
-#ifndef LUA_CROSS_COMPILER
-#include "platform_conf.h"
-#endif
-
-#ifdef LUA_RPC
-#include "desktop_conf.h"
-#endif
-
-LUALIB_API int luaopen_platform (lua_State *L);
-int luaopen_dummy(lua_State *L);
-
-// Declare table
-#if defined(LUA_PLATFORM_LIBS_ROM) && LUA_OPTIMIZE_MEMORY == 2
-#undef _ROM
-#define _ROM( name, openf, table ) extern const luaR_entry table[];
-LUA_PLATFORM_LIBS_ROM;
-#endif
-
-// ****************************************************************************
-// Platform module handling
-// Automatically generate all the data required for platform modules
-
-#if defined( PLATFORM_MODULES_ENABLE )
-
-#if LUA_OPTIMIZE_MEMORY == 2
-#undef _ROM
-#define _ROM( name, openf, table ) extern const luaR_entry table[];
-PLATFORM_MODULES_LIBS_ROM
-#else // #if LUA_OPTIMIZE_MEMORY == 2
-#undef _ROM
-#define _ROM( name, openf, table ) extern const luaL_reg table[];
-PLATFORM_MODULES_LIBS_ROM
-#endif // #if LUA_OPTIMIZE_MEMORY == 2
-
-#if LUA_OPTIMIZE_MEMORY == 2
-const luaR_entry platform_map[] = {
-#undef _ROM
-#define _ROM( name, openf, table ) { LRO_STRKEY( name ), LRO_ROVAL( table ) },
-  PLATFORM_MODULES_LIBS_ROM
-  { LRO_NILKEY, LRO_NILVAL }
-};
-#else // #if LUA_OPTIMIZE_MEMORY == 2
-typedef struct {
-  const char *name;
-  const luaL_reg *table;
-} PLATFORM_MODULE_ENTRY;
-
-static const PLATFORM_MODULE_ENTRY platform_map_tables[] = {
-#undef _ROM
-#define _ROM( name, openf, table ) { name, table },
-  PLATFORM_MODULES_LIBS_ROM
-  { NULL, NULL }
-};
-#endif // #if LUA_OPTIMIZE_MEMORY == 2
-
-#undef _ROM
-#define _ROM( name, openf, table ) int openf (lua_State*);
-PLATFORM_MODULES_LIBS_ROM
-static const lua_CFunction platform_open_funcs[] = {
-#undef _ROM
-#define _ROM( name, openf, table ) openf,
-  PLATFORM_MODULES_LIBS_ROM
-  luaopen_dummy
-};
-
-LUALIB_API int luaopen_platform (lua_State *L)
-{
-#if LUA_OPTIMIZE_MEMORY == 0
-  // Register the platform table first and each of the platform module's tables
-  const PLATFORM_MODULE_ENTRY *plibs = platform_map_tables;
-
-  lua_newtable(L);
-  lua_pushvalue(L, -1);
-  lua_setfield(L, LUA_GLOBALSINDEX, PS_LIB_TABLE_NAME);
-  for(; plibs->name; plibs ++) {
-    lua_newtable(L);
-    luaL_register(L, NULL, plibs->table);
-    lua_setfield(L, -2, plibs->name);
-  }
-  lua_pop(L, 1);
-#endif // #if LUA_OPTIMIZE_MEMORY == 0
-  // In any case, call each platform module's initialization function if present
-  unsigned i;
-  for (i = 0; i < sizeof(platform_open_funcs) / sizeof(lua_CFunction); i++) {
-    lua_pushcfunction(L, platform_open_funcs[i]);
-    lua_call(L, 0, 0);
-  }
-  return 0;
-}
-#endif // #if defined( PLATFORM_MODULES_ENABLE )
-
-// End of platform module section
-// ****************************************************************************
-
-
-// Dummy open function
-int luaopen_dummy(lua_State *L)
-{
-  return 0;
-}
-
-#undef _ROM
-#define _ROM( name, openf, table ) { name, openf },
-
-static const luaL_Reg lualibs[] = {
-  {"", luaopen_base},
-#ifdef LUA_PLATFORM_LIBS_REG
-  LUA_PLATFORM_LIBS_REG,
-#endif 
-#if defined(LUA_PLATFORM_LIBS_ROM)
-  LUA_PLATFORM_LIBS_ROM
-#endif
-#if defined(LUA_LIBS_NOLTR)
-  LUA_LIBS_NOLTR
-#endif
-  {NULL, NULL}
-};
-
-const luaR_table lua_rotable[] = 
-{
-#if defined(LUA_PLATFORM_LIBS_ROM) && LUA_OPTIMIZE_MEMORY == 2
-#undef _ROM
-#define _ROM( name, openf, table ) { name, table },
-  LUA_PLATFORM_LIBS_ROM
-#endif
-  {NULL, NULL}
-};
-
-LUALIB_API void luaL_openlibs (lua_State *L) {
-  const luaL_Reg *lib = lualibs;
-  for (; lib->name; lib++)
-    if (lib->func) {
-      lua_pushcfunction(L, lib->func);
-      lua_pushstring(L, lib->name);
-      lua_call(L, 1, 0);
-    }
-}
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/liolib.c.donotcompile
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/liolib.c.donotcompile b/libs/elua/elua_base/src/liolib.c.donotcompile
deleted file mode 100644
index aa68e25..0000000
--- a/libs/elua/elua_base/src/liolib.c.donotcompile
+++ /dev/null
@@ -1,619 +0,0 @@
-/*
-** $Id: liolib.c,v 2.73.1.4 2010/05/14 15:33:51 roberto Exp $
-** Standard I/O (and system) library
-** See Copyright Notice in lua.h
-*/
-
-
-#include <errno.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#define liolib_c
-#define LUA_LIB
-
-#include "lua.h"
-
-#include "lauxlib.h"
-#include "lualib.h"
-#include "lrotable.h"
-
-
-#define IO_INPUT	1
-#define IO_OUTPUT	2
-#define IO_STDERR	0
-
-#if LUA_OPTIMIZE_MEMORY != 2
-#define LUA_IO_GETFIELD(f)	lua_rawgeti(L, LUA_ENVIRONINDEX, f)
-#define LUA_IO_SETFIELD(f)  lua_rawseti(L, LUA_ENVIRONINDEX, f)
-#else
-#define LUA_IO_GETFIELD(f)  lua_rawgeti(L, LUA_REGISTRYINDEX, liolib_keys[f])
-#define LUA_IO_SETFIELD(f)  lua_rawseti(L, LUA_REGISTRYINDEX, liolib_keys[f])
-
-/* "Pseudo-random" keys for the registry */
-static const int liolib_keys[] = {(int)&luaL_callmeta, (int)&luaL_typerror, (int)&luaL_argerror};
-#endif
-
-static const char *const fnames[] = {"input", "output"};
-
-
-static int pushresult (lua_State *L, int i, const char *filename) {
-  int en = errno;  /* calls to Lua API may change this value */
-  if (i) {
-    lua_pushboolean(L, 1);
-    return 1;
-  }
-  else {
-    lua_pushnil(L);
-    if (filename)
-      lua_pushfstring(L, "%s: %s", filename, strerror(en));
-    else
-      lua_pushfstring(L, "%s", strerror(en));
-    lua_pushinteger(L, en);
-    return 3;
-  }
-}
-
-
-static void fileerror (lua_State *L, int arg, const char *filename) {
-  lua_pushfstring(L, "%s: %s", filename, strerror(errno));
-  luaL_argerror(L, arg, lua_tostring(L, -1));
-}
-
-
-#define tofilep(L)	((FILE **)luaL_checkudata(L, 1, LUA_FILEHANDLE))
-
-
-static int io_type (lua_State *L) {
-  void *ud;
-  luaL_checkany(L, 1);
-  ud = lua_touserdata(L, 1);
-  lua_getfield(L, LUA_REGISTRYINDEX, LUA_FILEHANDLE);
-  if (ud == NULL || !lua_getmetatable(L, 1) || !lua_rawequal(L, -2, -1))
-    lua_pushnil(L);  /* not a file */
-  else if (*((FILE **)ud) == NULL)
-    lua_pushliteral(L, "closed file");
-  else
-    lua_pushliteral(L, "file");
-  return 1;
-}
-
-
-static FILE *tofile (lua_State *L) {
-  FILE **f = tofilep(L);
-  if (*f == NULL)
-    luaL_error(L, "attempt to use a closed file");
-  return *f;
-}
-
-
-
-/*
-** When creating file handles, always creates a `closed' file handle
-** before opening the actual file; so, if there is a memory error, the
-** file is not left opened.
-*/
-static FILE **newfile (lua_State *L) {
-  FILE **pf = (FILE **)lua_newuserdata(L, sizeof(FILE *));
-  *pf = NULL;  /* file handle is currently `closed' */
-  luaL_getmetatable(L, LUA_FILEHANDLE);
-  lua_setmetatable(L, -2);
-  return pf;
-}
-
-
-#if LUA_OPTIMIZE_MEMORY != 2
-/*
-** function to (not) close the standard files stdin, stdout, and stderr
-*/
-static int io_noclose (lua_State *L) {
-  lua_pushnil(L);
-  lua_pushliteral(L, "cannot close standard file");
-  return 2;
-}
-
-
-/*
-** function to close 'popen' files
-*/
-static int io_pclose (lua_State *L) {
-  FILE **p = tofilep(L);
-  int ok = lua_pclose(L, *p);
-  *p = NULL;
-  return pushresult(L, ok, NULL);
-}
-
-
-/*
-** function to close regular files
-*/
-static int io_fclose (lua_State *L) {
-  FILE **p = tofilep(L);
-  int ok = (fclose(*p) == 0);
-  *p = NULL;
-  return pushresult(L, ok, NULL);
-}
-#endif
-
-static int aux_close (lua_State *L) {
-#if LUA_OPTIMIZE_MEMORY != 2
-  lua_getfenv(L, 1);
-  lua_getfield(L, -1, "__close");
-  return (lua_tocfunction(L, -1))(L);
-#else
-  FILE **p = tofilep(L);
-  if(*p == stdin || *p == stdout || *p == stderr)
-  {
-    lua_pushnil(L);
-    lua_pushliteral(L, "cannot close standard file");
-    return 2;  
-  }
-  int ok = (fclose(*p) == 0);
-  *p = NULL;
-  return pushresult(L, ok, NULL);
-#endif 
-}
-
-
-static int io_close (lua_State *L) {
-  if (lua_isnone(L, 1))
-    LUA_IO_GETFIELD(IO_OUTPUT);
-  tofile(L);  /* make sure argument is a file */
-  return aux_close(L);
-}
-
-
-static int io_gc (lua_State *L) {
-  FILE *f = *tofilep(L);
-  /* ignore closed files */
-  if (f != NULL)
-    aux_close(L);
-  return 0;
-}
-
-
-static int io_tostring (lua_State *L) {
-  FILE *f = *tofilep(L);
-  if (f == NULL)
-    lua_pushliteral(L, "file (closed)");
-  else
-    lua_pushfstring(L, "file (%p)", f);
-  return 1;
-}
-
-
-static int io_open (lua_State *L) {
-  const char *filename = luaL_checkstring(L, 1);
-  const char *mode = luaL_optstring(L, 2, "r");
-  FILE **pf = newfile(L);
-  *pf = fopen(filename, mode);
-  return (*pf == NULL) ? pushresult(L, 0, filename) : 1;
-}
-
-
-/*
-** this function has a separated environment, which defines the
-** correct __close for 'popen' files
-*/
-static int io_popen (lua_State *L) {
-  const char *filename = luaL_checkstring(L, 1);
-  const char *mode = luaL_optstring(L, 2, "r");
-  FILE **pf = newfile(L);
-  *pf = lua_popen(L, filename, mode);
-  return (*pf == NULL) ? pushresult(L, 0, filename) : 1;
-}
-
-
-static int io_tmpfile (lua_State *L) {
-  FILE **pf = newfile(L);
-  *pf = tmpfile();
-  return (*pf == NULL) ? pushresult(L, 0, NULL) : 1;
-}
-
-
-static FILE *getiofile (lua_State *L, int findex) {
-  FILE *f;
-  LUA_IO_GETFIELD(findex);
-  f = *(FILE **)lua_touserdata(L, -1);
-  if (f == NULL)
-    luaL_error(L, "standard %s file is closed", fnames[findex - 1]);
-  return f;
-}
-
-
-static int g_iofile (lua_State *L, int f, const char *mode) {
-  if (!lua_isnoneornil(L, 1)) {
-    const char *filename = lua_tostring(L, 1);
-    if (filename) {
-      FILE **pf = newfile(L);
-      *pf = fopen(filename, mode);
-      if (*pf == NULL)
-        fileerror(L, 1, filename);
-    }
-    else {
-      tofile(L);  /* check that it's a valid file handle */
-      lua_pushvalue(L, 1);
-    }
-    LUA_IO_SETFIELD(f);
-  }
-  /* return current value */
-  LUA_IO_GETFIELD(f);
-  return 1;
-}
-
-
-static int io_input (lua_State *L) {
-  return g_iofile(L, IO_INPUT, "r");
-}
-
-
-static int io_output (lua_State *L) {
-  return g_iofile(L, IO_OUTPUT, "w");
-}
-
-
-static int io_readline (lua_State *L);
-
-
-static void aux_lines (lua_State *L, int idx, int toclose) {
-  lua_pushvalue(L, idx);
-  lua_pushboolean(L, toclose);  /* close/not close file when finished */
-  lua_pushcclosure(L, io_readline, 2);
-}
-
-
-static int f_lines (lua_State *L) {
-  tofile(L);  /* check that it's a valid file handle */
-  aux_lines(L, 1, 0);
-  return 1;
-}
-
-
-static int io_lines (lua_State *L) {
-  if (lua_isnoneornil(L, 1)) {  /* no arguments? */
-    /* will iterate over default input */
-    LUA_IO_GETFIELD(IO_INPUT);
-    return f_lines(L);
-  }
-  else {
-    const char *filename = luaL_checkstring(L, 1);
-    FILE **pf = newfile(L);
-    *pf = fopen(filename, "r");
-    if (*pf == NULL)
-      fileerror(L, 1, filename);
-    aux_lines(L, lua_gettop(L), 1);
-    return 1;
-  }
-}
-
-
-/*
-** {======================================================
-** READ
-** =======================================================
-*/
-
-
-static int read_number (lua_State *L, FILE *f) {
-  lua_Number d;
-  if (fscanf(f, LUA_NUMBER_SCAN, &d) == 1) {
-    lua_pushnumber(L, d);
-    return 1;
-  }
-  else {
-    lua_pushnil(L);  /* "result" to be removed */
-    return 0;  /* read fails */
-  }
-}
-
-
-static int test_eof (lua_State *L, FILE *f) {
-  int c = getc(f);
-  ungetc(c, f);
-  lua_pushlstring(L, NULL, 0);
-  return (c != EOF);
-}
-
-
-static int read_line (lua_State *L, FILE *f) {
-  luaL_Buffer b;
-  luaL_buffinit(L, &b);
-  for (;;) {
-    size_t l;
-    char *p = luaL_prepbuffer(&b);
-    if (fgets(p, LUAL_BUFFERSIZE, f) == NULL) {  /* eof? */
-      luaL_pushresult(&b);  /* close buffer */
-      return (lua_objlen(L, -1) > 0);  /* check whether read something */
-    }
-    l = strlen(p);
-    if (l == 0 || p[l-1] != '\n')
-      luaL_addsize(&b, l);
-    else {
-      luaL_addsize(&b, l - 1);  /* do not include `eol' */
-      luaL_pushresult(&b);  /* close buffer */
-      return 1;  /* read at least an `eol' */
-    }
-  }
-}
-
-
-static int read_chars (lua_State *L, FILE *f, size_t n) {
-  size_t rlen;  /* how much to read */
-  size_t nr;  /* number of chars actually read */
-  luaL_Buffer b;
-  luaL_buffinit(L, &b);
-  rlen = LUAL_BUFFERSIZE;  /* try to read that much each time */
-  do {
-    char *p = luaL_prepbuffer(&b);
-    if (rlen > n) rlen = n;  /* cannot read more than asked */
-    nr = fread(p, sizeof(char), rlen, f);
-    luaL_addsize(&b, nr);
-    n -= nr;  /* still have to read `n' chars */
-  } while (n > 0 && nr == rlen);  /* until end of count or eof */
-  luaL_pushresult(&b);  /* close buffer */
-  return (n == 0 || lua_objlen(L, -1) > 0);
-}
-
-
-static int g_read (lua_State *L, FILE *f, int first) {
-  int nargs = lua_gettop(L) - 1;
-  int success;
-  int n;
-  clearerr(f);
-  if (nargs == 0) {  /* no arguments? */
-    success = read_line(L, f);
-    n = first+1;  /* to return 1 result */
-  }
-  else {  /* ensure stack space for all results and for auxlib's buffer */
-    luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments");
-    success = 1;
-    for (n = first; nargs-- && success; n++) {
-      if (lua_type(L, n) == LUA_TNUMBER) {
-        size_t l = (size_t)lua_tointeger(L, n);
-        success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l);
-      }
-      else {
-        const char *p = lua_tostring(L, n);
-        luaL_argcheck(L, p && p[0] == '*', n, "invalid option");
-        switch (p[1]) {
-          case 'n':  /* number */
-            success = read_number(L, f);
-            break;
-          case 'l':  /* line */
-            success = read_line(L, f);
-            break;
-          case 'a':  /* file */
-            read_chars(L, f, ~((size_t)0));  /* read MAX_SIZE_T chars */
-            success = 1; /* always success */
-            break;
-          default:
-            return luaL_argerror(L, n, "invalid format");
-        }
-      }
-    }
-  }
-  if (ferror(f))
-    return pushresult(L, 0, NULL);
-  if (!success) {
-    lua_pop(L, 1);  /* remove last result */
-    lua_pushnil(L);  /* push nil instead */
-  }
-  return n - first;
-}
-
-
-static int io_read (lua_State *L) {
-  return g_read(L, getiofile(L, IO_INPUT), 1);
-}
-
-
-static int f_read (lua_State *L) {
-  return g_read(L, tofile(L), 2);
-}
-
-
-static int io_readline (lua_State *L) {
-  FILE *f = *(FILE **)lua_touserdata(L, lua_upvalueindex(1));
-  int sucess;
-  if (f == NULL)  /* file is already closed? */
-    luaL_error(L, "file is already closed");
-  sucess = read_line(L, f);
-  if (ferror(f))
-    return luaL_error(L, "%s", strerror(errno));
-  if (sucess) return 1;
-  else {  /* EOF */
-    if (lua_toboolean(L, lua_upvalueindex(2))) {  /* generator created file? */
-      lua_settop(L, 0);
-      lua_pushvalue(L, lua_upvalueindex(1));
-      aux_close(L);  /* close it */
-    }
-    return 0;
-  }
-}
-
-/* }====================================================== */
-
-
-static int g_write (lua_State *L, FILE *f, int arg) {
-  int nargs = lua_gettop(L) - 1;
-  int status = 1;
-  for (; nargs--; arg++) {
-    if (lua_type(L, arg) == LUA_TNUMBER) {
-      /* optimization: could be done exactly as for strings */
-      status = status &&
-          fprintf(f, LUA_NUMBER_FMT, lua_tonumber(L, arg)) > 0;
-    }
-    else {
-      size_t l;
-      const char *s = luaL_checklstring(L, arg, &l);
-      status = status && (fwrite(s, sizeof(char), l, f) == l);
-    }
-  }
-  return pushresult(L, status, NULL);
-}
-
-
-static int io_write (lua_State *L) {
-  return g_write(L, getiofile(L, IO_OUTPUT), 1);
-}
-
-
-static int f_write (lua_State *L) {
-  return g_write(L, tofile(L), 2);
-}
-
-
-static int f_seek (lua_State *L) {
-  static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
-  static const char *const modenames[] = {"set", "cur", "end", NULL};
-  FILE *f = tofile(L);
-  int op = luaL_checkoption(L, 2, "cur", modenames);
-  long offset = luaL_optlong(L, 3, 0);
-  op = fseek(f, offset, mode[op]);
-  if (op)
-    return pushresult(L, 0, NULL);  /* error */
-  else {
-    lua_pushinteger(L, ftell(f));
-    return 1;
-  }
-}
-
-
-static int f_setvbuf (lua_State *L) {
-  static const int mode[] = {_IONBF, _IOFBF, _IOLBF};
-  static const char *const modenames[] = {"no", "full", "line", NULL};
-  FILE *f = tofile(L);
-  int op = luaL_checkoption(L, 2, NULL, modenames);
-  lua_Integer sz = luaL_optinteger(L, 3, LUAL_BUFFERSIZE);
-  int res = setvbuf(f, NULL, mode[op], sz);
-  return pushresult(L, res == 0, NULL);
-}
-
-
-
-static int io_flush (lua_State *L) {
-  return pushresult(L, fflush(getiofile(L, IO_OUTPUT)) == 0, NULL);
-}
-
-
-static int f_flush (lua_State *L) {
-  return pushresult(L, fflush(tofile(L)) == 0, NULL);
-}
-
-#define MIN_OPT_LEVEL 2
-#include "lrodefs.h"
-#if LUA_OPTIMIZE_MEMORY == 2
-const LUA_REG_TYPE iolib_funcs[] = {
-#else
-const LUA_REG_TYPE iolib[] = {
-#endif
-  {LSTRKEY("close"), LFUNCVAL(io_close)},
-  {LSTRKEY("flush"), LFUNCVAL(io_flush)},
-  {LSTRKEY("input"), LFUNCVAL(io_input)},
-  {LSTRKEY("lines"), LFUNCVAL(io_lines)},
-  {LSTRKEY("open"), LFUNCVAL(io_open)},
-  {LSTRKEY("output"), LFUNCVAL(io_output)},
-  {LSTRKEY("popen"), LFUNCVAL(io_popen)},
-  {LSTRKEY("read"), LFUNCVAL(io_read)},
-  {LSTRKEY("tmpfile"), LFUNCVAL(io_tmpfile)},
-  {LSTRKEY("type"), LFUNCVAL(io_type)},
-  {LSTRKEY("write"), LFUNCVAL(io_write)},
-  {LNILKEY, LNILVAL}
-};
-
-#if LUA_OPTIMIZE_MEMORY == 2
-static int luaL_index(lua_State *L)
-{
-  return luaR_findfunction(L, iolib_funcs);
-}
-  
-const luaL_Reg iolib[] = {
-  {"__index", luaL_index},
-  {NULL, NULL}
-};
-#endif
-
-#undef MIN_OPT_LEVEL
-#define MIN_OPT_LEVEL 1
-#include "lrodefs.h"
-const LUA_REG_TYPE flib[] = {
-  {LSTRKEY("close"), LFUNCVAL(io_close)},
-  {LSTRKEY("flush"), LFUNCVAL(f_flush)},
-  {LSTRKEY("lines"), LFUNCVAL(f_lines)},
-  {LSTRKEY("read"), LFUNCVAL(f_read)},
-  {LSTRKEY("seek"), LFUNCVAL(f_seek)},
-  {LSTRKEY("setvbuf"), LFUNCVAL(f_setvbuf)},
-  {LSTRKEY("write"), LFUNCVAL(f_write)},
-  {LSTRKEY("__gc"), LFUNCVAL(io_gc)},
-  {LSTRKEY("__tostring"), LFUNCVAL(io_tostring)},
-#if LUA_OPTIMIZE_MEMORY > 0
-  {LSTRKEY("__index"), LROVAL(flib)},
-#endif
-  {LNILKEY, LNILVAL}
-};
-
-static void createmeta (lua_State *L) {
-#if LUA_OPTIMIZE_MEMORY == 0
-  luaL_newmetatable(L, LUA_FILEHANDLE);  /* create metatable for file handles */
-  lua_pushvalue(L, -1);  /* push metatable */
-  lua_setfield(L, -2, "__index");  /* metatable.__index = metatable */
-  luaL_register(L, NULL, flib);  /* file methods */
-#else
-  luaL_rometatable(L, LUA_FILEHANDLE, (void*)flib);  /* create metatable for file handles */
-#endif
-}
-
-
-static void createstdfile (lua_State *L, FILE *f, int k, const char *fname) {
-  *newfile(L) = f;
-#if LUA_OPTIMIZE_MEMORY != 2
-  if (k > 0) {
-    lua_pushvalue(L, -1);
-    lua_rawseti(L, LUA_ENVIRONINDEX, k);
-  }
-  lua_pushvalue(L, -2);  /* copy environment */
-  lua_setfenv(L, -2);  /* set it */
-  lua_setfield(L, -3, fname);
-#else
-  lua_pushvalue(L, -1);
-  lua_rawseti(L, LUA_REGISTRYINDEX, liolib_keys[k]);
-  lua_setfield(L, -2, fname);
-#endif
-}
-
-#if LUA_OPTIMIZE_MEMORY != 2
-static void newfenv (lua_State *L, lua_CFunction cls) {
-  lua_createtable(L, 0, 1);
-  lua_pushcfunction(L, cls);
-  lua_setfield(L, -2, "__close");
-}
-#endif
-
-LUALIB_API int luaopen_io (lua_State *L) {
-  createmeta(L);
-#if LUA_OPTIMIZE_MEMORY != 2
-  /* create (private) environment (with fields IO_INPUT, IO_OUTPUT, __close) */
-  newfenv(L, io_fclose);
-  lua_replace(L, LUA_ENVIRONINDEX);
-  /* open library */
-  luaL_register(L, LUA_IOLIBNAME, iolib);
-  newfenv(L, io_noclose);  /* close function for default files */
-#else
-  luaL_register_light(L, LUA_IOLIBNAME, iolib);
-  lua_pushvalue(L, -1);
-  lua_setmetatable(L, -2);
-#endif
-  /* create (and set) default files */
-  createstdfile(L, stdin, IO_INPUT, "stdin");
-  createstdfile(L, stdout, IO_OUTPUT, "stdout");
-  createstdfile(L, stderr, IO_STDERR, "stderr");
-#if LUA_OPTIMIZE_MEMORY != 2
-  lua_pop(L, 1);  /* pop environment for default files */
-  lua_getfield(L, -1, "popen");
-  newfenv(L, io_pclose);  /* create environment for 'popen' */
-  lua_setfenv(L, -2);  /* set fenv for 'popen' */
-  lua_pop(L, 1);  /* pop 'popen' */
-#endif
-  return 1;
-}


[37/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/include/os/arch/cortex_m0/os/os_arch.h
----------------------------------------------------------------------
diff --git a/kernel/os/include/os/arch/cortex_m0/os/os_arch.h b/kernel/os/include/os/arch/cortex_m0/os/os_arch.h
new file mode 100755
index 0000000..1a83ba9
--- /dev/null
+++ b/kernel/os/include/os/arch/cortex_m0/os/os_arch.h
@@ -0,0 +1,74 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 _OS_ARCH_ARM_H
+#define _OS_ARCH_ARM_H
+
+#include <stdint.h>
+#include <mcu/cortex_m0.h>
+
+struct os_task;
+
+/* Run in priviliged or unprivileged Thread mode */
+#define OS_RUN_PRIV         (0)
+#define OS_RUN_UNPRIV       (1)
+
+/* CPU status register */
+typedef uint32_t os_sr_t;
+/* Stack type, aligned to a 32-bit word. */
+#define OS_STACK_PATTERN    (0xdeadbeef)
+
+typedef uint32_t os_stack_t;
+#define OS_ALIGNMENT        (4)
+#define OS_STACK_ALIGNMENT  (8)
+
+/*
+ * Stack sizes for common OS tasks
+ */
+#define OS_SANITY_STACK_SIZE (64)
+#define OS_IDLE_STACK_SIZE (64)
+
+#define OS_STACK_ALIGN(__nmemb) \
+    (OS_ALIGN((__nmemb), OS_STACK_ALIGNMENT))
+
+/* Enter a critical section, save processor state, and block interrupts */
+#define OS_ENTER_CRITICAL(__os_sr) (__os_sr = os_arch_save_sr())
+/* Exit a critical section, restore processor state and unblock interrupts */
+#define OS_EXIT_CRITICAL(__os_sr) (os_arch_restore_sr(__os_sr))
+#define OS_ASSERT_CRITICAL() (assert(os_arch_in_critical()))
+
+os_stack_t *os_arch_task_stack_init(struct os_task *, os_stack_t *, int);
+void timer_handler(void);
+void os_arch_ctx_sw(struct os_task *);
+os_sr_t os_arch_save_sr(void);
+void os_arch_restore_sr(os_sr_t);
+int os_arch_in_critical(void);
+void os_arch_init(void);
+uint32_t os_arch_start(void);
+os_error_t os_arch_os_init(void);
+os_error_t os_arch_os_start(void);
+void os_set_env(os_stack_t *);
+void os_arch_init_task_stack(os_stack_t *sf);
+void os_default_irq_asm(void);
+
+/* External function prototypes supplied by BSP */
+void os_bsp_systick_init(uint32_t os_ticks_per_sec, int prio);
+void os_bsp_ctx_sw(void);
+
+#endif /* _OS_ARCH_ARM_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/include/os/arch/cortex_m4/os/os_arch.h
----------------------------------------------------------------------
diff --git a/kernel/os/include/os/arch/cortex_m4/os/os_arch.h b/kernel/os/include/os/arch/cortex_m4/os/os_arch.h
new file mode 100755
index 0000000..9e43a7a
--- /dev/null
+++ b/kernel/os/include/os/arch/cortex_m4/os/os_arch.h
@@ -0,0 +1,75 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 _OS_ARCH_ARM_H
+#define _OS_ARCH_ARM_H
+
+#include <stdint.h>
+#include "mcu/cortex_m4.h"
+
+struct os_task;
+
+/* Run in priviliged or unprivileged Thread mode */
+#define OS_RUN_PRIV         (0)
+#define OS_RUN_UNPRIV       (1)
+
+/* CPU status register */
+typedef uint32_t os_sr_t;
+/* Stack type, aligned to a 32-bit word. */
+#define OS_STACK_PATTERN    (0xdeadbeef)
+
+typedef uint32_t os_stack_t;
+#define OS_ALIGNMENT        (4)
+#define OS_STACK_ALIGNMENT  (8)
+
+/*
+ * Stack sizes for common OS tasks
+ */
+#define OS_SANITY_STACK_SIZE (64)
+#define OS_IDLE_STACK_SIZE (64)
+
+#define OS_STACK_ALIGN(__nmemb) \
+    (OS_ALIGN((__nmemb), OS_STACK_ALIGNMENT))
+
+/* Enter a critical section, save processor state, and block interrupts */
+#define OS_ENTER_CRITICAL(__os_sr) (__os_sr = os_arch_save_sr())
+/* Exit a critical section, restore processor state and unblock interrupts */
+#define OS_EXIT_CRITICAL(__os_sr) (os_arch_restore_sr(__os_sr))
+#define OS_ASSERT_CRITICAL() (assert(os_arch_in_critical()))
+
+os_stack_t *os_arch_task_stack_init(struct os_task *, os_stack_t *, int);
+void timer_handler(void);
+void os_arch_ctx_sw(struct os_task *);
+os_sr_t os_arch_save_sr(void);
+void os_arch_restore_sr(os_sr_t);
+int os_arch_in_critical(void);
+void os_arch_init(void);
+uint32_t os_arch_start(void);
+os_error_t os_arch_os_init(void);
+os_error_t os_arch_os_start(void);
+void os_set_env(os_stack_t *);
+void os_arch_init_task_stack(os_stack_t *sf);
+void os_default_irq_asm(void);
+
+/* External function prototypes supplied by BSP */
+void os_bsp_systick_init(uint32_t os_tick_per_sec, int prio);
+void os_bsp_idle(os_time_t ticks);
+void os_bsp_ctx_sw(void);
+
+#endif /* _OS_ARCH_ARM_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/include/os/arch/sim/os/os_arch.h
----------------------------------------------------------------------
diff --git a/kernel/os/include/os/arch/sim/os/os_arch.h b/kernel/os/include/os/arch/sim/os/os_arch.h
new file mode 100644
index 0000000..d9570c8
--- /dev/null
+++ b/kernel/os/include/os/arch/sim/os/os_arch.h
@@ -0,0 +1,74 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 _OS_ARCH_SIM_H
+#define _OS_ARCH_SIM_H
+
+#include <mcu/mcu_sim.h>
+
+struct os_task;
+
+/* CPU status register */
+typedef unsigned int os_sr_t;
+/* Stack type, aligned to a 32-bit word. */
+#define OS_STACK_PATTERN (0xdeadbeef)
+
+typedef unsigned int os_stack_t;
+#define OS_ALIGNMENT (4)
+#define OS_STACK_ALIGNMENT (16)
+
+/*
+ * Stack sizes for common OS tasks
+ */
+#define OS_SANITY_STACK_SIZE (1024)
+#define OS_IDLE_STACK_SIZE (1024)
+
+/*
+ * The 'sim' architecture-specific code does not have as much control on
+ * stack usage as the real embedded architectures.
+ *
+ * For e.g. the space occupied by the signal handler frame on the task
+ * stack is entirely dependent on the host OS.
+ *
+ * Deal with this by scaling the stack size by a factor of 16. The scaling
+ * factor can be arbitrarily large because the stacks are allocated from
+ * BSS and thus don't add to either the executable size or resident
+ * memory.
+ */
+#define OS_STACK_ALIGN(__nmemb) \
+    (OS_ALIGN(((__nmemb) * 16), OS_STACK_ALIGNMENT))
+
+/* Enter a critical section, save processor state, and block interrupts */
+#define OS_ENTER_CRITICAL(__os_sr) (__os_sr = os_arch_save_sr())
+/* Exit a critical section, restore processor state and unblock interrupts */
+#define OS_EXIT_CRITICAL(__os_sr) (os_arch_restore_sr(__os_sr))
+#define OS_ASSERT_CRITICAL() (assert(os_arch_in_critical()))
+
+void _Die(char *file, int line);
+
+os_stack_t *os_arch_task_stack_init(struct os_task *, os_stack_t *, int);
+void os_arch_ctx_sw(struct os_task *);
+os_sr_t os_arch_save_sr(void);
+void os_arch_restore_sr(os_sr_t sr);
+int os_arch_in_critical(void);
+os_error_t os_arch_os_init(void);
+void os_arch_os_stop(void);
+os_error_t os_arch_os_start(void);
+
+#endif /* _OS_ARCH_SIM_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/include/os/endian.h
----------------------------------------------------------------------
diff --git a/kernel/os/include/os/endian.h b/kernel/os/include/os/endian.h
new file mode 100644
index 0000000..ffb054d
--- /dev/null
+++ b/kernel/os/include/os/endian.h
@@ -0,0 +1,92 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 H_ENDIAN_
+#define H_ENDIAN_
+
+#include <inttypes.h>
+
+#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
+
+#ifndef ntohll
+#define ntohll(x)  ((uint64_t)(x))
+#endif
+
+#ifndef htonll
+#define htonll(x)  ((uint64_t)(x))
+#endif
+
+#ifndef ntohl
+#define ntohl(x)   ((uint32_t)(x))
+#endif
+
+#ifndef htonl
+#define htonl(x)   ((uint32_t)(x))
+#endif
+
+#ifndef ntohs
+#define ntohs(x)   ((uint16_t)(x))
+#endif
+
+#ifndef htons
+#define htons(x)   ((uint16_t)(x))
+#endif
+
+#else
+
+#ifndef ntohll
+#define ntohll(x)   ((uint64_t)                     \
+     ((((x) & 0xff00000000000000ull) >> 56) |       \
+      (((x) & 0x00ff000000000000ull) >> 40) |       \
+      (((x) & 0x0000ff0000000000ull) >> 24) |       \
+      (((x) & 0x000000ff00000000ull) >>  8) |       \
+      (((x) & 0x00000000ff000000ull) <<  8) |       \
+      (((x) & 0x0000000000ff0000ull) << 24) |       \
+      (((x) & 0x000000000000ff00ull) << 40) |       \
+      (((x) & 0x00000000000000ffull) << 56)))
+#endif
+
+#ifndef htonll
+#define htonll      ntohll
+#endif
+
+#ifndef ntohl
+#define ntohl(x)    ((uint32_t)                     \
+    ((((x) & 0xff000000) >> 24) |                   \
+     (((x) & 0x00ff0000) >>  8) |                   \
+     (((x) & 0x0000ff00) <<  8) |                   \
+     (((x) & 0x000000ff) << 24)))
+#endif
+
+#ifndef htonl
+#define htonl       ntohl
+#endif
+
+#ifndef htons
+#define htons(x)   ((uint16_t)                      \
+    ((((x) & 0xff00) >> 8) |                        \
+     (((x) & 0x00ff) << 8)))
+#endif
+
+#ifndef ntohs
+#define ntohs       htons
+#endif
+
+#endif
+#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/include/os/os.h
----------------------------------------------------------------------
diff --git a/kernel/os/include/os/os.h b/kernel/os/include/os/os.h
new file mode 100644
index 0000000..0f1879c
--- /dev/null
+++ b/kernel/os/include/os/os.h
@@ -0,0 +1,101 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 _OS_H
+#define _OS_H
+
+#include <stdlib.h>
+//#include <stdint.h>
+
+#ifndef min
+#define min(a, b) ((a)<(b)?(a):(b))
+#endif
+
+#ifndef max
+#define max(a, b) ((a)>(b)?(a):(b))
+#endif
+
+#define os_get_return_addr() (__builtin_return_address(0))
+
+#define OS_ALIGN(__n, __a) (                             \
+        (((__n) & ((__a) - 1)) == 0)                   ? \
+            (__n)                                      : \
+            ((__n) + ((__a) - ((__n) & ((__a) - 1))))    \
+        )
+
+
+/**
+ * Whether or not the operating system has been started.  Set to
+ * 1 right before first task is run.
+ */
+extern int g_os_started;
+
+int os_info_init(void);
+
+/**
+ * Returns 1 if the OS has been started, 0 if it has not yet been
+ * been started.
+ */
+int os_started(void);
+
+/* OS error enumerations */
+enum os_error {
+    OS_OK = 0,
+    OS_ENOMEM = 1,
+    OS_EINVAL = 2,
+    OS_INVALID_PARM = 3,
+    OS_MEM_NOT_ALIGNED = 4,
+    OS_BAD_MUTEX = 5,
+    OS_TIMEOUT = 6,
+    OS_ERR_IN_ISR = 7,      /* Function cannot be called from ISR */
+    OS_ERR_PRIV = 8,        /* Privileged access error */
+    OS_NOT_STARTED = 9,     /* Operating must be started to call this function, but isn't */
+    OS_ENOENT = 10,         /* No such thing */
+    OS_EBUSY = 11,          /* Resource busy */
+    OS_ERROR = 12,           /* Generic Error */
+};
+
+#define OS_WAIT_FOREVER (-1)
+
+typedef enum os_error os_error_t;
+
+#define OS_IDLE_PRIO (0xff)
+
+void os_init(void);
+void os_start(void);
+
+/* XXX: Not sure if this should go here; I want to differentiate API that
+ * should be called by application developers as those that should not. */
+void os_init_idle_task(void);
+
+#include "os/os_sanity.h"
+#include "os/os_arch.h"
+#include "os/os_time.h"
+#include "os/os_task.h"
+#include "os/os_sched.h"
+#include "os/os_eventq.h"
+#include "os/os_callout.h"
+#include "os/os_heap.h"
+#include "os/os_mutex.h"
+#include "os/os_sem.h"
+#include "os/os_mempool.h"
+#include "os/os_mbuf.h"
+#include "os/os_dev.h"
+
+#endif /* _OS_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/include/os/os_callout.h
----------------------------------------------------------------------
diff --git a/kernel/os/include/os/os_callout.h b/kernel/os/include/os/os_callout.h
new file mode 100644
index 0000000..baa377a
--- /dev/null
+++ b/kernel/os/include/os/os_callout.h
@@ -0,0 +1,60 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 _OS_CALLOUT_H
+#define _OS_CALLOUT_H
+
+#define OS_CALLOUT_F_QUEUED (0x01)
+
+struct os_callout {
+    struct os_event c_ev;
+    struct os_eventq *c_evq;
+    uint32_t c_ticks;
+    TAILQ_ENTRY(os_callout) c_next;
+};
+
+typedef void (*os_callout_func_t)(void *);
+
+struct os_callout_func {
+    /* Must be the first element in the structure for casting
+     * purposes.
+     */
+    struct os_callout cf_c;
+    os_callout_func_t cf_func;
+};
+#define CF_ARG(__cf) ((__cf)->cf_c.c_ev.ev_arg)
+
+void os_callout_func_init(struct os_callout_func *cf, struct os_eventq *evq,
+  os_callout_func_t timo_func, void *ev_arg);
+void os_callout_stop(struct os_callout *);
+int os_callout_reset(struct os_callout *, int32_t);
+void os_callout_tick(void);
+os_time_t os_callout_wakeup_ticks(os_time_t now);
+
+static inline int
+os_callout_queued(struct os_callout *c)
+{
+    return c->c_next.tqe_prev != NULL;
+}
+
+#endif /* _OS_CALLOUT_H */
+
+
+

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/include/os/os_cfg.h
----------------------------------------------------------------------
diff --git a/kernel/os/include/os/os_cfg.h b/kernel/os/include/os/os_cfg.h
new file mode 100644
index 0000000..40c1e91
--- /dev/null
+++ b/kernel/os/include/os/os_cfg.h
@@ -0,0 +1,25 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 _OS_CFG_H_
+#define _OS_CFG_H_ 
+
+
+#endif /* _OS_CFG_H_ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/include/os/os_dev.h
----------------------------------------------------------------------
diff --git a/kernel/os/include/os/os_dev.h b/kernel/os/include/os/os_dev.h
new file mode 100644
index 0000000..def42c0
--- /dev/null
+++ b/kernel/os/include/os/os_dev.h
@@ -0,0 +1,114 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 _OS_DEV_H
+#define _OS_DEV_H
+
+#include <os/os.h>
+
+#include "os/queue.h"
+
+struct os_dev;
+
+/*
+ * Initialization order, defines when a device should be initialized
+ * by the Mynewt kernel.
+ *
+ */
+#define OS_DEV_INIT_PRIMARY   (1)
+#define OS_DEV_INIT_SECONDARY (2)
+#define OS_DEV_INIT_KERNEL    (3)
+
+#define OS_DEV_INIT_F_CRITICAL (1 << 0)
+
+
+#define OS_DEV_INIT_PRIO_DEFAULT (0xff)
+
+/**
+ * Device status, so functions can ensure device is called in a
+ * consistent state.
+ */
+#define OS_DEV_F_STATUS_READY     (1 << 0)
+#define OS_DEV_F_STATUS_OPEN      (1 << 1)
+#define OS_DEV_F_STATUS_SUSPENDED (1 << 2)
+#define OS_DEV_F_INIT_CRITICAL    (1 << 3)
+
+typedef int (*os_dev_init_func_t)(struct os_dev *, void *);
+typedef int (*os_dev_open_func_t)(struct os_dev *, uint32_t,
+        void *);
+typedef int (*os_dev_suspend_func_t)(struct os_dev *, os_time_t, int);
+typedef int (*os_dev_resume_func_t)(struct os_dev *);
+typedef int (*os_dev_close_func_t)(struct os_dev *);
+
+struct os_dev_handlers {
+    os_dev_open_func_t od_open;
+    os_dev_suspend_func_t od_suspend;
+    os_dev_resume_func_t od_resume;
+    os_dev_close_func_t od_close;
+};
+
+/*
+ * Device structure.
+ */
+struct os_dev {
+    struct os_dev_handlers od_handlers;
+    os_dev_init_func_t od_init;
+    void *od_init_arg;
+    uint8_t od_stage;
+    uint8_t od_priority;
+    uint8_t od_open_ref;
+    uint8_t od_flags;
+    char *od_name;
+    STAILQ_ENTRY(os_dev) od_next;
+};
+
+#define OS_DEV_SETHANDLERS(__dev, __open, __close)          \
+    (__dev)->od_handlers.od_open = (__open);                \
+    (__dev)->od_handlers.od_close = (__close);
+
+static inline int
+os_dev_suspend(struct os_dev *dev, os_time_t suspend_t, uint8_t force)
+{
+    if (dev->od_handlers.od_suspend == NULL) {
+        return (0);
+    } else {
+        return (dev->od_handlers.od_suspend(dev, suspend_t, force));
+    }
+}
+
+static inline int
+os_dev_resume(struct os_dev *dev)
+{
+    if (dev->od_handlers.od_resume == NULL) {
+        return (0);
+    } else {
+        return (dev->od_handlers.od_resume(dev));
+    }
+}
+
+int os_dev_create(struct os_dev *dev, char *name, uint8_t stage,
+        uint8_t priority, os_dev_init_func_t od_init, void *arg);
+int os_dev_initialize_all(uint8_t stage);
+int os_dev_suspend_all(os_time_t, uint8_t);
+int os_dev_resume_all(void);
+struct os_dev *os_dev_open(char *devname, uint32_t timo, void *arg);
+int os_dev_close(struct os_dev *dev);
+void os_dev_reset(void);
+
+#endif /* _OS_DEV_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/include/os/os_eventq.h
----------------------------------------------------------------------
diff --git a/kernel/os/include/os/os_eventq.h b/kernel/os/include/os/os_eventq.h
new file mode 100644
index 0000000..b298f92
--- /dev/null
+++ b/kernel/os/include/os/os_eventq.h
@@ -0,0 +1,51 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 _OS_EVENTQ_H
+#define _OS_EVENTQ_H
+
+#include <inttypes.h>
+#include <os/os_time.h>
+
+struct os_event {
+    uint8_t ev_queued;
+    uint8_t ev_type;
+    void *ev_arg;
+    STAILQ_ENTRY(os_event) ev_next;
+};
+
+#define OS_EVENT_QUEUED(__ev) ((__ev)->ev_queued)
+
+#define OS_EVENT_T_TIMER (1)
+#define OS_EVENT_T_MQUEUE_DATA (2)
+#define OS_EVENT_T_PERUSER (16)
+
+struct os_eventq {
+    struct os_task *evq_task;
+    STAILQ_HEAD(, os_event) evq_list;
+};
+
+void os_eventq_init(struct os_eventq *);
+void os_eventq_put(struct os_eventq *, struct os_event *);
+struct os_event *os_eventq_get(struct os_eventq *);
+struct os_event *os_eventq_poll(struct os_eventq **, int, os_time_t);
+void os_eventq_remove(struct os_eventq *, struct os_event *);
+
+#endif /* _OS_EVENTQ_H */
+

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/include/os/os_heap.h
----------------------------------------------------------------------
diff --git a/kernel/os/include/os/os_heap.h b/kernel/os/include/os/os_heap.h
new file mode 100644
index 0000000..e526537
--- /dev/null
+++ b/kernel/os/include/os/os_heap.h
@@ -0,0 +1,30 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 H_OS_HEAP_
+#define H_OS_HEAP_
+
+#include <stddef.h>
+
+void *os_malloc(size_t size);
+void os_free(void *mem);
+void *os_realloc(void *ptr, size_t size);
+
+#endif
+

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/include/os/os_malloc.h
----------------------------------------------------------------------
diff --git a/kernel/os/include/os/os_malloc.h b/kernel/os/include/os/os_malloc.h
new file mode 100644
index 0000000..1823856
--- /dev/null
+++ b/kernel/os/include/os/os_malloc.h
@@ -0,0 +1,34 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 H_OS_MALLOC_
+#define H_OS_MALLOC_
+
+#include "os/os_heap.h"
+
+#undef  malloc
+#define malloc  os_malloc
+
+#undef  free
+#define free    os_free
+
+#undef  realloc
+#define realloc  os_realloc
+
+#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/include/os/os_mbuf.h
----------------------------------------------------------------------
diff --git a/kernel/os/include/os/os_mbuf.h b/kernel/os/include/os/os_mbuf.h
new file mode 100644
index 0000000..e0733fd
--- /dev/null
+++ b/kernel/os/include/os/os_mbuf.h
@@ -0,0 +1,297 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 _OS_MBUF_H 
+#define _OS_MBUF_H 
+
+#include "os/queue.h"
+#include "os/os_eventq.h"
+
+/**
+ * A mbuf pool from which to allocate mbufs. This contains a pointer to the os 
+ * mempool to allocate mbufs out of, the total number of elements in the pool, 
+ * and the amount of "user" data in a non-packet header mbuf. The total pool 
+ * size, in bytes, should be: 
+ *  os_mbuf_count * (omp_databuf_len + sizeof(struct os_mbuf))
+ */
+struct os_mbuf_pool {
+    /** 
+     * Total length of the databuf in each mbuf.  This is the size of the 
+     * mempool block, minus the mbuf header
+     */
+    uint16_t omp_databuf_len;
+    /**
+     * Total number of memblock's allocated in this mempool.
+     */
+    uint16_t omp_mbuf_count;
+    /**
+     * The memory pool which to allocate mbufs out of 
+     */
+    struct os_mempool *omp_pool;
+
+    /**
+     * Link to the next mbuf pool for system memory pools.
+     */
+    STAILQ_ENTRY(os_mbuf_pool) omp_next;
+};
+
+
+/**
+ * A packet header structure that preceeds the mbuf packet headers.
+ */
+struct os_mbuf_pkthdr {
+    /**
+     * Overall length of the packet. 
+     */
+    uint16_t omp_len;
+    /**
+     * Flags
+     */
+    uint16_t omp_flags;
+    /**
+     * Next packet in the mbuf chain.
+     */
+    STAILQ_ENTRY(os_mbuf_pkthdr) omp_next;
+};
+
+/**
+ * Chained memory buffer.
+ */
+struct os_mbuf {
+    /**
+     * Current pointer to data in the structure
+     */
+    uint8_t *om_data;
+    /**
+     * Flags associated with this buffer, see OS_MBUF_F_* defintions
+     */
+    uint8_t om_flags;
+    /**
+     * Length of packet header
+     */
+    uint8_t om_pkthdr_len;
+    /**
+     * Length of data in this buffer 
+     */
+    uint16_t om_len;
+
+    /**
+     * The mbuf pool this mbuf was allocated out of 
+     */
+    struct os_mbuf_pool *om_omp;
+
+    /**
+     * Pointer to next entry in the chained memory buffer
+     */
+    SLIST_ENTRY(os_mbuf) om_next;
+
+    /**
+     * Pointer to the beginning of the data, after this buffer
+     */
+    uint8_t om_databuf[0];
+};
+
+struct os_mqueue {
+    STAILQ_HEAD(, os_mbuf_pkthdr) mq_head;
+    struct os_event mq_ev;
+};
+
+/*
+ * Given a flag number, provide the mask for it
+ *
+ * @param __n The number of the flag in the mask 
+ */
+#define OS_MBUF_F_MASK(__n) (1 << (__n))
+
+/* 
+ * Checks whether a given mbuf is a packet header mbuf 
+ *
+ * @param __om The mbuf to check 
+ */
+#define OS_MBUF_IS_PKTHDR(__om) \
+    ((__om)->om_pkthdr_len >= sizeof (struct os_mbuf_pkthdr))
+
+/* Get a packet header pointer given an mbuf pointer */
+#define OS_MBUF_PKTHDR(__om) ((struct os_mbuf_pkthdr *)     \
+    ((uint8_t *)&(__om)->om_data + sizeof(struct os_mbuf)))
+
+/* Given a mbuf packet header pointer, return a pointer to the mbuf */
+#define OS_MBUF_PKTHDR_TO_MBUF(__hdr)   \
+     (struct os_mbuf *)((uint8_t *)(__hdr) - sizeof(struct os_mbuf))
+
+/**
+ * Gets the length of an entire mbuf chain.  The specified mbuf must have a
+ * packet header.
+ */
+#define OS_MBUF_PKTLEN(__om) (OS_MBUF_PKTHDR(__om)->omp_len)
+
+/*
+ * Access the data of a mbuf, and cast it to type
+ *
+ * @param __om The mbuf to access, and cast 
+ * @param __type The type to cast it to 
+ */
+#define OS_MBUF_DATA(__om, __type) \
+     (__type) ((__om)->om_data)
+
+/**
+ * Access the "user header" in the head of an mbuf chain.
+ *
+ * @param om                    Pointer to the head of an mbuf chain.
+ */
+#define OS_MBUF_USRHDR(om)                              \
+    (void *)((uint8_t *)om + sizeof (struct os_mbuf) +  \
+             sizeof (struct os_mbuf_pkthdr))
+
+/**
+ * Retrieves the length of the user header in an mbuf.
+ *
+ * @param om                    Pointer to the mbuf to query.
+ */
+#define OS_MBUF_USRHDR_LEN(om) \
+    ((om)->om_pkthdr_len - sizeof (struct os_mbuf_pkthdr))
+
+/*
+ * Called by OS_MBUF_LEADINGSPACE() macro
+ */
+static inline uint16_t 
+_os_mbuf_leadingspace(struct os_mbuf *om)
+{
+    uint16_t startoff;
+    uint16_t leadingspace;
+
+    startoff = 0;
+    if (OS_MBUF_IS_PKTHDR(om)) {
+        startoff = om->om_pkthdr_len;
+    }
+
+    leadingspace = (uint16_t) (OS_MBUF_DATA(om, uint8_t *) - 
+        ((uint8_t *) &om->om_databuf[0] + startoff));
+
+    return (leadingspace);
+}
+
+/**
+ * Returns the leading space (space at the beginning) of the mbuf. 
+ * Works on both packet header, and regular mbufs, as it accounts 
+ * for the additional space allocated to the packet header.
+ * 
+ * @param __omp Is the mbuf pool (which contains packet header length.)
+ * @param __om  Is the mbuf in that pool to get the leadingspace for 
+ *
+ * @return Amount of leading space available in the mbuf 
+ */
+#define OS_MBUF_LEADINGSPACE(__om) _os_mbuf_leadingspace(__om)
+
+/* Called by OS_MBUF_TRAILINGSPACE() macro. */
+static inline uint16_t 
+_os_mbuf_trailingspace(struct os_mbuf *om)
+{
+    struct os_mbuf_pool *omp;
+
+    omp = om->om_omp;
+
+    return (&om->om_databuf[0] + omp->omp_databuf_len) -
+      (om->om_data + om->om_len);
+}
+
+/**
+ * Returns the trailing space (space at the end) of the mbuf.
+ * Works on both packet header and regular mbufs.
+ *
+ * @param __omp The mbuf pool for this mbuf 
+ * @param __om  Is the mbuf in that pool to get trailing space for 
+ *
+ * @return The amount of trailing space available in the mbuf 
+ */
+#define OS_MBUF_TRAILINGSPACE(__om) _os_mbuf_trailingspace(__om)
+
+/* Mbuf queue functions */
+
+/* Initialize a mbuf queue */
+int os_mqueue_init(struct os_mqueue *, void *arg);
+
+/* Get an element from a mbuf queue */
+struct os_mbuf *os_mqueue_get(struct os_mqueue *);
+
+/* Put an element in a mbuf queue */
+int os_mqueue_put(struct os_mqueue *, struct os_eventq *, struct os_mbuf *);
+
+/* Register an mbuf pool with the system pool registry */
+int os_msys_register(struct os_mbuf_pool *);
+
+/* Return a mbuf from the system pool, given an indicative mbuf size */
+struct os_mbuf *os_msys_get(uint16_t dsize, uint16_t leadingspace);
+
+/* De-registers all mbuf pools from msys. */
+void os_msys_reset(void);
+
+/* Return a packet header mbuf from the system pool */
+struct os_mbuf *os_msys_get_pkthdr(uint16_t dsize, uint16_t user_hdr_len);
+
+int os_msys_count(void);
+int os_msys_num_free(void);
+
+/* Initialize a mbuf pool */
+int os_mbuf_pool_init(struct os_mbuf_pool *, struct os_mempool *mp, 
+        uint16_t, uint16_t);
+
+/* Allocate a new mbuf out of the os_mbuf_pool */ 
+struct os_mbuf *os_mbuf_get(struct os_mbuf_pool *omp, uint16_t);
+
+/* Allocate a new packet header mbuf out of the os_mbuf_pool */ 
+struct os_mbuf *os_mbuf_get_pkthdr(struct os_mbuf_pool *omp, 
+        uint8_t pkthdr_len);
+
+/* Duplicate a mbuf from the pool */
+struct os_mbuf *os_mbuf_dup(struct os_mbuf *m);
+
+struct os_mbuf *os_mbuf_off(const struct os_mbuf *om, int off,
+                            uint16_t *out_off);
+
+/* Copy data from an mbuf to a flat buffer. */
+int os_mbuf_copydata(const struct os_mbuf *m, int off, int len, void *dst);
+
+/* Append data onto a mbuf */
+int os_mbuf_append(struct os_mbuf *m, const void *, uint16_t);
+
+int os_mbuf_appendfrom(struct os_mbuf *dst, const struct os_mbuf *src,
+                       uint16_t src_off, uint16_t len);
+
+/* Free a mbuf */
+int os_mbuf_free(struct os_mbuf *mb);
+
+/* Free a mbuf chain */
+int os_mbuf_free_chain(struct os_mbuf *om);
+
+void os_mbuf_adj(struct os_mbuf *mp, int req_len);
+int os_mbuf_cmpf(const struct os_mbuf *om, int off, const void *data,
+                   int len);
+int os_mbuf_cmpm(const struct os_mbuf *om1, uint16_t offset1,
+                 const struct os_mbuf *om2, uint16_t offset2,
+                 uint16_t len);
+
+struct os_mbuf *os_mbuf_prepend(struct os_mbuf *om, int len);
+struct os_mbuf *os_mbuf_prepend_pullup(struct os_mbuf *om, uint16_t len);
+int os_mbuf_copyinto(struct os_mbuf *om, int off, const void *src, int len);
+void os_mbuf_concat(struct os_mbuf *first, struct os_mbuf *second);
+void *os_mbuf_extend(struct os_mbuf *om, uint16_t len);
+struct os_mbuf *os_mbuf_pullup(struct os_mbuf *om, uint16_t len);
+
+#endif /* _OS_MBUF_H */ 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/include/os/os_mempool.h
----------------------------------------------------------------------
diff --git a/kernel/os/include/os/os_mempool.h b/kernel/os/include/os/os_mempool.h
new file mode 100644
index 0000000..a731618
--- /dev/null
+++ b/kernel/os/include/os/os_mempool.h
@@ -0,0 +1,94 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 _OS_MEMPOOL_H_
+#define _OS_MEMPOOL_H_
+
+#include "os/os.h"
+#include "os/queue.h"
+
+/* 
+ * A memory block structure. This simply contains a pointer to the free list 
+ * chain and is only used when the block is on the free list. When the block 
+ * has been removed from the free list the entire memory block is usable by the 
+ * caller. 
+ */
+struct os_memblock {
+    SLIST_ENTRY(os_memblock) mb_next;
+};
+
+/* XXX: Change this structure so that we keep the first address in the pool? */
+/* XXX: add memory debug structure and associated code */
+/* XXX: Change how I coded the SLIST_HEAD here. It should be named:
+   SLIST_HEAD(,os_memblock) mp_head; */
+
+/* Memory pool */
+struct os_mempool {
+    int mp_block_size;          /* Size of the memory blocks, in bytes. */
+    int mp_num_blocks;          /* The number of memory blocks. */
+    int mp_num_free;            /* The number of free blocks left */
+    uint32_t mp_membuf_addr;    /* Address of memory buffer used by pool */
+    STAILQ_ENTRY(os_mempool) mp_list;
+    SLIST_HEAD(,os_memblock);   /* Pointer to list of free blocks */
+    char *name;                 /* Name for memory block */
+};
+
+#define OS_MEMPOOL_INFO_NAME_LEN (32)
+
+struct os_mempool_info {
+    int omi_block_size;
+    int omi_num_blocks;
+    int omi_num_free;
+    char omi_name[OS_MEMPOOL_INFO_NAME_LEN];
+};
+
+struct os_mempool *os_mempool_info_get_next(struct os_mempool *, 
+        struct os_mempool_info *);
+
+/* 
+ * To calculate size of the memory buffer needed for the pool. NOTE: This size 
+ * is NOT in bytes! The size is the number of os_membuf_t elements required for 
+ * the memory pool.
+ */
+#if (OS_CFG_ALIGNMENT == OS_CFG_ALIGN_4)
+#define OS_MEMPOOL_SIZE(n,blksize)      ((((blksize) + 3) / 4) * (n))
+typedef uint32_t os_membuf_t;
+#else
+#define OS_MEMPOOL_SIZE(n,blksize)      ((((blksize) + 7) / 8) * (n)) 
+typedef uint64_t os_membuf_t;
+#endif
+
+/** Calculates the number of bytes required to initialize a memory pool. */
+#define OS_MEMPOOL_BYTES(n,blksize)     \
+    (sizeof (os_membuf_t) * OS_MEMPOOL_SIZE((n), (blksize)))
+
+/* Initialize a memory pool */
+os_error_t os_mempool_init(struct os_mempool *mp, int blocks, int block_size, 
+                           void *membuf, char *name);
+
+/* Checks if a memory block was allocated from the specified mempool. */
+int os_memblock_from(struct os_mempool *mp, void *block_addr);
+
+/* Get a memory block from the pool */
+void *os_memblock_get(struct os_mempool *mp);
+
+/* Put the memory block back into the pool */
+os_error_t os_memblock_put(struct os_mempool *mp, void *block_addr);
+
+#endif  /* _OS_MEMPOOL_H_ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/include/os/os_mutex.h
----------------------------------------------------------------------
diff --git a/kernel/os/include/os/os_mutex.h b/kernel/os/include/os/os_mutex.h
new file mode 100644
index 0000000..46c15f2
--- /dev/null
+++ b/kernel/os/include/os/os_mutex.h
@@ -0,0 +1,59 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 _OS_MUTEX_H_
+#define _OS_MUTEX_H_
+
+#include "os/os.h"
+#include "os/queue.h"
+
+struct os_mutex
+{
+    SLIST_HEAD(, os_task) mu_head;  /* chain of waiting tasks */
+    uint8_t     _pad;
+    uint8_t     mu_prio;            /* owner's default priority*/
+    uint16_t    mu_level;           /* call nesting level */
+    struct os_task *mu_owner;       /* owners task */
+};
+
+/* 
+  XXX: NOTES
+    -> Should we add a magic number or flag to the mutex structure so
+    that we know that this is a mutex? We can use it for double checking
+    that a proper mutex was passed in to the API.
+    -> What debug information should we add to this structure? Who last
+    acquired the mutex? File/line where it was released?
+    -> Should we add a name to the mutex?
+    -> Should we add a "os_mutex_inspect() api?
+*/
+
+/* XXX: api to create
+os_mutex_inspect(); 
+*/ 
+
+/* Initialize a mutex */
+os_error_t os_mutex_init(struct os_mutex *mu);
+
+/* Release a mutex */
+os_error_t os_mutex_release(struct os_mutex *mu);
+
+/* Pend (wait) for a mutex */
+os_error_t os_mutex_pend(struct os_mutex *mu, uint32_t timeout);
+
+#endif  /* _OS_MUTEX_H_ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/include/os/os_sanity.h
----------------------------------------------------------------------
diff --git a/kernel/os/include/os/os_sanity.h b/kernel/os/include/os/os_sanity.h
new file mode 100644
index 0000000..fb93570
--- /dev/null
+++ b/kernel/os/include/os/os_sanity.h
@@ -0,0 +1,56 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 _OS_SANITY_H
+#define _OS_SANITY_H
+
+#include <stdint.h>
+
+#include "os/os_time.h"
+#include "os/queue.h"
+
+struct os_sanity_check;
+typedef int (*os_sanity_check_func_t)(struct os_sanity_check *, void *);
+
+struct os_sanity_check {
+    os_time_t sc_checkin_last;
+    os_time_t sc_checkin_itvl;
+    os_sanity_check_func_t sc_func;
+    void *sc_arg;
+
+    SLIST_ENTRY(os_sanity_check) sc_next;
+
+};
+
+#define OS_SANITY_CHECK_SETFUNC(__sc, __f, __arg, __itvl)  \
+    (__sc)->sc_func = (__f);                               \
+    (__sc)->sc_arg = (__arg);                              \
+    (__sc)->sc_checkin_itvl = (__itvl) * OS_TICKS_PER_SEC;
+
+int os_sanity_init(void);
+void os_sanity_run(void);
+
+struct os_task;
+int os_sanity_task_checkin(struct os_task *);
+
+int os_sanity_check_init(struct os_sanity_check *);
+int os_sanity_check_register(struct os_sanity_check *);
+int os_sanity_check_reset(struct os_sanity_check *);
+
+#endif /* _OS_SANITY_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/include/os/os_sched.h
----------------------------------------------------------------------
diff --git a/kernel/os/include/os/os_sched.h b/kernel/os/include/os/os_sched.h
new file mode 100644
index 0000000..ac45683
--- /dev/null
+++ b/kernel/os/include/os/os_sched.h
@@ -0,0 +1,37 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 _OS_SCHED_H
+#define _OS_SCHED_H
+
+#include "os/os_task.h"
+
+void os_sched_ctx_sw_hook(struct os_task *);
+struct os_task *os_sched_get_current_task(void);
+void os_sched_set_current_task(struct os_task *);
+struct os_task *os_sched_next_task(void);
+void os_sched(struct os_task *);
+void os_sched_os_timer_exp(void);
+os_error_t os_sched_insert(struct os_task *);
+int os_sched_sleep(struct os_task *, os_time_t nticks);
+int os_sched_wakeup(struct os_task *);
+void os_sched_resort(struct os_task *);
+os_time_t os_sched_wakeup_ticks(os_time_t now);
+
+#endif /* _OS_SCHED_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/include/os/os_sem.h
----------------------------------------------------------------------
diff --git a/kernel/os/include/os/os_sem.h b/kernel/os/include/os/os_sem.h
new file mode 100644
index 0000000..0d44f91
--- /dev/null
+++ b/kernel/os/include/os/os_sem.h
@@ -0,0 +1,52 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 _OS_SEM_H_
+#define _OS_SEM_H_
+
+#include "os/queue.h"
+
+struct os_sem
+{
+    SLIST_HEAD(, os_task) sem_head;     /* chain of waiting tasks */
+    uint16_t    _pad;
+    uint16_t    sem_tokens;             /* # of tokens */
+};
+
+/* 
+  XXX: NOTES
+    -> Should we add a magic number or flag to the semaphore structure so
+    that we know that this is a semaphore? We can use it for double checking
+    that a proper semaphore was passed in to the API.
+    -> What debug information should we add to this structure? Who last
+    acquired the semaphore? File/line where it was released?
+    -> Should we add a name to the semaphore?
+    -> Should we add a "os_sem_inspect() api, like ucos?
+*/ 
+
+/* Create a semaphore */
+os_error_t os_sem_init(struct os_sem *sem, uint16_t tokens);
+
+/* Release a semaphore */
+os_error_t os_sem_release(struct os_sem *sem);
+
+/* Pend (wait) for a semaphore */
+os_error_t os_sem_pend(struct os_sem *sem, uint32_t timeout);
+
+#endif  /* _OS_MUTEX_H_ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/include/os/os_task.h
----------------------------------------------------------------------
diff --git a/kernel/os/include/os/os_task.h b/kernel/os/include/os/os_task.h
new file mode 100644
index 0000000..561583b
--- /dev/null
+++ b/kernel/os/include/os/os_task.h
@@ -0,0 +1,114 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 _OS_TASK_H
+#define _OS_TASK_H
+
+#include "os/os.h"
+#include "os/os_sanity.h" 
+#include "os/queue.h"
+
+/* The highest and lowest task priorities */
+#define OS_TASK_PRI_HIGHEST (0)
+#define OS_TASK_PRI_LOWEST  (0xff)
+
+/* 
+ * Generic "object" structure. All objects that a task can wait on must
+ * have a SLIST_HEAD(, os_task) head_name as the first element in the object 
+ * structure. The element 'head_name' can be any name. See os_mutex.h or
+ * os_sem.h for an example.
+ */
+struct os_task_obj
+{
+    SLIST_HEAD(, os_task) obj_head;     /* chain of waiting tasks */
+};
+
+/* Task states */
+typedef enum os_task_state {
+    OS_TASK_READY = 1, 
+    OS_TASK_SLEEP = 2
+} os_task_state_t;
+
+/* Task flags */
+#define OS_TASK_FLAG_NO_TIMEOUT     (0x01U)
+#define OS_TASK_FLAG_SEM_WAIT       (0x02U)
+#define OS_TASK_FLAG_MUTEX_WAIT     (0x04U)
+
+typedef void (*os_task_func_t)(void *);
+
+#define OS_TASK_MAX_NAME_LEN (32)
+
+struct os_task {
+    os_stack_t *t_stackptr;
+    os_stack_t *t_stacktop;
+
+    uint16_t t_stacksize;
+    uint16_t t_pad;
+
+    uint8_t t_taskid;
+    uint8_t t_prio;
+    uint8_t t_state;
+    uint8_t t_flags;
+
+    const char *t_name;
+    os_task_func_t t_func;
+    void *t_arg;
+
+    void *t_obj;
+
+    struct os_sanity_check t_sanity_check;
+
+    os_time_t t_next_wakeup;
+    os_time_t t_run_time;
+    uint32_t t_ctx_sw_cnt;
+
+    /* Global list of all tasks, irrespective of run or sleep lists */
+    STAILQ_ENTRY(os_task) t_os_task_list;
+
+    /* Used to chain task to either the run or sleep list */
+    TAILQ_ENTRY(os_task) t_os_list;
+
+    /* Used to chain task to an object such as a semaphore or mutex */
+    SLIST_ENTRY(os_task) t_obj_list;
+};
+
+int os_task_init(struct os_task *, const char *, os_task_func_t, void *,
+        uint8_t, os_time_t, os_stack_t *, uint16_t);
+
+uint8_t os_task_count(void);
+
+struct os_task_info {
+    uint8_t oti_prio;
+    uint8_t oti_taskid;
+    uint8_t oti_state;
+    uint8_t oti_flags;
+    uint16_t oti_stkusage;
+    uint16_t oti_stksize;
+    uint32_t oti_cswcnt;
+    uint32_t oti_runtime;
+    os_time_t oti_last_checkin;
+    os_time_t oti_next_checkin;
+
+    char oti_name[OS_TASK_MAX_NAME_LEN];
+};
+struct os_task *os_task_info_get_next(const struct os_task *,
+        struct os_task_info *);
+
+
+#endif /* _OS_TASK_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/include/os/os_test.h
----------------------------------------------------------------------
diff --git a/kernel/os/include/os/os_test.h b/kernel/os/include/os/os_test.h
new file mode 100644
index 0000000..6701315
--- /dev/null
+++ b/kernel/os/include/os/os_test.h
@@ -0,0 +1,25 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 H_OS_TEST_
+#define H_OS_TEST_
+
+int os_test_all(void);
+
+#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/include/os/os_time.h
----------------------------------------------------------------------
diff --git a/kernel/os/include/os/os_time.h b/kernel/os/include/os/os_time.h
new file mode 100644
index 0000000..38b6bd9
--- /dev/null
+++ b/kernel/os/include/os/os_time.h
@@ -0,0 +1,111 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.
+ */
+
+/*-
+ * Copyright (c) 1982, 1986, 1993
+ *      The Regents of the University of California.  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.
+ * 4. Neither the name of the University 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 REGENTS 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 REGENTS 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.
+ *
+ *      @(#)time.h      8.5 (Berkeley) 5/4/95
+ * $FreeBSD$
+ */
+
+#ifndef _OS_TIME_H
+#define _OS_TIME_H
+
+#include <stdbool.h>
+#include <stdint.h>
+
+#ifndef UINT32_MAX
+#define UINT32_MAX  0xFFFFFFFFU
+#endif
+
+typedef uint32_t os_time_t;
+#define OS_TIME_MAX UINT32_MAX
+ 
+/* Used to wait forever for events and mutexs */
+#define OS_TIMEOUT_NEVER    (UINT32_MAX)
+
+os_time_t os_time_get(void);
+void os_time_advance(int ticks);
+void os_time_delay(int32_t osticks);
+
+#define OS_TIME_TICK_LT(__t1, __t2) ((int32_t) ((__t1) - (__t2)) < 0)
+#define OS_TIME_TICK_GT(__t1, __t2) ((int32_t) ((__t1) - (__t2)) > 0)
+#define OS_TIME_TICK_GEQ(__t1, __t2) ((int32_t) ((__t1) - (__t2)) >= 0)
+
+struct os_timeval {
+    int64_t tv_sec;         /* seconds since Jan 1 1970 */
+    int32_t tv_usec;        /* microseconds within the second */
+};
+
+struct os_timezone {
+    int16_t tz_minuteswest;     /* with respect to GMT */
+    int16_t tz_dsttime;         /* daylight savings time correction (if any) */
+};
+
+#define os_timeradd(tvp, uvp, vvp)                                      \
+        do {                                                            \
+                (vvp)->tv_sec = (tvp)->tv_sec + (uvp)->tv_sec;          \
+                (vvp)->tv_usec = (tvp)->tv_usec + (uvp)->tv_usec;       \
+                if ((vvp)->tv_usec >= 1000000) {                        \
+                        (vvp)->tv_sec++;                                \
+                        (vvp)->tv_usec -= 1000000;                      \
+                }                                                       \
+        } while (0)
+
+#define os_timersub(tvp, uvp, vvp)                                      \
+        do {                                                            \
+                (vvp)->tv_sec = (tvp)->tv_sec - (uvp)->tv_sec;          \
+                (vvp)->tv_usec = (tvp)->tv_usec - (uvp)->tv_usec;       \
+                if ((vvp)->tv_usec < 0) {                               \
+                        (vvp)->tv_sec--;                                \
+                        (vvp)->tv_usec += 1000000;                      \
+                }                                                       \
+        } while (0)
+
+int os_settimeofday(struct os_timeval *utctime, struct os_timezone *tz);
+int os_gettimeofday(struct os_timeval *utctime, struct os_timezone *tz);
+int64_t os_get_uptime_usec(void);
+int os_time_ms_to_ticks(uint32_t ms, uint32_t *out_ticks);
+
+#endif /* _OS_TIME_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/include/os/queue.h
----------------------------------------------------------------------
diff --git a/kernel/os/include/os/queue.h b/kernel/os/include/os/queue.h
new file mode 100755
index 0000000..01739af
--- /dev/null
+++ b/kernel/os/include/os/queue.h
@@ -0,0 +1,514 @@
+/*
+ * Copyright (c) 1991, 1993
+ *	The Regents of the University of California.  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.
+ * 4. Neither the name of the University 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 REGENTS 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 REGENTS 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.
+ *
+ *	@(#)queue.h	8.5 (Berkeley) 8/20/94
+ * $FreeBSD: src/sys/sys/queue.h,v 1.32.2.7 2002/04/17 14:21:02 des Exp $
+ */
+
+#ifndef _QUEUE_H_
+#define	_QUEUE_H_
+
+/*
+ * This file defines five types of data structures: singly-linked lists,
+ * singly-linked tail queues, lists, tail queues, and circular queues.
+ *
+ * A singly-linked list is headed by a single forward pointer. The elements
+ * are singly linked for minimum space and pointer manipulation overhead at
+ * the expense of O(n) removal for arbitrary elements. New elements can be
+ * added to the list after an existing element or at the head of the list.
+ * Elements being removed from the head of the list should use the explicit
+ * macro for this purpose for optimum efficiency. A singly-linked list may
+ * only be traversed in the forward direction.  Singly-linked lists are ideal
+ * for applications with large datasets and few or no removals or for
+ * implementing a LIFO queue.
+ *
+ * A singly-linked tail queue is headed by a pair of pointers, one to the
+ * head of the list and the other to the tail of the list. The elements are
+ * singly linked for minimum space and pointer manipulation overhead at the
+ * expense of O(n) removal for arbitrary elements. New elements can be added
+ * to the list after an existing element, at the head of the list, or at the
+ * end of the list. Elements being removed from the head of the tail queue
+ * should use the explicit macro for this purpose for optimum efficiency.
+ * A singly-linked tail queue may only be traversed in the forward direction.
+ * Singly-linked tail queues are ideal for applications with large datasets
+ * and few or no removals or for implementing a FIFO queue.
+ *
+ * A list is headed by a single forward pointer (or an array of forward
+ * pointers for a hash table header). The elements are doubly linked
+ * so that an arbitrary element can be removed without a need to
+ * traverse the list. New elements can be added to the list before
+ * or after an existing element or at the head of the list. A list
+ * may only be traversed in the forward direction.
+ *
+ * A tail queue is headed by a pair of pointers, one to the head of the
+ * list and the other to the tail of the list. The elements are doubly
+ * linked so that an arbitrary element can be removed without a need to
+ * traverse the list. New elements can be added to the list before or
+ * after an existing element, at the head of the list, or at the end of
+ * the list. A tail queue may be traversed in either direction.
+ *
+ * A circle queue is headed by a pair of pointers, one to the head of the
+ * list and the other to the tail of the list. The elements are doubly
+ * linked so that an arbitrary element can be removed without a need to
+ * traverse the list. New elements can be added to the list before or after
+ * an existing element, at the head of the list, or at the end of the list.
+ * A circle queue may be traversed in either direction, but has a more
+ * complex end of list detection.
+ *
+ * For details on the use of these macros, see the queue(3) manual page.
+ *
+ *
+ *                      SLIST   LIST    STAILQ  TAILQ   CIRCLEQ
+ * _HEAD                +       +       +       +       +
+ * _HEAD_INITIALIZER    +       +       +       +       +
+ * _ENTRY               +       +       +       +       +
+ * _INIT                +       +       +       +       +
+ * _EMPTY               +       +       +       +       +
+ * _FIRST               +       +       +       +       +
+ * _NEXT                +       +       +       +       +
+ * _PREV                -       -       -       +       +
+ * _LAST                -       -       +       +       +
+ * _FOREACH             +       +       +       +       +
+ * _FOREACH_REVERSE     -       -       -       +       +
+ * _INSERT_HEAD         +       +       +       +       +
+ * _INSERT_BEFORE       -       +       -       +       +
+ * _INSERT_AFTER        +       +       +       +       +
+ * _INSERT_TAIL         -       -       +       +       +
+ * _REMOVE_HEAD         +       -       +       -       -
+ * _REMOVE              +       +       +       +       +
+ *
+ */
+
+/*
+ * Singly-linked List declarations.
+ */
+#define	SLIST_HEAD(name, type)                          \
+struct name {                                           \
+    struct type *slh_first;	/* first element */         \
+}
+
+#define	SLIST_HEAD_INITIALIZER(head)                    \
+    { NULL }
+ 
+#define	SLIST_ENTRY(type)                               \
+struct {                                                \
+    struct type *sle_next;  /* next element */          \
+}
+ 
+/*
+ * Singly-linked List functions.
+ */
+#define SLIST_EMPTY(head)   ((head)->slh_first == NULL)
+
+#define SLIST_FIRST(head)   ((head)->slh_first)
+
+#define SLIST_FOREACH(var, head, field)                 \
+    for ((var) = SLIST_FIRST((head));                   \
+        (var);                                          \
+        (var) = SLIST_NEXT((var), field))
+
+#define SLIST_INIT(head) do {                           \
+        SLIST_FIRST((head)) = NULL;                     \
+} while (0)
+
+#define SLIST_INSERT_AFTER(slistelm, elm, field) do {           \
+    SLIST_NEXT((elm), field) = SLIST_NEXT((slistelm), field);   \
+    SLIST_NEXT((slistelm), field) = (elm);                      \
+} while (0)
+
+#define SLIST_INSERT_HEAD(head, elm, field) do {            \
+    SLIST_NEXT((elm), field) = SLIST_FIRST((head));         \
+    SLIST_FIRST((head)) = (elm);                            \
+} while (0)
+
+#define SLIST_NEXT(elm, field)	((elm)->field.sle_next)
+
+#define SLIST_REMOVE(head, elm, type, field) do {           \
+    if (SLIST_FIRST((head)) == (elm)) {                     \
+        SLIST_REMOVE_HEAD((head), field);                   \
+    }                                                       \
+    else {                                                  \
+        struct type *curelm = SLIST_FIRST((head));          \
+        while (SLIST_NEXT(curelm, field) != (elm))          \
+            curelm = SLIST_NEXT(curelm, field);             \
+        SLIST_NEXT(curelm, field) =                         \
+            SLIST_NEXT(SLIST_NEXT(curelm, field), field);   \
+    }                                                       \
+} while (0)
+
+#define SLIST_REMOVE_HEAD(head, field) do {                         \
+    SLIST_FIRST((head)) = SLIST_NEXT(SLIST_FIRST((head)), field);   \
+} while (0)
+
+/*
+ * Singly-linked Tail queue declarations.
+ */
+#define	STAILQ_HEAD(name, type)						\
+struct name {								\
+	struct type *stqh_first;/* first element */			\
+	struct type **stqh_last;/* addr of last next element */		\
+}
+
+#define	STAILQ_HEAD_INITIALIZER(head)					\
+	{ NULL, &(head).stqh_first }
+
+#define	STAILQ_ENTRY(type)						\
+struct {								\
+	struct type *stqe_next;	/* next element */			\
+}
+
+/*
+ * Singly-linked Tail queue functions.
+ */
+#define	STAILQ_EMPTY(head)	((head)->stqh_first == NULL)
+
+#define	STAILQ_FIRST(head)	((head)->stqh_first)
+
+#define	STAILQ_FOREACH(var, head, field)				\
+	for((var) = STAILQ_FIRST((head));				\
+	   (var);							\
+	   (var) = STAILQ_NEXT((var), field))
+
+#define	STAILQ_INIT(head) do {						\
+	STAILQ_FIRST((head)) = NULL;					\
+	(head)->stqh_last = &STAILQ_FIRST((head));			\
+} while (0)
+
+#define	STAILQ_INSERT_AFTER(head, tqelm, elm, field) do {		\
+	if ((STAILQ_NEXT((elm), field) = STAILQ_NEXT((tqelm), field)) == NULL)\
+		(head)->stqh_last = &STAILQ_NEXT((elm), field);		\
+	STAILQ_NEXT((tqelm), field) = (elm);				\
+} while (0)
+
+#define	STAILQ_INSERT_HEAD(head, elm, field) do {			\
+	if ((STAILQ_NEXT((elm), field) = STAILQ_FIRST((head))) == NULL)	\
+		(head)->stqh_last = &STAILQ_NEXT((elm), field);		\
+	STAILQ_FIRST((head)) = (elm);					\
+} while (0)
+
+#define	STAILQ_INSERT_TAIL(head, elm, field) do {			\
+	STAILQ_NEXT((elm), field) = NULL;				\
+	*(head)->stqh_last = (elm);					\
+	(head)->stqh_last = &STAILQ_NEXT((elm), field);			\
+} while (0)
+
+#define	STAILQ_LAST(head, type, field)					\
+	(STAILQ_EMPTY(head) ?						\
+		NULL :							\
+	        ((struct type *)					\
+		((char *)((head)->stqh_last) - offsetof(struct type, field))))
+
+#define	STAILQ_NEXT(elm, field)	((elm)->field.stqe_next)
+
+#define	STAILQ_REMOVE(head, elm, type, field) do {			\
+	if (STAILQ_FIRST((head)) == (elm)) {				\
+		STAILQ_REMOVE_HEAD(head, field);			\
+	}								\
+	else {								\
+		struct type *curelm = STAILQ_FIRST((head));		\
+		while (STAILQ_NEXT(curelm, field) != (elm))		\
+			curelm = STAILQ_NEXT(curelm, field);		\
+		if ((STAILQ_NEXT(curelm, field) =			\
+		     STAILQ_NEXT(STAILQ_NEXT(curelm, field), field)) == NULL)\
+			(head)->stqh_last = &STAILQ_NEXT((curelm), field);\
+	}								\
+} while (0)
+
+#define	STAILQ_REMOVE_HEAD(head, field) do {				\
+	if ((STAILQ_FIRST((head)) =					\
+	     STAILQ_NEXT(STAILQ_FIRST((head)), field)) == NULL)		\
+		(head)->stqh_last = &STAILQ_FIRST((head));		\
+} while (0)
+
+#define	STAILQ_REMOVE_HEAD_UNTIL(head, elm, field) do {			\
+	if ((STAILQ_FIRST((head)) = STAILQ_NEXT((elm), field)) == NULL)	\
+		(head)->stqh_last = &STAILQ_FIRST((head));		\
+} while (0)
+
+#define STAILQ_REMOVE_AFTER(head, elm, field) do {			\
+	if ((STAILQ_NEXT(elm, field) =					\
+	     STAILQ_NEXT(STAILQ_NEXT(elm, field), field)) == NULL)	\
+		(head)->stqh_last = &STAILQ_NEXT((elm), field);		\
+} while (0)
+
+/*
+ * List declarations.
+ */
+#define	LIST_HEAD(name, type)						\
+struct name {								\
+	struct type *lh_first;	/* first element */			\
+}
+
+#define	LIST_HEAD_INITIALIZER(head)					\
+	{ NULL }
+
+#define	LIST_ENTRY(type)						\
+struct {								\
+	struct type *le_next;	/* next element */			\
+	struct type **le_prev;	/* address of previous next element */	\
+}
+
+/*
+ * List functions.
+ */
+
+#define	LIST_EMPTY(head)	((head)->lh_first == NULL)
+
+#define	LIST_FIRST(head)	((head)->lh_first)
+
+#define	LIST_FOREACH(var, head, field)					\
+	for ((var) = LIST_FIRST((head));				\
+	    (var);							\
+	    (var) = LIST_NEXT((var), field))
+
+#define	LIST_INIT(head) do {						\
+	LIST_FIRST((head)) = NULL;					\
+} while (0)
+
+#define	LIST_INSERT_AFTER(listelm, elm, field) do {			\
+	if ((LIST_NEXT((elm), field) = LIST_NEXT((listelm), field)) != NULL)\
+		LIST_NEXT((listelm), field)->field.le_prev =		\
+		    &LIST_NEXT((elm), field);				\
+	LIST_NEXT((listelm), field) = (elm);				\
+	(elm)->field.le_prev = &LIST_NEXT((listelm), field);		\
+} while (0)
+
+#define	LIST_INSERT_BEFORE(listelm, elm, field) do {			\
+	(elm)->field.le_prev = (listelm)->field.le_prev;		\
+	LIST_NEXT((elm), field) = (listelm);				\
+	*(listelm)->field.le_prev = (elm);				\
+	(listelm)->field.le_prev = &LIST_NEXT((elm), field);		\
+} while (0)
+
+#define	LIST_INSERT_HEAD(head, elm, field) do {				\
+	if ((LIST_NEXT((elm), field) = LIST_FIRST((head))) != NULL)	\
+		LIST_FIRST((head))->field.le_prev = &LIST_NEXT((elm), field);\
+	LIST_FIRST((head)) = (elm);					\
+	(elm)->field.le_prev = &LIST_FIRST((head));			\
+} while (0)
+
+#define	LIST_NEXT(elm, field)	((elm)->field.le_next)
+
+#define	LIST_REMOVE(elm, field) do {					\
+	if (LIST_NEXT((elm), field) != NULL)				\
+		LIST_NEXT((elm), field)->field.le_prev = 		\
+		    (elm)->field.le_prev;				\
+	*(elm)->field.le_prev = LIST_NEXT((elm), field);		\
+} while (0)
+
+/*
+ * Tail queue declarations.
+ */
+#define	TAILQ_HEAD(name, type)						\
+struct name {								\
+	struct type *tqh_first;	/* first element */			\
+	struct type **tqh_last;	/* addr of last next element */		\
+}
+
+#define	TAILQ_HEAD_INITIALIZER(head)					\
+	{ NULL, &(head).tqh_first }
+
+#define	TAILQ_ENTRY(type)						\
+struct {								\
+	struct type *tqe_next;	/* next element */			\
+	struct type **tqe_prev;	/* address of previous next element */	\
+}
+
+/*
+ * Tail queue functions.
+ */
+#define	TAILQ_EMPTY(head)	((head)->tqh_first == NULL)
+
+#define	TAILQ_FIRST(head)	((head)->tqh_first)
+
+#define	TAILQ_FOREACH(var, head, field)					\
+	for ((var) = TAILQ_FIRST((head));				\
+	    (var);							\
+	    (var) = TAILQ_NEXT((var), field))
+
+#define	TAILQ_FOREACH_REVERSE(var, head, headname, field)		\
+	for ((var) = TAILQ_LAST((head), headname);			\
+	    (var);							\
+	    (var) = TAILQ_PREV((var), headname, field))
+
+#define	TAILQ_INIT(head) do {						\
+	TAILQ_FIRST((head)) = NULL;					\
+	(head)->tqh_last = &TAILQ_FIRST((head));			\
+} while (0)
+
+#define	TAILQ_INSERT_AFTER(head, listelm, elm, field) do {		\
+	if ((TAILQ_NEXT((elm), field) = TAILQ_NEXT((listelm), field)) != NULL)\
+		TAILQ_NEXT((elm), field)->field.tqe_prev = 		\
+		    &TAILQ_NEXT((elm), field);				\
+	else								\
+		(head)->tqh_last = &TAILQ_NEXT((elm), field);		\
+	TAILQ_NEXT((listelm), field) = (elm);				\
+	(elm)->field.tqe_prev = &TAILQ_NEXT((listelm), field);		\
+} while (0)
+
+#define	TAILQ_INSERT_BEFORE(listelm, elm, field) do {			\
+	(elm)->field.tqe_prev = (listelm)->field.tqe_prev;		\
+	TAILQ_NEXT((elm), field) = (listelm);				\
+	*(listelm)->field.tqe_prev = (elm);				\
+	(listelm)->field.tqe_prev = &TAILQ_NEXT((elm), field);		\
+} while (0)
+
+#define	TAILQ_INSERT_HEAD(head, elm, field) do {			\
+	if ((TAILQ_NEXT((elm), field) = TAILQ_FIRST((head))) != NULL)	\
+		TAILQ_FIRST((head))->field.tqe_prev =			\
+		    &TAILQ_NEXT((elm), field);				\
+	else								\
+		(head)->tqh_last = &TAILQ_NEXT((elm), field);		\
+	TAILQ_FIRST((head)) = (elm);					\
+	(elm)->field.tqe_prev = &TAILQ_FIRST((head));			\
+} while (0)
+
+#define	TAILQ_INSERT_TAIL(head, elm, field) do {			\
+	TAILQ_NEXT((elm), field) = NULL;				\
+	(elm)->field.tqe_prev = (head)->tqh_last;			\
+	*(head)->tqh_last = (elm);					\
+	(head)->tqh_last = &TAILQ_NEXT((elm), field);			\
+} while (0)
+
+#define	TAILQ_LAST(head, headname)					\
+	(*(((struct headname *)((head)->tqh_last))->tqh_last))
+
+#define	TAILQ_NEXT(elm, field) ((elm)->field.tqe_next)
+
+#define	TAILQ_PREV(elm, headname, field)				\
+	(*(((struct headname *)((elm)->field.tqe_prev))->tqh_last))
+
+#define	TAILQ_REMOVE(head, elm, field) do {				\
+	if ((TAILQ_NEXT((elm), field)) != NULL)				\
+		TAILQ_NEXT((elm), field)->field.tqe_prev = 		\
+		    (elm)->field.tqe_prev;				\
+	else								\
+		(head)->tqh_last = (elm)->field.tqe_prev;		\
+	*(elm)->field.tqe_prev = TAILQ_NEXT((elm), field);		\
+} while (0)
+
+/*
+ * Circular queue declarations.
+ */
+#define	CIRCLEQ_HEAD(name, type)					\
+struct name {								\
+	struct type *cqh_first;		/* first element */		\
+	struct type *cqh_last;		/* last element */		\
+}
+
+#define	CIRCLEQ_HEAD_INITIALIZER(head)					\
+	{ (void *)&(head), (void *)&(head) }
+
+#define	CIRCLEQ_ENTRY(type)						\
+struct {								\
+	struct type *cqe_next;		/* next element */		\
+	struct type *cqe_prev;		/* previous element */		\
+}
+
+/*
+ * Circular queue functions.
+ */
+#define	CIRCLEQ_EMPTY(head)	((head)->cqh_first == (void *)(head))
+
+#define	CIRCLEQ_FIRST(head)	((head)->cqh_first)
+
+#define	CIRCLEQ_FOREACH(var, head, field)				\
+	for ((var) = CIRCLEQ_FIRST((head));				\
+	    (var) != (void *)(head) || ((var) = NULL);			\
+	    (var) = CIRCLEQ_NEXT((var), field))
+
+#define	CIRCLEQ_FOREACH_REVERSE(var, head, field)			\
+	for ((var) = CIRCLEQ_LAST((head));				\
+	    (var) != (void *)(head) || ((var) = NULL);			\
+	    (var) = CIRCLEQ_PREV((var), field))
+
+#define	CIRCLEQ_INIT(head) do {						\
+	CIRCLEQ_FIRST((head)) = (void *)(head);				\
+	CIRCLEQ_LAST((head)) = (void *)(head);				\
+} while (0)
+
+#define	CIRCLEQ_INSERT_AFTER(head, listelm, elm, field) do {		\
+	CIRCLEQ_NEXT((elm), field) = CIRCLEQ_NEXT((listelm), field);	\
+	CIRCLEQ_PREV((elm), field) = (listelm);				\
+	if (CIRCLEQ_NEXT((listelm), field) == (void *)(head))		\
+		CIRCLEQ_LAST((head)) = (elm);				\
+	else								\
+		CIRCLEQ_PREV(CIRCLEQ_NEXT((listelm), field), field) = (elm);\
+	CIRCLEQ_NEXT((listelm), field) = (elm);				\
+} while (0)
+
+#define	CIRCLEQ_INSERT_BEFORE(head, listelm, elm, field) do {		\
+	CIRCLEQ_NEXT((elm), field) = (listelm);				\
+	CIRCLEQ_PREV((elm), field) = CIRCLEQ_PREV((listelm), field);	\
+	if (CIRCLEQ_PREV((listelm), field) == (void *)(head))		\
+		CIRCLEQ_FIRST((head)) = (elm);				\
+	else								\
+		CIRCLEQ_NEXT(CIRCLEQ_PREV((listelm), field), field) = (elm);\
+	CIRCLEQ_PREV((listelm), field) = (elm);				\
+} while (0)
+
+#define	CIRCLEQ_INSERT_HEAD(head, elm, field) do {			\
+	CIRCLEQ_NEXT((elm), field) = CIRCLEQ_FIRST((head));		\
+	CIRCLEQ_PREV((elm), field) = (void *)(head);			\
+	if (CIRCLEQ_LAST((head)) == (void *)(head))			\
+		CIRCLEQ_LAST((head)) = (elm);				\
+	else								\
+		CIRCLEQ_PREV(CIRCLEQ_FIRST((head)), field) = (elm);	\
+	CIRCLEQ_FIRST((head)) = (elm);					\
+} while (0)
+
+#define	CIRCLEQ_INSERT_TAIL(head, elm, field) do {			\
+	CIRCLEQ_NEXT((elm), field) = (void *)(head);			\
+	CIRCLEQ_PREV((elm), field) = CIRCLEQ_LAST((head));		\
+	if (CIRCLEQ_FIRST((head)) == (void *)(head))			\
+		CIRCLEQ_FIRST((head)) = (elm);				\
+	else								\
+		CIRCLEQ_NEXT(CIRCLEQ_LAST((head)), field) = (elm);	\
+	CIRCLEQ_LAST((head)) = (elm);					\
+} while (0)
+
+#define	CIRCLEQ_LAST(head)	((head)->cqh_last)
+
+#define	CIRCLEQ_NEXT(elm,field)	((elm)->field.cqe_next)
+
+#define	CIRCLEQ_PREV(elm,field)	((elm)->field.cqe_prev)
+
+#define	CIRCLEQ_REMOVE(head, elm, field) do {				\
+	if (CIRCLEQ_NEXT((elm), field) == (void *)(head))		\
+		CIRCLEQ_LAST((head)) = CIRCLEQ_PREV((elm), field);	\
+	else								\
+		CIRCLEQ_PREV(CIRCLEQ_NEXT((elm), field), field) =	\
+		    CIRCLEQ_PREV((elm), field);				\
+	if (CIRCLEQ_PREV((elm), field) == (void *)(head))		\
+		CIRCLEQ_FIRST((head)) = CIRCLEQ_NEXT((elm), field);	\
+	else								\
+		CIRCLEQ_NEXT(CIRCLEQ_PREV((elm), field), field) =	\
+		    CIRCLEQ_NEXT((elm), field);				\
+} while (0)
+
+#endif /* !_QUEUE_H_ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/pkg.yml
----------------------------------------------------------------------
diff --git a/kernel/os/pkg.yml b/kernel/os/pkg.yml
new file mode 100644
index 0000000..57a9e63
--- /dev/null
+++ b/kernel/os/pkg.yml
@@ -0,0 +1,84 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+#
+
+pkg.name: kernel/os
+pkg.description: Mynewt operating system core.
+pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
+pkg.homepage: "http://mynewt.apache.org/"
+pkg.keywords:
+
+pkg.deps:
+    - sys/sysinit
+    - libs/util
+
+pkg.req_apis:
+    - console
+
+pkg.deps.OS_CLI:
+    - sys/shell
+
+pkg.deps.OS_COREDUMP:
+    - sys/coredump
+
+pkg.init_function: os_pkg_init
+pkg.init_stage: 0
+
+pkg.syscfg_defs:
+    OS_CLI:
+        description: 'TBD'
+        value: 'MYNEWT_PKG_LIBS_SHELL'
+    OS_COREDUMP:
+        description: 'TBD'
+        value: 'MYNEWT_PKG_SYS_COREDUMP'
+    SANITY_INTERVAL:
+        description: 'The interval (in milliseconds) at which the sanity checks should run, should be at least 200ms prior to watchdog'
+        value: 59500
+    WATCHDOG_INTERVAL:
+        description: 'The interval (in milliseconds) at which the watchdog should reset if not tickled, in ms'
+        value: 60000
+    MSYS_1_BLOCK_COUNT:
+        description: 'TBD'
+        value: 12
+    MSYS_1_BLOCK_SIZE:
+        description: 'TBD'
+        value: 260
+    MSYS_2_BLOCK_COUNT:
+        description: 'TBD'
+        value: 0
+    MSYS_2_BLOCK_SIZE:
+        description: 'TBD'
+        value: 0
+    MSYS_3_BLOCK_COUNT:
+        description: 'TBD'
+        value: 0
+    MSYS_3_BLOCK_SIZE:
+        description: 'TBD'
+        value: 0
+    MSYS_4_BLOCK_COUNT:
+        description: 'TBD'
+        value: 0
+    MSYS_4_BLOCK_SIZE:
+        description: 'TBD'
+        value: 0
+    MSYS_5_BLOCK_COUNT:
+        description: 'TBD'
+        value: 0
+    MSYS_5_BLOCK_SIZE:
+        description: 'TBD'
+        value: 0


[29/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/bootutil/test/src/boot_test.c
----------------------------------------------------------------------
diff --git a/libs/bootutil/test/src/boot_test.c b/libs/bootutil/test/src/boot_test.c
deleted file mode 100644
index 10cd045..0000000
--- a/libs/bootutil/test/src/boot_test.c
+++ /dev/null
@@ -1,1169 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include <assert.h>
-#include <stddef.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <inttypes.h>
-#include "syscfg/syscfg.h"
-#include "testutil/testutil.h"
-#include "hal/hal_flash.h"
-#include "hal/flash_map.h"
-#include "bootutil/image.h"
-#include "bootutil/loader.h"
-#include "bootutil/bootutil_misc.h"
-#include "../src/bootutil_priv.h"
-
-#include "mbedtls/sha256.h"
-
-#define BOOT_TEST_HEADER_SIZE       0x200
-
-/** Internal flash layout. */
-static struct flash_area boot_test_area_descs[] = {
-    [0] = { .fa_off = 0x00020000, .fa_size = 128 * 1024 },
-    [1] = { .fa_off = 0x00040000, .fa_size = 128 * 1024 },
-    [2] = { .fa_off = 0x00060000, .fa_size = 128 * 1024 },
-    [3] = { .fa_off = 0x00080000, .fa_size = 128 * 1024 },
-    [4] = { .fa_off = 0x000a0000, .fa_size = 128 * 1024 },
-    [5] = { .fa_off = 0x000c0000, .fa_size = 128 * 1024 },
-    [6] = { .fa_off = 0x000e0000, .fa_size = 128 * 1024 },
-    [7] = { 0 },
-};
-
-/** Areas representing the beginning of image slots. */
-static uint8_t boot_test_slot_areas[] = {
-    0, 3,
-};
-
-/** Flash offsets of the two image slots. */
-static struct {
-    uint8_t flash_id;
-    uint32_t address;
-} boot_test_img_addrs[] = {
-    { 0, 0x20000 },
-    { 0, 0x80000 },
-};
-
-#define BOOT_TEST_AREA_IDX_SCRATCH 6
-
-static uint8_t
-boot_test_util_byte_at(int img_msb, uint32_t image_offset)
-{
-    uint32_t u32;
-    uint8_t *u8p;
-
-    TEST_ASSERT(image_offset < 0x01000000);
-    u32 = image_offset + (img_msb << 24);
-    u8p = (void *)&u32;
-    return u8p[image_offset % 4];
-}
-
-static void
-boot_test_util_init_flash(void)
-{
-    const struct flash_area *area_desc;
-    int rc;
-
-    rc = hal_flash_init();
-    TEST_ASSERT(rc == 0);
-
-    for (area_desc = boot_test_area_descs;
-         area_desc->fa_size != 0;
-         area_desc++) {
-
-        rc = flash_area_erase(area_desc, 0, area_desc->fa_size);
-        TEST_ASSERT(rc == 0);
-    }
-}
-
-static void
-boot_test_util_copy_area(int from_area_idx, int to_area_idx)
-{
-    const struct flash_area *from_area_desc;
-    const struct flash_area *to_area_desc;
-    void *buf;
-    int rc;
-
-    from_area_desc = boot_test_area_descs + from_area_idx;
-    to_area_desc = boot_test_area_descs + to_area_idx;
-
-    TEST_ASSERT(from_area_desc->fa_size == to_area_desc->fa_size);
-
-    buf = malloc(from_area_desc->fa_size);
-    TEST_ASSERT(buf != NULL);
-
-    rc = flash_area_read(from_area_desc, 0, buf,
-                         from_area_desc->fa_size);
-    TEST_ASSERT(rc == 0);
-
-    rc = flash_area_erase(to_area_desc,
-                          0,
-                          to_area_desc->fa_size);
-    TEST_ASSERT(rc == 0);
-
-    rc = flash_area_write(to_area_desc, 0, buf,
-                          to_area_desc->fa_size);
-    TEST_ASSERT(rc == 0);
-
-    free(buf);
-}
-
-static void
-boot_test_util_swap_areas(int area_idx1, int area_idx2)
-{
-    const struct flash_area *area_desc1;
-    const struct flash_area *area_desc2;
-    void *buf1;
-    void *buf2;
-    int rc;
-
-    area_desc1 = boot_test_area_descs + area_idx1;
-    area_desc2 = boot_test_area_descs + area_idx2;
-
-    TEST_ASSERT(area_desc1->fa_size == area_desc2->fa_size);
-
-    buf1 = malloc(area_desc1->fa_size);
-    TEST_ASSERT(buf1 != NULL);
-
-    buf2 = malloc(area_desc2->fa_size);
-    TEST_ASSERT(buf2 != NULL);
-
-    rc = flash_area_read(area_desc1, 0, buf1, area_desc1->fa_size);
-    TEST_ASSERT(rc == 0);
-
-    rc = flash_area_read(area_desc2, 0, buf2, area_desc2->fa_size);
-    TEST_ASSERT(rc == 0);
-
-    rc = flash_area_erase(area_desc1, 0, area_desc1->fa_size);
-    TEST_ASSERT(rc == 0);
-
-    rc = flash_area_erase(area_desc2, 0, area_desc2->fa_size);
-    TEST_ASSERT(rc == 0);
-
-    rc = flash_area_write(area_desc1, 0, buf2, area_desc1->fa_size);
-    TEST_ASSERT(rc == 0);
-
-    rc = flash_area_write(area_desc2, 0, buf1, area_desc2->fa_size);
-    TEST_ASSERT(rc == 0);
-
-    free(buf1);
-    free(buf2);
-}
-
-static void
-boot_test_util_write_image(const struct image_header *hdr, int slot)
-{
-    uint32_t image_off;
-    uint32_t off;
-    uint8_t flash_id;
-    uint8_t buf[256];
-    int chunk_sz;
-    int rc;
-    int i;
-
-    TEST_ASSERT(slot == 0 || slot == 1);
-
-    flash_id = boot_test_img_addrs[slot].flash_id;
-    off = boot_test_img_addrs[slot].address;
-
-    rc = hal_flash_write(flash_id, off, hdr, sizeof *hdr);
-    TEST_ASSERT(rc == 0);
-
-    off += hdr->ih_hdr_size;
-
-    image_off = 0;
-    while (image_off < hdr->ih_img_size) {
-        if (hdr->ih_img_size - image_off > sizeof buf) {
-            chunk_sz = sizeof buf;
-        } else {
-            chunk_sz = hdr->ih_img_size - image_off;
-        }
-
-        for (i = 0; i < chunk_sz; i++) {
-            buf[i] = boot_test_util_byte_at(slot, image_off + i);
-        }
-
-        rc = hal_flash_write(flash_id, off + image_off, buf, chunk_sz);
-        TEST_ASSERT(rc == 0);
-
-        image_off += chunk_sz;
-    }
-}
-
-static void
-boot_test_util_write_hash(const struct image_header *hdr, int slot)
-{
-    uint8_t tmpdata[1024];
-    uint8_t hash[32];
-    int rc;
-    uint32_t off;
-    uint32_t blk_sz;
-    uint32_t sz;
-    mbedtls_sha256_context ctx;
-    uint8_t flash_id;
-    uint32_t addr;
-    struct image_tlv tlv;
-
-    mbedtls_sha256_init(&ctx);
-    mbedtls_sha256_starts(&ctx, 0);
-
-    flash_id = boot_test_img_addrs[slot].flash_id;
-    addr = boot_test_img_addrs[slot].address;
-
-    sz = hdr->ih_hdr_size + hdr->ih_img_size;
-    for (off = 0; off < sz; off += blk_sz) {
-        blk_sz = sz - off;
-        if (blk_sz > sizeof(tmpdata)) {
-            blk_sz = sizeof(tmpdata);
-        }
-        rc = hal_flash_read(flash_id, addr + off, tmpdata, blk_sz);
-        TEST_ASSERT(rc == 0);
-        mbedtls_sha256_update(&ctx, tmpdata, blk_sz);
-    }
-    mbedtls_sha256_finish(&ctx, hash);
-
-    tlv.it_type = IMAGE_TLV_SHA256;
-    tlv._pad = 0;
-    tlv.it_len = sizeof(hash);
-
-    rc = hal_flash_write(flash_id, addr + off, &tlv, sizeof(tlv));
-    TEST_ASSERT(rc == 0);
-    off += sizeof(tlv);
-    rc = hal_flash_write(flash_id, addr + off, hash, sizeof(hash));
-    TEST_ASSERT(rc == 0);
-}
-
-static void
-boot_test_util_verify_area(const struct flash_area *area_desc,
-                           const struct image_header *hdr,
-                           uint32_t image_addr, int img_msb)
-{
-    struct image_header temp_hdr;
-    uint32_t area_end;
-    uint32_t img_size;
-    uint32_t img_off;
-    uint32_t img_end;
-    uint32_t addr;
-    uint8_t buf[256];
-    int rem_area;
-    int past_image;
-    int chunk_sz;
-    int rem_img;
-    int rc;
-    int i;
-
-    addr = area_desc->fa_off;
-
-    if (hdr != NULL) {
-        img_size = hdr->ih_img_size;
-
-        if (addr == image_addr) {
-            rc = hal_flash_read(area_desc->fa_flash_id, image_addr,
-                                &temp_hdr, sizeof temp_hdr);
-            TEST_ASSERT(rc == 0);
-            TEST_ASSERT(memcmp(&temp_hdr, hdr, sizeof *hdr) == 0);
-
-            addr += hdr->ih_hdr_size;
-        }
-    } else {
-        img_size = 0;
-    }
-
-    area_end = area_desc->fa_off + area_desc->fa_size;
-    img_end = image_addr + img_size;
-    past_image = addr >= img_end;
-
-    while (addr < area_end) {
-        rem_area = area_end - addr;
-        rem_img = img_end - addr;
-
-        if (hdr != NULL) {
-            img_off = addr - image_addr - hdr->ih_hdr_size;
-        } else {
-            img_off = 0;
-        }
-
-        if (rem_area > sizeof buf) {
-            chunk_sz = sizeof buf;
-        } else {
-            chunk_sz = rem_area;
-        }
-
-        rc = hal_flash_read(area_desc->fa_flash_id, addr, buf, chunk_sz);
-        TEST_ASSERT(rc == 0);
-
-        for (i = 0; i < chunk_sz; i++) {
-            if (rem_img > 0) {
-                TEST_ASSERT(buf[i] == boot_test_util_byte_at(img_msb,
-                                                        img_off + i));
-            } else if (past_image) {
-#if 0
-                TEST_ASSERT(buf[i] == 0xff);
-#endif
-            }
-        }
-
-        addr += chunk_sz;
-    }
-}
-
-static void
-boot_test_util_verify_status_clear(void)
-{
-    struct boot_img_trailer bit;
-    const struct flash_area *fap;
-    int rc;
-
-    rc = flash_area_open(FLASH_AREA_IMAGE_0, &fap);
-    TEST_ASSERT(rc == 0);
-
-    rc = flash_area_read(fap, fap->fa_size - sizeof(bit), &bit, sizeof(bit));
-    TEST_ASSERT(rc == 0);
-
-    TEST_ASSERT(bit.bit_copy_start != BOOT_IMG_MAGIC ||
-      bit.bit_copy_done != 0xff);
-}
-
-static void
-boot_test_util_verify_flash(const struct image_header *hdr0, int orig_slot_0,
-                            const struct image_header *hdr1, int orig_slot_1)
-{
-    const struct flash_area *area_desc;
-    int area_idx;
-
-    area_idx = 0;
-
-    while (1) {
-        area_desc = boot_test_area_descs + area_idx;
-        if (area_desc->fa_off == boot_test_img_addrs[1].address &&
-            area_desc->fa_flash_id == boot_test_img_addrs[1].flash_id) {
-            break;
-        }
-
-        boot_test_util_verify_area(area_desc, hdr0,
-                                   boot_test_img_addrs[0].address, orig_slot_0);
-        area_idx++;
-    }
-
-    while (1) {
-        if (area_idx == BOOT_TEST_AREA_IDX_SCRATCH) {
-            break;
-        }
-
-        area_desc = boot_test_area_descs + area_idx;
-        boot_test_util_verify_area(area_desc, hdr1,
-                                   boot_test_img_addrs[1].address, orig_slot_1);
-        area_idx++;
-    }
-}
-
-TEST_CASE(boot_test_nv_ns_10)
-{
-    struct boot_rsp rsp;
-    int rc;
-
-    struct image_header hdr = {
-        .ih_magic = IMAGE_MAGIC,
-        .ih_tlv_size = 4 + 32,
-        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
-        .ih_img_size = 12 * 1024,
-        .ih_flags = IMAGE_F_SHA256,
-        .ih_ver = { 0, 2, 3, 4 },
-    };
-
-    struct boot_req req = {
-        .br_area_descs = boot_test_area_descs,
-        .br_slot_areas = boot_test_slot_areas,
-        .br_num_image_areas = BOOT_TEST_AREA_IDX_SCRATCH + 1,
-        .br_scratch_area_idx = BOOT_TEST_AREA_IDX_SCRATCH,
-        .br_img_sz = (384 * 1024),
-    };
-
-    boot_test_util_init_flash();
-    boot_test_util_write_image(&hdr, 0);
-    boot_test_util_write_hash(&hdr, 0);
-
-    rc = boot_go(&req, &rsp);
-    TEST_ASSERT(rc == 0);
-
-    TEST_ASSERT(memcmp(rsp.br_hdr, &hdr, sizeof hdr) == 0);
-    TEST_ASSERT(rsp.br_flash_id == boot_test_img_addrs[0].flash_id);
-    TEST_ASSERT(rsp.br_image_addr == boot_test_img_addrs[0].address);
-
-    boot_test_util_verify_flash(&hdr, 0, NULL, 0xff);
-    boot_test_util_verify_status_clear();
-}
-
-TEST_CASE(boot_test_nv_ns_01)
-{
-    struct boot_rsp rsp;
-    int rc;
-
-
-    struct image_header hdr = {
-        .ih_magic = IMAGE_MAGIC,
-        .ih_tlv_size = 4 + 32,
-        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
-        .ih_img_size = 10 * 1024,
-        .ih_flags = IMAGE_F_SHA256,
-        .ih_ver = { 1, 2, 3, 432 },
-    };
-
-    struct boot_req req = {
-        .br_area_descs = boot_test_area_descs,
-        .br_slot_areas = boot_test_slot_areas,
-        .br_num_image_areas = BOOT_TEST_AREA_IDX_SCRATCH + 1,
-        .br_scratch_area_idx = BOOT_TEST_AREA_IDX_SCRATCH,
-        .br_img_sz = (384 * 1024),
-    };
-
-    boot_test_util_init_flash();
-    boot_test_util_write_image(&hdr, 1);
-    boot_test_util_write_hash(&hdr, 1);
-
-    boot_vect_write_test(FLASH_AREA_IMAGE_1);
-    rc = boot_go(&req, &rsp);
-    TEST_ASSERT(rc == 0);
-
-    TEST_ASSERT(memcmp(rsp.br_hdr, &hdr, sizeof hdr) == 0);
-    TEST_ASSERT(rsp.br_flash_id == boot_test_img_addrs[0].flash_id);
-    TEST_ASSERT(rsp.br_image_addr == boot_test_img_addrs[0].address);
-
-    boot_test_util_verify_flash(&hdr, 1, NULL, 0xff);
-    boot_test_util_verify_status_clear();
-}
-
-TEST_CASE(boot_test_nv_ns_11)
-{
-    struct boot_rsp rsp;
-    int rc;
-
-    struct image_header hdr0 = {
-        .ih_magic = IMAGE_MAGIC,
-        .ih_tlv_size = 4 + 32,
-        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
-        .ih_img_size = 5 * 1024,
-        .ih_flags = IMAGE_F_SHA256,
-        .ih_ver = { 0, 5, 21, 432 },
-    };
-
-    struct image_header hdr1 = {
-        .ih_magic = IMAGE_MAGIC,
-        .ih_tlv_size = 4 + 32,
-        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
-        .ih_img_size = 32 * 1024,
-        .ih_flags = IMAGE_F_SHA256,
-        .ih_ver = { 1, 2, 3, 432 },
-    };
-
-    struct boot_req req = {
-        .br_area_descs = boot_test_area_descs,
-        .br_slot_areas = boot_test_slot_areas,
-        .br_num_image_areas = BOOT_TEST_AREA_IDX_SCRATCH + 1,
-        .br_scratch_area_idx = BOOT_TEST_AREA_IDX_SCRATCH,
-        .br_img_sz = (384 * 1024),
-    };
-
-    boot_test_util_init_flash();
-    boot_test_util_write_image(&hdr0, 0);
-    boot_test_util_write_hash(&hdr0, 0);
-    boot_test_util_write_image(&hdr1, 1);
-    boot_test_util_write_hash(&hdr1, 1);
-
-    rc = boot_go(&req, &rsp);
-    TEST_ASSERT(rc == 0);
-
-    TEST_ASSERT(memcmp(rsp.br_hdr, &hdr0, sizeof hdr0) == 0);
-    TEST_ASSERT(rsp.br_flash_id == boot_test_img_addrs[0].flash_id);
-    TEST_ASSERT(rsp.br_image_addr == boot_test_img_addrs[0].address);
-
-    boot_test_util_verify_flash(&hdr0, 0, &hdr1, 1);
-    boot_test_util_verify_status_clear();
-}
-
-TEST_CASE(boot_test_vm_ns_10)
-{
-    struct boot_rsp rsp;
-    int rc;
-
-
-    struct image_header hdr = {
-        .ih_magic = IMAGE_MAGIC,
-        .ih_tlv_size = 4 + 32,
-        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
-        .ih_img_size = 12 * 1024,
-        .ih_flags = IMAGE_F_SHA256,
-        .ih_ver = { 0, 2, 3, 4 },
-    };
-
-    struct boot_req req = {
-        .br_area_descs = boot_test_area_descs,
-        .br_slot_areas = boot_test_slot_areas,
-        .br_num_image_areas = BOOT_TEST_AREA_IDX_SCRATCH + 1,
-        .br_scratch_area_idx = BOOT_TEST_AREA_IDX_SCRATCH,
-        .br_img_sz = (384 * 1024),
-    };
-
-    boot_test_util_init_flash();
-    boot_test_util_write_image(&hdr, 0);
-    boot_test_util_write_hash(&hdr, 0);
-
-    rc = boot_go(&req, &rsp);
-    TEST_ASSERT(rc == 0);
-
-    TEST_ASSERT(memcmp(rsp.br_hdr, &hdr, sizeof hdr) == 0);
-    TEST_ASSERT(rsp.br_flash_id == boot_test_img_addrs[0].flash_id);
-    TEST_ASSERT(rsp.br_image_addr == boot_test_img_addrs[0].address);
-
-    boot_test_util_verify_flash(&hdr, 0, NULL, 0xff);
-    boot_test_util_verify_status_clear();
-}
-
-TEST_CASE(boot_test_vm_ns_01)
-{
-    struct boot_rsp rsp;
-    int rc;
-
-    struct image_header hdr = {
-        .ih_magic = IMAGE_MAGIC,
-        .ih_tlv_size = 4 + 32,
-        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
-        .ih_img_size = 10 * 1024,
-        .ih_flags = IMAGE_F_SHA256,
-        .ih_ver = { 1, 2, 3, 432 },
-    };
-
-    struct boot_req req = {
-        .br_area_descs = boot_test_area_descs,
-        .br_slot_areas = boot_test_slot_areas,
-        .br_num_image_areas = BOOT_TEST_AREA_IDX_SCRATCH + 1,
-        .br_scratch_area_idx = BOOT_TEST_AREA_IDX_SCRATCH,
-        .br_img_sz = (384 * 1024),
-    };
-
-    boot_test_util_init_flash();
-    boot_test_util_write_image(&hdr, 1);
-    boot_test_util_write_hash(&hdr, 1);
-
-    rc = boot_vect_write_test(FLASH_AREA_IMAGE_1);
-    TEST_ASSERT(rc == 0);
-
-    rc = boot_go(&req, &rsp);
-    TEST_ASSERT(rc == 0);
-
-    TEST_ASSERT(memcmp(rsp.br_hdr, &hdr, sizeof hdr) == 0);
-    TEST_ASSERT(rsp.br_flash_id == boot_test_img_addrs[0].flash_id);
-    TEST_ASSERT(rsp.br_image_addr == boot_test_img_addrs[0].address);
-
-    boot_test_util_verify_flash(&hdr, 1, NULL, 0xff);
-    boot_test_util_verify_status_clear();
-}
-
-TEST_CASE(boot_test_vm_ns_11_a)
-{
-    struct boot_rsp rsp;
-    int rc;
-
-    struct image_header hdr0 = {
-        .ih_magic = IMAGE_MAGIC,
-        .ih_tlv_size = 4 + 32,
-        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
-        .ih_img_size = 5 * 1024,
-        .ih_flags = IMAGE_F_SHA256,
-        .ih_ver = { 0, 5, 21, 432 },
-    };
-
-    struct image_header hdr1 = {
-        .ih_magic = IMAGE_MAGIC,
-        .ih_tlv_size = 4 + 32,
-        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
-        .ih_img_size = 32 * 1024,
-        .ih_flags = IMAGE_F_SHA256,
-        .ih_ver = { 1, 2, 3, 432 },
-    };
-
-    struct boot_req req = {
-        .br_area_descs = boot_test_area_descs,
-        .br_slot_areas = boot_test_slot_areas,
-        .br_num_image_areas = BOOT_TEST_AREA_IDX_SCRATCH + 1,
-        .br_scratch_area_idx = BOOT_TEST_AREA_IDX_SCRATCH,
-        .br_img_sz = (384 * 1024),
-    };
-
-    boot_test_util_init_flash();
-    boot_test_util_write_image(&hdr0, 0);
-    boot_test_util_write_hash(&hdr0, 0);
-    boot_test_util_write_image(&hdr1, 1);
-    boot_test_util_write_hash(&hdr1, 1);
-
-    rc = boot_go(&req, &rsp);
-    TEST_ASSERT(rc == 0);
-
-    TEST_ASSERT(memcmp(rsp.br_hdr, &hdr0, sizeof hdr0) == 0);
-    TEST_ASSERT(rsp.br_flash_id == boot_test_img_addrs[0].flash_id);
-    TEST_ASSERT(rsp.br_image_addr == boot_test_img_addrs[0].address);
-
-    boot_test_util_verify_flash(&hdr0, 0, &hdr1, 1);
-    boot_test_util_verify_status_clear();
-}
-
-TEST_CASE(boot_test_vm_ns_11_b)
-{
-    struct boot_rsp rsp;
-    int rc;
-
-    struct image_header hdr0 = {
-        .ih_magic = IMAGE_MAGIC,
-        .ih_tlv_size = 4 + 32,
-        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
-        .ih_img_size = 5 * 1024,
-        .ih_flags = IMAGE_F_SHA256,
-        .ih_ver = { 0, 5, 21, 432 },
-    };
-
-    struct image_header hdr1 = {
-        .ih_magic = IMAGE_MAGIC,
-        .ih_tlv_size = 4 + 32,
-        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
-        .ih_img_size = 32 * 1024,
-        .ih_flags = IMAGE_F_SHA256,
-        .ih_ver = { 1, 2, 3, 432 },
-    };
-
-    struct boot_req req = {
-        .br_area_descs = boot_test_area_descs,
-        .br_slot_areas = boot_test_slot_areas,
-        .br_num_image_areas = BOOT_TEST_AREA_IDX_SCRATCH + 1,
-        .br_scratch_area_idx = BOOT_TEST_AREA_IDX_SCRATCH,
-        .br_img_sz = (384 * 1024),
-    };
-
-    boot_test_util_init_flash();
-    boot_test_util_write_image(&hdr0, 0);
-    boot_test_util_write_hash(&hdr0, 0);
-    boot_test_util_write_image(&hdr1, 1);
-    boot_test_util_write_hash(&hdr1, 1);
-
-    rc = boot_vect_write_test(FLASH_AREA_IMAGE_1);
-    TEST_ASSERT(rc == 0);
-
-    rc = boot_go(&req, &rsp);
-    TEST_ASSERT(rc == 0);
-
-    TEST_ASSERT(memcmp(rsp.br_hdr, &hdr1, sizeof hdr1) == 0);
-    TEST_ASSERT(rsp.br_flash_id == boot_test_img_addrs[0].flash_id);
-    TEST_ASSERT(rsp.br_image_addr == boot_test_img_addrs[0].address);
-
-    boot_test_util_verify_flash(&hdr1, 1, &hdr0, 0);
-    boot_test_util_verify_status_clear();
-}
-
-TEST_CASE(boot_test_vm_ns_11_2areas)
-{
-    struct boot_rsp rsp;
-    int rc;
-
-    struct image_header hdr0 = {
-        .ih_magic = IMAGE_MAGIC,
-        .ih_tlv_size = 4 + 32,
-        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
-        .ih_img_size = 5 * 1024,
-        .ih_flags = IMAGE_F_SHA256,
-        .ih_ver = { 0, 5, 21, 432 },
-    };
-
-    struct image_header hdr1 = {
-        .ih_magic = IMAGE_MAGIC,
-        .ih_tlv_size = 4 + 32,
-        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
-        .ih_img_size = 196 * 1024,
-        .ih_flags = IMAGE_F_SHA256,
-        .ih_ver = { 1, 2, 3, 432 },
-    };
-
-    struct boot_req req = {
-        .br_area_descs = boot_test_area_descs,
-        .br_slot_areas = boot_test_slot_areas,
-        .br_num_image_areas = BOOT_TEST_AREA_IDX_SCRATCH + 1,
-        .br_scratch_area_idx = BOOT_TEST_AREA_IDX_SCRATCH,
-        .br_img_sz = (384 * 1024),
-    };
-
-    boot_test_util_init_flash();
-    boot_test_util_write_image(&hdr0, 0);
-    boot_test_util_write_hash(&hdr0, 0);
-    boot_test_util_write_image(&hdr1, 1);
-    boot_test_util_write_hash(&hdr1, 1);
-
-    rc = boot_vect_write_test(FLASH_AREA_IMAGE_1);
-    TEST_ASSERT(rc == 0);
-
-    rc = boot_go(&req, &rsp);
-    TEST_ASSERT(rc == 0);
-
-    TEST_ASSERT(memcmp(rsp.br_hdr, &hdr1, sizeof hdr1) == 0);
-    TEST_ASSERT(rsp.br_flash_id == boot_test_img_addrs[0].flash_id);
-    TEST_ASSERT(rsp.br_image_addr == boot_test_img_addrs[0].address);
-
-    boot_test_util_verify_flash(&hdr1, 1, &hdr0, 0);
-    boot_test_util_verify_status_clear();
-}
-
-TEST_CASE(boot_test_nv_bs_10)
-{
-    struct boot_status status;
-    struct boot_rsp rsp;
-    int rc;
-
-    struct image_header hdr = {
-        .ih_magic = IMAGE_MAGIC,
-        .ih_tlv_size = 4 + 32,
-        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
-        .ih_img_size = 12 * 1024,
-        .ih_flags = IMAGE_F_SHA256,
-        .ih_ver = { 0, 2, 3, 4 },
-    };
-
-    struct boot_req req = {
-        .br_area_descs = boot_test_area_descs,
-        .br_slot_areas = boot_test_slot_areas,
-        .br_num_image_areas = BOOT_TEST_AREA_IDX_SCRATCH + 1,
-        .br_scratch_area_idx = BOOT_TEST_AREA_IDX_SCRATCH,
-        .br_img_sz = (384 * 1024),
-    };
-
-    boot_test_util_init_flash();
-    boot_test_util_write_image(&hdr, 0);
-    boot_test_util_write_hash(&hdr, 0);
-    boot_test_util_swap_areas(boot_test_slot_areas[1],
-      BOOT_TEST_AREA_IDX_SCRATCH);
-#if 0
-    status.length = hdr.ih_hdr_size + hdr.ih_img_size + hdr.ih_tlv_size;
-    status.state = 1;
-
-    rc = boot_write_status(&status);
-    TEST_ASSERT(rc == 0);
-    conf_load();
-#else
-    (void)status;
-#endif
-    rc = boot_go(&req, &rsp);
-    TEST_ASSERT(rc == 0);
-
-    TEST_ASSERT(memcmp(rsp.br_hdr, &hdr, sizeof hdr) == 0);
-    TEST_ASSERT(rsp.br_flash_id == boot_test_img_addrs[0].flash_id);
-    TEST_ASSERT(rsp.br_image_addr == boot_test_img_addrs[0].address);
-
-    boot_test_util_verify_flash(&hdr, 0, NULL, 0xff);
-    boot_test_util_verify_status_clear();
-}
-
-TEST_CASE(boot_test_nv_bs_11)
-{
-    struct boot_status status;
-    struct boot_rsp rsp;
-    int rc;
-
-    struct image_header hdr0 = {
-        .ih_magic = IMAGE_MAGIC,
-        .ih_tlv_size = 4 + 32,
-        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
-        .ih_img_size = 12 * 1024,
-        .ih_flags = IMAGE_F_SHA256,
-        .ih_ver = { 0, 2, 3, 4 },
-    };
-
-    struct image_header hdr1 = {
-        .ih_magic = IMAGE_MAGIC,
-        .ih_tlv_size = 4 + 32,
-        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
-        .ih_img_size = 17 * 1024,
-        .ih_flags = IMAGE_F_SHA256,
-        .ih_ver = { 1, 1, 5, 5 },
-    };
-
-    struct boot_req req = {
-        .br_area_descs = boot_test_area_descs,
-        .br_slot_areas = boot_test_slot_areas,
-        .br_num_image_areas = BOOT_TEST_AREA_IDX_SCRATCH + 1,
-        .br_scratch_area_idx = BOOT_TEST_AREA_IDX_SCRATCH,
-        .br_img_sz = (384 * 1024),
-    };
-
-    boot_test_util_init_flash();
-    boot_test_util_write_image(&hdr0, 0);
-    boot_test_util_write_hash(&hdr0, 0);
-    boot_test_util_write_image(&hdr1, 1);
-    boot_test_util_write_hash(&hdr1, 1);
-    rc = boot_vect_write_test(FLASH_AREA_IMAGE_1);
-    boot_test_util_copy_area(5,
-      BOOT_TEST_AREA_IDX_SCRATCH);
-
-    boot_req_set(&req);
-    status.idx = 0;
-    status.elem_sz = 1;
-    status.state = 1;
-
-    rc = boot_write_status(&status);
-    TEST_ASSERT(rc == 0);
-
-    rc = boot_go(&req, &rsp);
-    TEST_ASSERT(rc == 0);
-
-    TEST_ASSERT(memcmp(rsp.br_hdr, &hdr1, sizeof hdr1) == 0);
-    TEST_ASSERT(rsp.br_flash_id == boot_test_img_addrs[0].flash_id);
-    TEST_ASSERT(rsp.br_image_addr == boot_test_img_addrs[0].address);
-
-    boot_test_util_verify_flash(&hdr1, 1, &hdr0, 0);
-    boot_test_util_verify_status_clear();
-}
-
-TEST_CASE(boot_test_nv_bs_11_2areas)
-{
-    struct boot_status status;
-    struct boot_rsp rsp;
-    int rc;
-
-    struct image_header hdr0 = {
-        .ih_magic = IMAGE_MAGIC,
-        .ih_tlv_size = 4 + 32,
-        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
-        .ih_img_size = 150 * 1024,
-        .ih_flags = IMAGE_F_SHA256,
-        .ih_ver = { 0, 5, 21, 432 },
-    };
-
-    struct image_header hdr1 = {
-        .ih_magic = IMAGE_MAGIC,
-        .ih_tlv_size = 4 + 32,
-        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
-        .ih_img_size = 190 * 1024,
-        .ih_flags = IMAGE_F_SHA256,
-        .ih_ver = { 1, 2, 3, 432 },
-    };
-
-    struct boot_req req = {
-        .br_area_descs = boot_test_area_descs,
-        .br_slot_areas = boot_test_slot_areas,
-        .br_num_image_areas = BOOT_TEST_AREA_IDX_SCRATCH + 1,
-        .br_scratch_area_idx = BOOT_TEST_AREA_IDX_SCRATCH,
-        .br_img_sz = (384 * 1024),
-    };
-
-    boot_test_util_init_flash();
-    boot_test_util_write_image(&hdr0, 0);
-    boot_test_util_write_hash(&hdr0, 0);
-    boot_test_util_write_image(&hdr1, 1);
-    boot_test_util_write_hash(&hdr1, 1);
-    rc = boot_vect_write_test(FLASH_AREA_IMAGE_1);
-
-    boot_test_util_swap_areas(2, 5);
-
-    status.idx = 1;
-    status.elem_sz = 1;
-    status.state = 0;
-
-    rc = boot_write_status(&status);
-    TEST_ASSERT(rc == 0);
-
-    rc = boot_go(&req, &rsp);
-    TEST_ASSERT(rc == 0);
-
-    TEST_ASSERT(memcmp(rsp.br_hdr, &hdr1, sizeof hdr1) == 0);
-    TEST_ASSERT(rsp.br_flash_id == boot_test_img_addrs[0].flash_id);
-    TEST_ASSERT(rsp.br_image_addr == boot_test_img_addrs[0].address);
-
-    boot_test_util_verify_flash(&hdr1, 1, &hdr0, 0);
-    boot_test_util_verify_status_clear();
-}
-
-TEST_CASE(boot_test_vb_ns_11)
-{
-    const struct flash_area *fap;
-    struct boot_img_trailer bit;
-    struct boot_rsp rsp;
-    int rc;
-    int i;
-
-    struct image_header hdr0 = {
-        .ih_magic = IMAGE_MAGIC,
-        .ih_tlv_size = 4 + 32,
-        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
-        .ih_img_size = 5 * 1024,
-        .ih_flags = IMAGE_F_SHA256,
-        .ih_ver = { 0, 5, 21, 432 },
-    };
-
-    struct image_header hdr1 = {
-        .ih_magic = IMAGE_MAGIC,
-        .ih_tlv_size = 4 + 32,
-        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
-        .ih_img_size = 32 * 1024,
-        .ih_flags = IMAGE_F_SHA256,
-        .ih_ver = { 1, 2, 3, 432 },
-    };
-
-    struct boot_req req = {
-        .br_area_descs = boot_test_area_descs,
-        .br_slot_areas = boot_test_slot_areas,
-        .br_num_image_areas = BOOT_TEST_AREA_IDX_SCRATCH + 1,
-        .br_scratch_area_idx = BOOT_TEST_AREA_IDX_SCRATCH,
-        .br_img_sz = (384 * 1024),
-    };
-
-    boot_test_util_init_flash();
-    boot_test_util_write_image(&hdr0, 0);
-    boot_test_util_write_hash(&hdr0, 0);
-    boot_test_util_write_image(&hdr1, 1);
-    boot_test_util_write_hash(&hdr1, 1);
-
-    rc = flash_area_open(FLASH_AREA_IMAGE_0, &fap);
-    TEST_ASSERT(rc == 0);
-
-    memset(&bit, 0xff, sizeof(bit));
-    bit.bit_copy_start = BOOT_IMG_MAGIC;
-    bit.bit_copy_done = 0;
-    bit.bit_img_ok = 1;
-
-    rc = flash_area_write(fap, fap->fa_size - sizeof(bit), &bit, sizeof(bit));
-    TEST_ASSERT(rc == 0);
-
-    rc = boot_vect_write_test(FLASH_AREA_IMAGE_1);
-    TEST_ASSERT(rc == 0);
-
-    /* First boot should use the test image. */
-    rc = boot_go(&req, &rsp);
-    TEST_ASSERT(rc == 0);
-
-    TEST_ASSERT(memcmp(rsp.br_hdr, &hdr1, sizeof hdr1) == 0);
-    TEST_ASSERT(rsp.br_flash_id == boot_test_img_addrs[0].flash_id);
-    TEST_ASSERT(rsp.br_image_addr == boot_test_img_addrs[0].address);
-
-    boot_test_util_verify_flash(&hdr1, 1, &hdr0, 0);
-    boot_test_util_verify_status_clear();
-
-    /* Ensure all subsequent boots use the main image. */
-    for (i = 0; i < 10; i++) {
-        rc = boot_go(&req, &rsp);
-        TEST_ASSERT(rc == 0);
-
-        TEST_ASSERT(memcmp(rsp.br_hdr, &hdr0, sizeof hdr0) == 0);
-        TEST_ASSERT(rsp.br_flash_id == boot_test_img_addrs[0].flash_id);
-        TEST_ASSERT(rsp.br_image_addr == boot_test_img_addrs[0].address);
-
-        boot_test_util_verify_flash(&hdr0, 0, &hdr1, 1);
-        boot_test_util_verify_status_clear();
-        boot_vect_write_main();
-    }
-}
-
-TEST_CASE(boot_test_no_hash)
-{
-    struct boot_rsp rsp;
-    int rc;
-
-    struct image_header hdr0 = {
-        .ih_magic = IMAGE_MAGIC,
-        .ih_tlv_size = 4 + 32,
-        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
-        .ih_img_size = 12 * 1024,
-        .ih_flags = IMAGE_F_SHA256,
-        .ih_ver = { 0, 2, 3, 4 },
-    };
-    struct image_header hdr1 = {
-        .ih_magic = IMAGE_MAGIC,
-        .ih_tlv_size = 0,
-        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
-        .ih_img_size = 32 * 1024,
-        .ih_flags = 0,
-        .ih_ver = { 1, 2, 3, 432 },
-    };
-
-    struct boot_req req = {
-        .br_area_descs = boot_test_area_descs,
-        .br_slot_areas = boot_test_slot_areas,
-        .br_num_image_areas = BOOT_TEST_AREA_IDX_SCRATCH + 1,
-        .br_scratch_area_idx = BOOT_TEST_AREA_IDX_SCRATCH,
-        .br_img_sz = (384 * 1024),
-    };
-
-    boot_test_util_init_flash();
-    boot_test_util_write_image(&hdr0, 0);
-    boot_test_util_write_hash(&hdr0, 0);
-    boot_test_util_write_image(&hdr1, 1);
-
-    rc = boot_vect_write_test(FLASH_AREA_IMAGE_1);
-    TEST_ASSERT(rc == 0);
-
-    rc = boot_go(&req, &rsp);
-    TEST_ASSERT(rc == 0);
-
-    TEST_ASSERT(memcmp(rsp.br_hdr, &hdr0, sizeof hdr0) == 0);
-
-    boot_test_util_verify_flash(&hdr0, 0, NULL, 0xff);
-    boot_test_util_verify_status_clear();
-}
-
-TEST_CASE(boot_test_no_flag_has_hash)
-{
-    struct boot_rsp rsp;
-    int rc;
-
-    struct image_header hdr0 = {
-        .ih_magic = IMAGE_MAGIC,
-        .ih_tlv_size = 4 + 32,
-        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
-        .ih_img_size = 12 * 1024,
-        .ih_flags = IMAGE_F_SHA256,
-        .ih_ver = { 0, 2, 3, 4 },
-    };
-    struct image_header hdr1 = {
-        .ih_magic = IMAGE_MAGIC,
-        .ih_tlv_size = 4 + 32,
-        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
-        .ih_img_size = 32 * 1024,
-        .ih_flags = 0,
-        .ih_ver = { 1, 2, 3, 432 },
-    };
-
-    struct boot_req req = {
-        .br_area_descs = boot_test_area_descs,
-        .br_slot_areas = boot_test_slot_areas,
-        .br_num_image_areas = BOOT_TEST_AREA_IDX_SCRATCH + 1,
-        .br_scratch_area_idx = BOOT_TEST_AREA_IDX_SCRATCH,
-        .br_img_sz = (384 * 1024),
-    };
-
-    boot_test_util_init_flash();
-    boot_test_util_write_image(&hdr0, 0);
-    boot_test_util_write_hash(&hdr0, 0);
-    boot_test_util_write_image(&hdr1, 1);
-    boot_test_util_write_hash(&hdr1, 1);
-
-    rc = boot_vect_write_test(FLASH_AREA_IMAGE_1);
-    TEST_ASSERT(rc == 0);
-
-    rc = boot_go(&req, &rsp);
-    TEST_ASSERT(rc == 0);
-
-    TEST_ASSERT(memcmp(rsp.br_hdr, &hdr0, sizeof hdr0) == 0);
-
-    boot_test_util_verify_flash(&hdr0, 0, NULL, 0xff);
-    boot_test_util_verify_status_clear();
-}
-
-TEST_CASE(boot_test_invalid_hash)
-{
-    struct boot_rsp rsp;
-    int rc;
-
-    struct image_header hdr0 = {
-        .ih_magic = IMAGE_MAGIC,
-        .ih_tlv_size = 4 + 32,
-        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
-        .ih_img_size = 12 * 1024,
-        .ih_flags = IMAGE_F_SHA256,
-        .ih_ver = { 0, 2, 3, 4 },
-    };
-    struct image_header hdr1 = {
-        .ih_magic = IMAGE_MAGIC,
-        .ih_tlv_size = 4 + 32,
-        .ih_hdr_size = BOOT_TEST_HEADER_SIZE,
-        .ih_img_size = 32 * 1024,
-        .ih_flags = 0,
-        .ih_ver = { 1, 2, 3, 432 },
-    };
-
-    struct boot_req req = {
-        .br_area_descs = boot_test_area_descs,
-        .br_slot_areas = boot_test_slot_areas,
-        .br_num_image_areas = BOOT_TEST_AREA_IDX_SCRATCH + 1,
-        .br_scratch_area_idx = BOOT_TEST_AREA_IDX_SCRATCH,
-        .br_img_sz = (384 * 1024),
-    };
-
-    struct image_tlv tlv = {
-        .it_type = IMAGE_TLV_SHA256,
-        .it_len = 32
-    };
-    boot_test_util_init_flash();
-    boot_test_util_write_image(&hdr0, 0);
-    boot_test_util_write_hash(&hdr0, 0);
-    boot_test_util_write_image(&hdr1, 1);
-    rc = hal_flash_write(boot_test_img_addrs[1].flash_id,
-      boot_test_img_addrs[1].address + hdr1.ih_hdr_size + hdr1.ih_img_size,
-      &tlv, sizeof(tlv));
-    TEST_ASSERT(rc == 0);
-
-    rc = boot_vect_write_test(FLASH_AREA_IMAGE_1);
-    TEST_ASSERT(rc == 0);
-
-    rc = boot_go(&req, &rsp);
-    TEST_ASSERT(rc == 0);
-
-    TEST_ASSERT(memcmp(rsp.br_hdr, &hdr0, sizeof hdr0) == 0);
-
-    boot_test_util_verify_flash(&hdr0, 0, NULL, 0xff);
-    boot_test_util_verify_status_clear();
-}
-
-TEST_SUITE(boot_test_main)
-{
-    boot_test_nv_ns_10();
-    boot_test_nv_ns_01();
-    boot_test_nv_ns_11();
-    boot_test_vm_ns_10();
-    boot_test_vm_ns_01();
-    boot_test_vm_ns_11_a();
-    boot_test_vm_ns_11_b();
-    boot_test_vm_ns_11_2areas();
-    boot_test_nv_bs_10();
-    boot_test_nv_bs_11();
-    boot_test_nv_bs_11_2areas();
-    boot_test_vb_ns_11();
-    boot_test_no_hash();
-    boot_test_no_flag_has_hash();
-    boot_test_invalid_hash();
-}
-
-int
-boot_test_all(void)
-{
-    boot_test_main();
-    return tu_any_failed;
-}
-
-#if MYNEWT_VAL(SELFTEST)
-
-int
-main(int argc, char **argv)
-{
-    tu_config.tc_print_results = 1;
-    tu_parse_args(argc, argv);
-
-    tu_init();
-
-    boot_test_all();
-
-    return tu_any_failed;
-}
-
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/cmsis-core/pkg.yml
----------------------------------------------------------------------
diff --git a/libs/cmsis-core/pkg.yml b/libs/cmsis-core/pkg.yml
deleted file mode 100644
index 7c3d5de..0000000
--- a/libs/cmsis-core/pkg.yml
+++ /dev/null
@@ -1,27 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you 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.
-#
-
-pkg.name: libs/cmsis-core
-pkg.description: CMSIS-CORE abstraction layer for Cortex-M processors.
-pkg.author: "Keil"
-pkg.homepage: "http://www.keil.com/pack/doc/CMSIS/Core/html/index.html"
-pkg.keywords:
-    - cmsis
-    - core
-pkg.type: sdk

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/cmsis-core/src/cmsis_nvic.c
----------------------------------------------------------------------
diff --git a/libs/cmsis-core/src/cmsis_nvic.c b/libs/cmsis-core/src/cmsis_nvic.c
deleted file mode 100644
index a350791..0000000
--- a/libs/cmsis-core/src/cmsis_nvic.c
+++ /dev/null
@@ -1,73 +0,0 @@
-/* mbed Microcontroller Library - cmsis_nvic for XXXX
- * Copyright (c) 2009-2011 ARM Limited. All rights reserved.
- *
- * CMSIS-style functionality to support dynamic vectors
- */
-#include "bsp/cmsis_nvic.h"
-
-#ifndef __CORTEX_M
-    #error "Macro __CORTEX_M not defined; must define cortex-m type!"
-#endif
-
-#if (__CORTEX_M == 0) 
-    #ifndef __VTOR_PRESENT
-    /* no VTOR is defined so we assume we can't relocate the vector table */
-    #define __VTOR_PRESENT  (0)
-#endif
-#endif
-
-extern char __isr_vector[];
-extern char __vector_tbl_reloc__[];
-
-void
-NVIC_Relocate(void)
-{
-    uint32_t *current_location;
-    uint32_t *new_location;
-    int i;
-
-    /*
-     * Relocate the vector table from its current position to the position
-     * designated in the linker script.
-     */
-    current_location = (uint32_t *)&__isr_vector;
-    new_location = (uint32_t *)&__vector_tbl_reloc__;
-
-    if (new_location != current_location) {
-        for (i = 0; i < NVIC_NUM_VECTORS; i++) {
-            new_location[i] = current_location[i];
-        }
-    }
-
-    /* Set VTOR except for M0 */
-#if ((__CORTEX_M == 0) && (__VTOR_PRESENT == 0))
-#else
-    SCB->VTOR = (uint32_t)&__vector_tbl_reloc__;
-#endif
-}
-
-void
-NVIC_SetVector(IRQn_Type IRQn, uint32_t vector)
-{
-    uint32_t *vectors;
-#if ((__CORTEX_M == 0) && (__VTOR_PRESENT == 0))
-    vectors = (uint32_t *)&__vector_tbl_reloc__;
-#else
-    vectors = (uint32_t *)SCB->VTOR;
-#endif
-    vectors[IRQn + NVIC_USER_IRQ_OFFSET] = vector;
-    __DMB();
-}
-
-uint32_t
-NVIC_GetVector(IRQn_Type IRQn)
-{
-    uint32_t *vectors;
-#if (__CORTEX_M == 0)
-    vectors = (uint32_t *)&__vector_tbl_reloc__;
-#else
-    vectors = (uint32_t*)SCB->VTOR;
-#endif
-    return vectors[IRQn + NVIC_USER_IRQ_OFFSET];
-}
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/cmsis-core/src/ext/core_ca9.h
----------------------------------------------------------------------
diff --git a/libs/cmsis-core/src/ext/core_ca9.h b/libs/cmsis-core/src/ext/core_ca9.h
deleted file mode 100644
index bae5f65..0000000
--- a/libs/cmsis-core/src/ext/core_ca9.h
+++ /dev/null
@@ -1,271 +0,0 @@
-/**************************************************************************//**
- * @file     core_ca9.h
- * @brief    CMSIS Cortex-A9 Core Peripheral Access Layer Header File
- * @version
- * @date     25 March 2013
- *
- * @note
- *
- ******************************************************************************/
-/* Copyright (c) 2009 - 2012 ARM LIMITED
-
-   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 ARM 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 COPYRIGHT HOLDERS AND CONTRIBUTORS BE
-   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-   POSSIBILITY OF SUCH DAMAGE.
-   ---------------------------------------------------------------------------*/
-
-
-#if defined ( __ICCARM__ )
- #pragma system_include  /* treat file as system include file for MISRA check */
-#endif
-
-#ifdef __cplusplus
- extern "C" {
-#endif
-
-#ifndef __CORE_CA9_H_GENERIC
-#define __CORE_CA9_H_GENERIC
-
-
-/** \page CMSIS_MISRA_Exceptions  MISRA-C:2004 Compliance Exceptions
-  CMSIS violates the following MISRA-C:2004 rules:
-
-   \li Required Rule 8.5, object/function definition in header file.<br>
-     Function definitions in header files are used to allow 'inlining'.
-
-   \li Required Rule 18.4, declaration of union type or object of union type: '{...}'.<br>
-     Unions are used for effective representation of core registers.
-
-   \li Advisory Rule 19.7, Function-like macro defined.<br>
-     Function-like macros are used to allow more efficient code.
- */
-
-
-/*******************************************************************************
- *                 CMSIS definitions
- ******************************************************************************/
-/** \ingroup Cortex_A9
-  @{
- */
-
-/*  CMSIS CA9 definitions */
-#define __CA9_CMSIS_VERSION_MAIN  (0x03)                                   /*!< [31:16] CMSIS HAL main version   */
-#define __CA9_CMSIS_VERSION_SUB   (0x10)                                   /*!< [15:0]  CMSIS HAL sub version    */
-#define __CA9_CMSIS_VERSION       ((__CA9_CMSIS_VERSION_MAIN << 16) | \
-                                    __CA9_CMSIS_VERSION_SUB          )     /*!< CMSIS HAL version number         */
-
-#define __CORTEX_A                (0x09)                                   /*!< Cortex-A Core                    */
-
-
-#if   defined ( __CC_ARM )
-  #define __ASM            __asm                                      /*!< asm keyword for ARM Compiler          */
-  #define __INLINE         __inline                                   /*!< inline keyword for ARM Compiler       */
-  #define __STATIC_INLINE  static __inline
-  #define __STATIC_ASM     static __asm
-
-#elif defined ( __ICCARM__ )
-  #define __ASM            __asm                                      /*!< asm keyword for IAR Compiler          */
-  #define __INLINE         inline                                     /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */
-  #define __STATIC_INLINE  static inline
-  #define __STATIC_ASM     static __asm
-
-#elif defined ( __TMS470__ )
-  #define __ASM            __asm                                      /*!< asm keyword for TI CCS Compiler       */
-  #define __STATIC_INLINE  static inline
-  #define __STATIC_ASM     static __asm
-
-#elif defined ( __GNUC__ )
-  #define __ASM            __asm                                      /*!< asm keyword for GNU Compiler          */
-  #define __INLINE         inline                                     /*!< inline keyword for GNU Compiler       */
-  #define __STATIC_INLINE  static inline
-  #define __STATIC_ASM     static __asm
-
-#elif defined ( __TASKING__ )
-  #define __ASM            __asm                                      /*!< asm keyword for TASKING Compiler      */
-  #define __INLINE         inline                                     /*!< inline keyword for TASKING Compiler   */
-  #define __STATIC_INLINE  static inline
-  #define __STATIC_ASM     static __asm
-
-#endif
-
-/** __FPU_USED indicates whether an FPU is used or not. For this, __FPU_PRESENT has to be checked prior to making use of FPU specific registers and functions.
-*/
-#if defined ( __CC_ARM )
-  #if defined __TARGET_FPU_VFP
-    #if (__FPU_PRESENT == 1)
-      #define __FPU_USED       1
-    #else
-      #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
-      #define __FPU_USED       0
-    #endif
-  #else
-    #define __FPU_USED         0
-  #endif
-
-#elif defined ( __ICCARM__ )
-  #if defined __ARMVFP__
-    #if (__FPU_PRESENT == 1)
-      #define __FPU_USED       1
-    #else
-      #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
-      #define __FPU_USED       0
-    #endif
-  #else
-    #define __FPU_USED         0
-  #endif
-
-#elif defined ( __TMS470__ )
-  #if defined __TI_VFP_SUPPORT__
-    #if (__FPU_PRESENT == 1)
-      #define __FPU_USED       1
-    #else
-      #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
-      #define __FPU_USED       0
-    #endif
-  #else
-    #define __FPU_USED         0
-  #endif
-
-#elif defined ( __GNUC__ )
-  #if defined (__VFP_FP__) && !defined(__SOFTFP__)
-    #if (__FPU_PRESENT == 1)
-      #define __FPU_USED       1
-    #else
-      #warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
-      #define __FPU_USED       0
-    #endif
-  #else
-    #define __FPU_USED         0
-  #endif
-
-#elif defined ( __TASKING__ )
-  #if defined __FPU_VFP__
-    #if (__FPU_PRESENT == 1)
-      #define __FPU_USED       1
-    #else
-      #error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
-      #define __FPU_USED       0
-    #endif
-  #else
-    #define __FPU_USED         0
-  #endif
-#endif
-
-#include <stdint.h>                      /*!< standard types definitions                      */
-#include "core_caInstr.h"                /*!< Core Instruction Access                         */
-#include "core_caFunc.h"                 /*!< Core Function Access                            */
-#include "core_cm4_simd.h"               /*!< Compiler specific SIMD Intrinsics               */
-
-#endif /* __CORE_CA9_H_GENERIC */
-
-#ifndef __CMSIS_GENERIC
-
-#ifndef __CORE_CA9_H_DEPENDANT
-#define __CORE_CA9_H_DEPENDANT
-
-/* check device defines and use defaults */
-#if defined __CHECK_DEVICE_DEFINES
-  #ifndef __CA9_REV
-    #define __CA9_REV               0x0000
-    #warning "__CA9_REV not defined in device header file; using default!"
-  #endif
-
-  #ifndef __FPU_PRESENT
-    #define __FPU_PRESENT             1
-    #warning "__FPU_PRESENT not defined in device header file; using default!"
-  #endif
-
-  #ifndef __Vendor_SysTickConfig
-    #define __Vendor_SysTickConfig    1
-  #endif
-
-  #if __Vendor_SysTickConfig == 0
-    #error "__Vendor_SysTickConfig set to 0, but vendor systick timer must be supplied for Cortex-A9"
-  #endif
-#endif
-
-/* IO definitions (access restrictions to peripheral registers) */
-/**
-    \defgroup CMSIS_glob_defs CMSIS Global Defines
-
-    <strong>IO Type Qualifiers</strong> are used
-    \li to specify the access to peripheral variables.
-    \li for automatic generation of peripheral register debug information.
-*/
-#ifdef __cplusplus
-  #define   __I     volatile             /*!< Defines 'read only' permissions                 */
-#else
-  #define   __I     volatile const       /*!< Defines 'read only' permissions                 */
-#endif
-#define     __O     volatile             /*!< Defines 'write only' permissions                */
-#define     __IO    volatile             /*!< Defines 'read / write' permissions              */
-
-/*@} end of group Cortex_A9 */
-
-
-/*******************************************************************************
- *                 Register Abstraction
- ******************************************************************************/
-/** \defgroup CMSIS_core_register Defines and Type Definitions
-    \brief Type definitions and defines for Cortex-A processor based devices.
-*/
-
-/** \ingroup    CMSIS_core_register
-    \defgroup   CMSIS_CORE  Status and Control Registers
-    \brief  Core Register type definitions.
-  @{
- */
-
-/** \brief  Union type to access the Application Program Status Register (APSR).
- */
-typedef union
-{
-  struct
-  {
-    uint32_t _reserved0:16;              /*!< bit:  0..15  Reserved                           */
-    uint32_t GE:4;                       /*!< bit: 16..19  Greater than or Equal flags        */
-    uint32_t reserved1:7;                /*!< bit: 20..23  Reserved                           */
-    uint32_t Q:1;                        /*!< bit:     27  Saturation condition flag          */
-    uint32_t V:1;                        /*!< bit:     28  Overflow condition code flag       */
-    uint32_t C:1;                        /*!< bit:     29  Carry condition code flag          */
-    uint32_t Z:1;                        /*!< bit:     30  Zero condition code flag           */
-    uint32_t N:1;                        /*!< bit:     31  Negative condition code flag       */
-  } b;                                   /*!< Structure used for bit  access                  */
-  uint32_t w;                            /*!< Type      used for word access                  */ 
-} APSR_Type;
-
-
-/*@} end of group CMSIS_CORE */
-
-/*@} end of CMSIS_Core_FPUFunctions */
-
-
-#endif /* __CORE_CA9_H_GENERIC */
-
-#endif /* __CMSIS_GENERIC */
-
-#ifdef __cplusplus
-}
-
-
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/cmsis-core/src/ext/core_caFunc.h
----------------------------------------------------------------------
diff --git a/libs/cmsis-core/src/ext/core_caFunc.h b/libs/cmsis-core/src/ext/core_caFunc.h
deleted file mode 100644
index 3f40094..0000000
--- a/libs/cmsis-core/src/ext/core_caFunc.h
+++ /dev/null
@@ -1,1161 +0,0 @@
-/**************************************************************************//**
- * @file     core_caFunc.h
- * @brief    CMSIS Cortex-A Core Function Access Header File
- * @version  V3.10
- * @date     9 May 2013
- *
- * @note
- *
- ******************************************************************************/
-/* Copyright (c) 2009 - 2012 ARM LIMITED
-
-   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 ARM 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 COPYRIGHT HOLDERS AND 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.
-   ---------------------------------------------------------------------------*/
-
-
-#ifndef __CORE_CAFUNC_H__
-#define __CORE_CAFUNC_H__
-
-
-/* ###########################  Core Function Access  ########################### */
-/** \ingroup  CMSIS_Core_FunctionInterface
-    \defgroup CMSIS_Core_RegAccFunctions CMSIS Core Register Access Functions
-  @{
- */
-
-#if   defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/
-/* ARM armcc specific functions */
-
-#if (__ARMCC_VERSION < 400677)
-  #error "Please use ARM Compiler Toolchain V4.0.677 or later!"
-#endif
-
-#define MODE_USR 0x10
-#define MODE_FIQ 0x11
-#define MODE_IRQ 0x12
-#define MODE_SVC 0x13
-#define MODE_MON 0x16
-#define MODE_ABT 0x17
-#define MODE_HYP 0x1A
-#define MODE_UND 0x1B
-#define MODE_SYS 0x1F
-
-/** \brief  Get APSR Register
-
-    This function returns the content of the APSR Register.
-
-    \return               APSR Register value
- */
-__STATIC_INLINE uint32_t __get_APSR(void)
-{
-  register uint32_t __regAPSR          __ASM("apsr");
-  return(__regAPSR);
-}
-
-
-/** \brief  Get CPSR Register
-
-    This function returns the content of the CPSR Register.
-
-    \return               CPSR Register value
- */
-__STATIC_INLINE uint32_t __get_CPSR(void)
-{
-  register uint32_t __regCPSR          __ASM("cpsr");
-  return(__regCPSR);
-}
-
-/** \brief  Set Stack Pointer
-
-    This function assigns the given value to the current stack pointer.
-
-    \param [in]    topOfStack  Stack Pointer value to set
- */
-register uint32_t __regSP              __ASM("sp");
-__STATIC_INLINE void __set_SP(uint32_t topOfStack)
-{
-    __regSP = topOfStack;
-}
-
-
-/** \brief  Get link register
-
-    This function returns the value of the link register
-
-    \return    Value of link register
- */
-register uint32_t __reglr         __ASM("lr");
-__STATIC_INLINE uint32_t __get_LR(void)
-{
-  return(__reglr);
-}
-
-/** \brief  Set link register
-
-    This function sets the value of the link register
-
-    \param [in]    lr  LR value to set
- */
-__STATIC_INLINE void __set_LR(uint32_t lr)
-{
-  __reglr = lr;
-}
-
-/** \brief  Set Process Stack Pointer
-
-    This function assigns the given value to the USR/SYS Stack Pointer (PSP).
-
-    \param [in]    topOfProcStack  USR/SYS Stack Pointer value to set
- */
-__STATIC_ASM void __set_PSP(uint32_t topOfProcStack)
-{
-    ARM
-    PRESERVE8
-
-    BIC     R0, R0, #7  ;ensure stack is 8-byte aligned
-    MRS     R1, CPSR
-    CPS     #MODE_SYS   ;no effect in USR mode
-    MOV     SP, R0
-    MSR     CPSR_c, R1  ;no effect in USR mode
-    ISB
-    BX      LR
-
-}
-
-/** \brief  Set User Mode
-
-    This function changes the processor state to User Mode
-
-    \param [in]    topOfProcStack  USR/SYS Stack Pointer value to set
- */
-__STATIC_ASM void __set_CPS_USR(void)
-{
-    ARM 
-
-    CPS  #MODE_USR  
-    BX   LR
-}
-
-
-/** \brief  Enable FIQ
-
-    This function enables FIQ interrupts by clearing the F-bit in the CPSR.
-    Can only be executed in Privileged modes.
- */
-#define __enable_fault_irq                __enable_fiq
-
-
-/** \brief  Disable FIQ
-
-    This function disables FIQ interrupts by setting the F-bit in the CPSR.
-    Can only be executed in Privileged modes.
- */
-#define __disable_fault_irq               __disable_fiq
-
-
-/** \brief  Get FPSCR
-
-    This function returns the current value of the Floating Point Status/Control register.
-
-    \return               Floating Point Status/Control register value
- */
-__STATIC_INLINE uint32_t __get_FPSCR(void)
-{
-#if (__FPU_PRESENT == 1) && (__FPU_USED == 1)
-  register uint32_t __regfpscr         __ASM("fpscr");
-  return(__regfpscr);
-#else
-   return(0);
-#endif
-}
-
-
-/** \brief  Set FPSCR
-
-    This function assigns the given value to the Floating Point Status/Control register.
-
-    \param [in]    fpscr  Floating Point Status/Control value to set
- */
-__STATIC_INLINE void __set_FPSCR(uint32_t fpscr)
-{
-#if (__FPU_PRESENT == 1) && (__FPU_USED == 1)
-  register uint32_t __regfpscr         __ASM("fpscr");
-  __regfpscr = (fpscr);
-#endif
-}
-
-/** \brief  Get FPEXC
-
-    This function returns the current value of the Floating Point Exception Control register.
-
-    \return               Floating Point Exception Control register value
- */
-__STATIC_INLINE uint32_t __get_FPEXC(void)
-{
-#if (__FPU_PRESENT == 1)
-  register uint32_t __regfpexc         __ASM("fpexc");
-  return(__regfpexc);
-#else
-   return(0);
-#endif
-}
-
-
-/** \brief  Set FPEXC
-
-    This function assigns the given value to the Floating Point Exception Control register.
-
-    \param [in]    fpscr  Floating Point Exception Control value to set
- */
-__STATIC_INLINE void __set_FPEXC(uint32_t fpexc)
-{
-#if (__FPU_PRESENT == 1)
-  register uint32_t __regfpexc         __ASM("fpexc");
-  __regfpexc = (fpexc);
-#endif
-}
-
-/** \brief  Get CPACR
-
-    This function returns the current value of the Coprocessor Access Control register.
-
-    \return               Coprocessor Access Control register value
- */
-__STATIC_INLINE uint32_t __get_CPACR(void)
-{
-    register uint32_t __regCPACR         __ASM("cp15:0:c1:c0:2");
-    return __regCPACR;
-}
-
-/** \brief  Set CPACR
-
-    This function assigns the given value to the Coprocessor Access Control register.
-
-    \param [in]    cpacr  Coporcessor Acccess Control value to set
- */
-__STATIC_INLINE void __set_CPACR(uint32_t cpacr)
-{
-    register uint32_t __regCPACR         __ASM("cp15:0:c1:c0:2");
-    __regCPACR = cpacr;
-    __ISB();
-}
-
-/** \brief  Get CBAR
-
-    This function returns the value of the Configuration Base Address register.
-
-    \return               Configuration Base Address register value
- */
-__STATIC_INLINE uint32_t __get_CBAR() {
-    register uint32_t __regCBAR         __ASM("cp15:4:c15:c0:0");
-    return(__regCBAR);
-}
-
-/** \brief  Get TTBR0
-
-    This function returns the value of the Configuration Base Address register.
-
-    \return               Translation Table Base Register 0 value
- */
-__STATIC_INLINE uint32_t __get_TTBR0() {
-    register uint32_t __regTTBR0        __ASM("cp15:0:c2:c0:0");
-    return(__regTTBR0);
-}
-
-/** \brief  Set TTBR0
-
-    This function assigns the given value to the Coprocessor Access Control register.
-
-    \param [in]    ttbr0  Translation Table Base Register 0 value to set
- */
-__STATIC_INLINE void __set_TTBR0(uint32_t ttbr0) {
-    register uint32_t __regTTBR0        __ASM("cp15:0:c2:c0:0");
-    __regTTBR0 = ttbr0;
-    __ISB();
-}
-
-/** \brief  Get DACR
-
-    This function returns the value of the Domain Access Control Register.
-
-    \return               Domain Access Control Register value
- */
-__STATIC_INLINE uint32_t __get_DACR() {
-    register uint32_t __regDACR         __ASM("cp15:0:c3:c0:0");
-    return(__regDACR);
-}
-
-/** \brief  Set DACR
-
-    This function assigns the given value to the Coprocessor Access Control register.
-
-    \param [in]    dacr   Domain Access Control Register value to set
- */
-__STATIC_INLINE void __set_DACR(uint32_t dacr) {
-    register uint32_t __regDACR         __ASM("cp15:0:c3:c0:0");
-    __regDACR = dacr;
-    __ISB();
-}
-
-/******************************** Cache and BTAC enable  ****************************************************/
-
-/** \brief  Set SCTLR
-
-    This function assigns the given value to the System Control Register.
-
-    \param [in]    sctlr  System Control Register, value to set
- */
-__STATIC_INLINE void __set_SCTLR(uint32_t sctlr)
-{
-    register uint32_t __regSCTLR         __ASM("cp15:0:c1:c0:0");
-    __regSCTLR = sctlr;
-}
-
-/** \brief  Get SCTLR
-
-    This function returns the value of the System Control Register.
-
-    \return               System Control Register value
- */
-__STATIC_INLINE uint32_t __get_SCTLR() {
-    register uint32_t __regSCTLR         __ASM("cp15:0:c1:c0:0");
-    return(__regSCTLR);
-}
-
-/** \brief  Enable Caches
-
-    Enable Caches
- */
-__STATIC_INLINE void __enable_caches(void) {
-    // Set I bit 12 to enable I Cache
-    // Set C bit  2 to enable D Cache
-    __set_SCTLR( __get_SCTLR() | (1 << 12) | (1 << 2));
-}
-
-/** \brief  Disable Caches
-
-    Disable Caches
- */
-__STATIC_INLINE void __disable_caches(void) {
-    // Clear I bit 12 to disable I Cache
-    // Clear C bit  2 to disable D Cache
-    __set_SCTLR( __get_SCTLR() & ~(1 << 12) & ~(1 << 2));
-    __ISB();
-}
-
-/** \brief  Enable BTAC
-
-    Enable BTAC
- */
-__STATIC_INLINE void __enable_btac(void) {
-    // Set Z bit 11 to enable branch prediction
-    __set_SCTLR( __get_SCTLR() | (1 << 11));
-    __ISB();
-}
-
-/** \brief  Disable BTAC
-
-    Disable BTAC
- */
-__STATIC_INLINE void __disable_btac(void) {
-    // Clear Z bit 11 to disable branch prediction
-    __set_SCTLR( __get_SCTLR() & ~(1 << 11));
-}
-
-
-/** \brief  Enable MMU
-
-    Enable MMU
- */
-__STATIC_INLINE void __enable_mmu(void) {
-    // Set M bit 0 to enable the MMU
-    // Set AFE bit to enable simplified access permissions model
-    // Clear TRE bit to disable TEX remap and A bit to disable strict alignment fault checking
-    __set_SCTLR( (__get_SCTLR() & ~(1 << 28) & ~(1 << 1)) | 1 | (1 << 29));
-    __ISB();
-}
-
-/** \brief  Enable MMU
-
-    Enable MMU
- */
-__STATIC_INLINE void __disable_mmu(void) {
-    // Clear M bit 0 to disable the MMU
-    __set_SCTLR( __get_SCTLR() & ~1);
-    __ISB();
-}
-
-/******************************** TLB maintenance operations ************************************************/
-/** \brief  Invalidate the whole tlb
-
-    TLBIALL. Invalidate the whole tlb
- */
-
-__STATIC_INLINE void __ca9u_inv_tlb_all(void) {
-    register uint32_t __TLBIALL         __ASM("cp15:0:c8:c7:0");
-    __TLBIALL = 0;
-    __DSB();
-    __ISB();
-}
-
-/******************************** BTB maintenance operations ************************************************/
-/** \brief  Invalidate entire branch predictor array
-
-    BPIALL. Branch Predictor Invalidate All.
- */
-
-__STATIC_INLINE void __v7_inv_btac(void) {
-    register uint32_t __BPIALL          __ASM("cp15:0:c7:c5:6");
-    __BPIALL  = 0;
-    __DSB();     //ensure completion of the invalidation
-    __ISB();     //ensure instruction fetch path sees new state
-}
-
-
-/******************************** L1 cache operations ******************************************************/
-
-/** \brief  Invalidate the whole I$
-
-    ICIALLU. Instruction Cache Invalidate All to PoU
- */
-__STATIC_INLINE void __v7_inv_icache_all(void) {
-    register uint32_t __ICIALLU         __ASM("cp15:0:c7:c5:0");
-    __ICIALLU = 0;
-    __DSB();     //ensure completion of the invalidation
-    __ISB();     //ensure instruction fetch path sees new I cache state
-}
-
-/** \brief  Clean D$ by MVA
-
-    DCCMVAC. Data cache clean by MVA to PoC
- */
-__STATIC_INLINE void __v7_clean_dcache_mva(void *va) {
-    register uint32_t __DCCMVAC         __ASM("cp15:0:c7:c10:1");
-    __DCCMVAC = (uint32_t)va;
-    __DMB();     //ensure the ordering of data cache maintenance operations and their effects
-}
-
-/** \brief  Invalidate D$ by MVA
-
-    DCIMVAC. Data cache invalidate by MVA to PoC
- */
-__STATIC_INLINE void __v7_inv_dcache_mva(void *va) {
-    register uint32_t __DCIMVAC         __ASM("cp15:0:c7:c6:1");
-    __DCIMVAC = (uint32_t)va;
-    __DMB();     //ensure the ordering of data cache maintenance operations and their effects
-}
-
-/** \brief  Clean and Invalidate D$ by MVA
-
-    DCCIMVAC. Data cache clean and invalidate by MVA to PoC
- */
-__STATIC_INLINE void __v7_clean_inv_dcache_mva(void *va) {
-    register uint32_t __DCCIMVAC        __ASM("cp15:0:c7:c14:1");
-    __DCCIMVAC = (uint32_t)va;
-    __DMB();     //ensure the ordering of data cache maintenance operations and their effects
-}
-
-/** \brief
- * Generic mechanism for cleaning/invalidating the entire data or unified cache to the point of coherency.
- */
-#pragma push
-#pragma arm
-__STATIC_ASM void __v7_all_cache(uint32_t op) {
-        ARM 
-
-        PUSH    {R4-R11}
-
-        MRC     p15, 1, R6, c0, c0, 1      // Read CLIDR
-        ANDS    R3, R6, #0x07000000        // Extract coherency level
-        MOV     R3, R3, LSR #23            // Total cache levels << 1
-        BEQ     Finished                   // If 0, no need to clean
-
-        MOV     R10, #0                    // R10 holds current cache level << 1
-Loop1   ADD     R2, R10, R10, LSR #1       // R2 holds cache "Set" position
-        MOV     R1, R6, LSR R2             // Bottom 3 bits are the Cache-type for this level
-        AND     R1, R1, #7                 // Isolate those lower 3 bits
-        CMP     R1, #2
-        BLT     Skip                       // No cache or only instruction cache at this level
-
-        MCR     p15, 2, R10, c0, c0, 0     // Write the Cache Size selection register
-        ISB                                // ISB to sync the change to the CacheSizeID reg
-        MRC     p15, 1, R1, c0, c0, 0      // Reads current Cache Size ID register
-        AND     R2, R1, #7                 // Extract the line length field
-        ADD     R2, R2, #4                 // Add 4 for the line length offset (log2 16 bytes)
-        LDR     R4, =0x3FF
-        ANDS    R4, R4, R1, LSR #3         // R4 is the max number on the way size (right aligned)
-        CLZ     R5, R4                     // R5 is the bit position of the way size increment
-        LDR     R7, =0x7FFF
-        ANDS    R7, R7, R1, LSR #13        // R7 is the max number of the index size (right aligned)
-
-Loop2   MOV     R9, R4                     // R9 working copy of the max way size (right aligned)
-
-Loop3   ORR     R11, R10, R9, LSL R5       // Factor in the Way number and cache number into R11
-        ORR     R11, R11, R7, LSL R2       // Factor in the Set number
-        CMP     R0, #0
-        BNE     Dccsw
-        MCR     p15, 0, R11, c7, c6, 2     // DCISW. Invalidate by Set/Way
-        B       cont
-Dccsw   CMP     R0, #1
-        BNE     Dccisw
-        MCR     p15, 0, R11, c7, c10, 2    // DCCSW. Clean by Set/Way
-        B       cont
-Dccisw  MCR     p15, 0, R11, c7, c14, 2    // DCCISW, Clean and Invalidate by Set/Way
-cont    SUBS    R9, R9, #1                 // Decrement the Way number
-        BGE     Loop3
-        SUBS    R7, R7, #1                 // Decrement the Set number
-        BGE     Loop2
-Skip    ADD     R10, R10, #2               // increment the cache number
-        CMP     R3, R10
-        BGT     Loop1
-
-Finished
-        DSB
-        POP    {R4-R11}
-        BX     lr
-
-}
-#pragma pop
-
-/** \brief  __v7_all_cache - helper function
-
- */
-
-/** \brief  Invalidate the whole D$
-
-    DCISW. Invalidate by Set/Way
- */
-
-__STATIC_INLINE void __v7_inv_dcache_all(void) {
-    __v7_all_cache(0);
-}
-
-/** \brief  Clean the whole D$
-
-    DCCSW. Clean by Set/Way
- */
-
-__STATIC_INLINE void __v7_clean_dcache_all(void) {
-    __v7_all_cache(1);
-}
-
-/** \brief  Clean and invalidate the whole D$
-
-    DCCISW. Clean and Invalidate by Set/Way
- */
-
-__STATIC_INLINE void __v7_clean_inv_dcache_all(void) {
-    __v7_all_cache(2);
-}
-
-#include "core_ca_mmu.h"
-
-#elif (defined (__ICCARM__)) /*---------------- ICC Compiler ---------------------*/
-
-#error IAR Compiler support not implemented for Cortex-A
-
-#elif (defined (__GNUC__)) /*------------------ GNU Compiler ---------------------*/
-
-/* GNU gcc specific functions */
-
-#define MODE_USR 0x10
-#define MODE_FIQ 0x11
-#define MODE_IRQ 0x12
-#define MODE_SVC 0x13
-#define MODE_MON 0x16
-#define MODE_ABT 0x17
-#define MODE_HYP 0x1A
-#define MODE_UND 0x1B
-#define MODE_SYS 0x1F
-
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_irq(void)
-{
-    __ASM volatile ("cpsie i");
-}
-
-/** \brief  Disable IRQ Interrupts
-
-  This function disables IRQ interrupts by setting the I-bit in the CPSR.
-  Can only be executed in Privileged modes.
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __disable_irq(void)
-{
-    uint32_t result;
-
-    __ASM volatile ("mrs %0, cpsr" : "=r" (result));
-    __ASM volatile ("cpsid i");
-    return(result & 0x80);
-}
-
-
-/** \brief  Get APSR Register
-
-    This function returns the content of the APSR Register.
-
-    \return               APSR Register value
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_APSR(void)
-{
-#if 1
-    uint32_t result;
-
-    __ASM volatile ("mrs %0, apsr" : "=r" (result) );
-    return (result);
-#else
-  register uint32_t __regAPSR          __ASM("apsr");
-  return(__regAPSR);
-#endif
-}
-
-
-/** \brief  Get CPSR Register
-
-    This function returns the content of the CPSR Register.
-
-    \return               CPSR Register value
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_CPSR(void)
-{
-#if 1
-  register uint32_t __regCPSR;
-  __ASM volatile ("mrs %0, cpsr" : "=r" (__regCPSR));
-#else
-  register uint32_t __regCPSR          __ASM("cpsr");
-#endif
-  return(__regCPSR);
-}
-
-#if 0
-/** \brief  Set Stack Pointer
-
-    This function assigns the given value to the current stack pointer.
-
-    \param [in]    topOfStack  Stack Pointer value to set
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_SP(uint32_t topOfStack)
-{
-    register uint32_t __regSP       __ASM("sp");
-    __regSP = topOfStack;
-}
-#endif
-
-/** \brief  Get link register
-
-    This function returns the value of the link register
-
-    \return    Value of link register
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_LR(void)
-{
-  register uint32_t __reglr         __ASM("lr");
-  return(__reglr);
-}
-
-#if 0
-/** \brief  Set link register
-
-    This function sets the value of the link register
-
-    \param [in]    lr  LR value to set
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_LR(uint32_t lr)
-{
-  register uint32_t __reglr         __ASM("lr");
-  __reglr = lr;
-}
-#endif
-
-/** \brief  Set Process Stack Pointer
-
-    This function assigns the given value to the USR/SYS Stack Pointer (PSP).
-
-    \param [in]    topOfProcStack  USR/SYS Stack Pointer value to set
- */
-extern void __set_PSP(uint32_t topOfProcStack);
-
-/** \brief  Set User Mode
-
-    This function changes the processor state to User Mode
-
-    \param [in]    topOfProcStack  USR/SYS Stack Pointer value to set
- */
-extern void __set_CPS_USR(void);
-
-/** \brief  Enable FIQ
-
-    This function enables FIQ interrupts by clearing the F-bit in the CPSR.
-    Can only be executed in Privileged modes.
- */
-#define __enable_fault_irq                __enable_fiq
-
-
-/** \brief  Disable FIQ
-
-    This function disables FIQ interrupts by setting the F-bit in the CPSR.
-    Can only be executed in Privileged modes.
- */
-#define __disable_fault_irq               __disable_fiq
-
-
-/** \brief  Get FPSCR
-
-    This function returns the current value of the Floating Point Status/Control register.
-
-    \return               Floating Point Status/Control register value
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_FPSCR(void)
-{
-#if (__FPU_PRESENT == 1) && (__FPU_USED == 1)
-#if 1
-    uint32_t result;
-
-    __ASM volatile ("vmrs %0, fpscr" : "=r" (result) );
-    return (result);
-#else
-  register uint32_t __regfpscr         __ASM("fpscr");
-  return(__regfpscr);
-#endif
-#else
-   return(0);
-#endif
-}
-
-
-/** \brief  Set FPSCR
-
-    This function assigns the given value to the Floating Point Status/Control register.
-
-    \param [in]    fpscr  Floating Point Status/Control value to set
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_FPSCR(uint32_t fpscr)
-{
-#if (__FPU_PRESENT == 1) && (__FPU_USED == 1)
-#if 1
-    __ASM volatile ("vmsr fpscr, %0" : : "r" (fpscr) );
-#else
-  register uint32_t __regfpscr         __ASM("fpscr");
-  __regfpscr = (fpscr);
-#endif
-#endif
-}
-
-/** \brief  Get FPEXC
-
-    This function returns the current value of the Floating Point Exception Control register.
-
-    \return               Floating Point Exception Control register value
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_FPEXC(void)
-{
-#if (__FPU_PRESENT == 1)
-#if 1
-    uint32_t result;
-
-    __ASM volatile ("vmrs %0, fpexc" : "=r" (result));
-    return (result);
-#else
-  register uint32_t __regfpexc         __ASM("fpexc");
-  return(__regfpexc);
-#endif
-#else
-   return(0);
-#endif
-}
-
-
-/** \brief  Set FPEXC
-
-    This function assigns the given value to the Floating Point Exception Control register.
-
-    \param [in]    fpscr  Floating Point Exception Control value to set
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_FPEXC(uint32_t fpexc)
-{
-#if (__FPU_PRESENT == 1)
-#if 1
-    __ASM volatile ("vmsr fpexc, %0" : : "r" (fpexc));
-#else
-  register uint32_t __regfpexc         __ASM("fpexc");
-  __regfpexc = (fpexc);
-#endif
-#endif
-}
-
-/** \brief  Get CPACR
-
-    This function returns the current value of the Coprocessor Access Control register.
-
-    \return               Coprocessor Access Control register value
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_CPACR(void)
-{
-#if 1
-    register uint32_t __regCPACR;
-    __ASM volatile ("mrc p15, 0, %0, c1, c0, 2" : "=r" (__regCPACR));
-#else
-    register uint32_t __regCPACR         __ASM("cp15:0:c1:c0:2");
-#endif
-    return __regCPACR;
-}
-
-/** \brief  Set CPACR
-
-    This function assigns the given value to the Coprocessor Access Control register.
-
-    \param [in]    cpacr  Coporcessor Acccess Control value to set
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_CPACR(uint32_t cpacr)
-{
-#if 1
-    __ASM volatile ("mcr p15, 0, %0, c1, c0, 2" : : "r" (cpacr));
-#else
-    register uint32_t __regCPACR         __ASM("cp15:0:c1:c0:2");
-    __regCPACR = cpacr;
-#endif
-    __ISB();
-}
-
-/** \brief  Get CBAR
-
-    This function returns the value of the Configuration Base Address register.
-
-    \return               Configuration Base Address register value
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_CBAR() {
-#if 1
-    register uint32_t __regCBAR;
-    __ASM volatile ("mrc p15, 4, %0, c15, c0, 0" : "=r" (__regCBAR));
-#else
-    register uint32_t __regCBAR         __ASM("cp15:4:c15:c0:0");
-#endif
-    return(__regCBAR);
-}
-
-/** \brief  Get TTBR0
-
-    This function returns the value of the Configuration Base Address register.
-
-    \return               Translation Table Base Register 0 value
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_TTBR0() {
-#if 1
-    register uint32_t __regTTBR0;
-    __ASM volatile ("mrc p15, 0, %0, c2, c0, 0" : "=r" (__regTTBR0));
-#else
-    register uint32_t __regTTBR0        __ASM("cp15:0:c2:c0:0");
-#endif
-    return(__regTTBR0);
-}
-
-/** \brief  Set TTBR0
-
-    This function assigns the given value to the Coprocessor Access Control register.
-
-    \param [in]    ttbr0  Translation Table Base Register 0 value to set
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_TTBR0(uint32_t ttbr0) {
-#if 1
-	__ASM volatile ("mcr p15, 0, %0, c2, c0, 0" : : "r" (ttbr0));
-#else
-    register uint32_t __regTTBR0        __ASM("cp15:0:c2:c0:0");
-    __regTTBR0 = ttbr0;
-#endif
-    __ISB();
-}
-
-/** \brief  Get DACR
-
-    This function returns the value of the Domain Access Control Register.
-
-    \return               Domain Access Control Register value
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_DACR() {
-#if 1
-    register uint32_t __regDACR;
-    __ASM volatile ("mrc p15, 0, %0, c3, c0, 0" : "=r" (__regDACR));
-#else
-    register uint32_t __regDACR         __ASM("cp15:0:c3:c0:0");
-#endif
-    return(__regDACR);
-}
-
-/** \brief  Set DACR
-
-    This function assigns the given value to the Coprocessor Access Control register.
-
-    \param [in]    dacr   Domain Access Control Register value to set
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_DACR(uint32_t dacr) {
-#if 1
-	__ASM volatile ("mcr p15, 0, %0, c3, c0, 0" : : "r" (dacr));
-#else
-    register uint32_t __regDACR         __ASM("cp15:0:c3:c0:0");
-    __regDACR = dacr;
-#endif
-    __ISB();
-}
-
-/******************************** Cache and BTAC enable  ****************************************************/
-
-/** \brief  Set SCTLR
-
-    This function assigns the given value to the System Control Register.
-
-    \param [in]    sctlr  System Control Register, value to set
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_SCTLR(uint32_t sctlr)
-{
-#if 1
-	__ASM volatile ("mcr p15, 0, %0, c1, c0, 0" : : "r" (sctlr));
-#else
-    register uint32_t __regSCTLR         __ASM("cp15:0:c1:c0:0");
-    __regSCTLR = sctlr;
-#endif
-}
-
-/** \brief  Get SCTLR
-
-    This function returns the value of the System Control Register.
-
-    \return               System Control Register value
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_SCTLR() {
-#if 1
-	register uint32_t __regSCTLR;
-	__ASM volatile ("mrc p15, 0, %0, c1, c0, 0" : "=r" (__regSCTLR));
-#else
-    register uint32_t __regSCTLR         __ASM("cp15:0:c1:c0:0");
-#endif
-    return(__regSCTLR);
-}
-
-/** \brief  Enable Caches
-
-    Enable Caches
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_caches(void) {
-    // Set I bit 12 to enable I Cache
-    // Set C bit  2 to enable D Cache
-    __set_SCTLR( __get_SCTLR() | (1 << 12) | (1 << 2));
-}
-
-/** \brief  Disable Caches
-
-    Disable Caches
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_caches(void) {
-    // Clear I bit 12 to disable I Cache
-    // Clear C bit  2 to disable D Cache
-    __set_SCTLR( __get_SCTLR() & ~(1 << 12) & ~(1 << 2));
-    __ISB();
-}
-
-/** \brief  Enable BTAC
-
-    Enable BTAC
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_btac(void) {
-    // Set Z bit 11 to enable branch prediction
-    __set_SCTLR( __get_SCTLR() | (1 << 11));
-    __ISB();
-}
-
-/** \brief  Disable BTAC
-
-    Disable BTAC
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_btac(void) {
-    // Clear Z bit 11 to disable branch prediction
-    __set_SCTLR( __get_SCTLR() & ~(1 << 11));
-}
-
-
-/** \brief  Enable MMU
-
-    Enable MMU
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_mmu(void) {
-    // Set M bit 0 to enable the MMU
-    // Set AFE bit to enable simplified access permissions model
-    // Clear TRE bit to disable TEX remap and A bit to disable strict alignment fault checking
-    __set_SCTLR( (__get_SCTLR() & ~(1 << 28) & ~(1 << 1)) | 1 | (1 << 29));
-    __ISB();
-}
-
-/** \brief  Enable MMU
-
-    Enable MMU
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_mmu(void) {
-    // Clear M bit 0 to disable the MMU
-    __set_SCTLR( __get_SCTLR() & ~1);
-    __ISB();
-}
-
-/******************************** TLB maintenance operations ************************************************/
-/** \brief  Invalidate the whole tlb
-
-    TLBIALL. Invalidate the whole tlb
- */
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE void __ca9u_inv_tlb_all(void) {
-#if 1
-	__ASM volatile ("mcr p15, 0, %0, c8, c7, 0" : : "r" (0));
-#else
-    register uint32_t __TLBIALL         __ASM("cp15:0:c8:c7:0");
-    __TLBIALL = 0;
-#endif
-    __DSB();
-    __ISB();
-}
-
-/******************************** BTB maintenance operations ************************************************/
-/** \brief  Invalidate entire branch predictor array
-
-    BPIALL. Branch Predictor Invalidate All.
- */
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_inv_btac(void) {
-#if 1
-	__ASM volatile ("mcr p15, 0, %0, c7, c5, 6" : : "r" (0));
-#else
-    register uint32_t __BPIALL          __ASM("cp15:0:c7:c5:6");
-    __BPIALL  = 0;
-#endif
-    __DSB();     //ensure completion of the invalidation
-    __ISB();     //ensure instruction fetch path sees new state
-}
-
-
-/******************************** L1 cache operations ******************************************************/
-
-/** \brief  Invalidate the whole I$
-
-    ICIALLU. Instruction Cache Invalidate All to PoU
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_inv_icache_all(void) {
-#if 1
-	__ASM volatile ("mcr p15, 0, %0, c7, c5, 0" : : "r" (0));
-#else
-    register uint32_t __ICIALLU         __ASM("cp15:0:c7:c5:0");
-    __ICIALLU = 0;
-#endif
-    __DSB();     //ensure completion of the invalidation
-    __ISB();     //ensure instruction fetch path sees new I cache state
-}
-
-/** \brief  Clean D$ by MVA
-
-    DCCMVAC. Data cache clean by MVA to PoC
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_clean_dcache_mva(void *va) {
-#if 1
-    __ASM volatile ("mcr p15, 0, %0, c7, c10, 1" : : "r" ((uint32_t)va));
-#else
-    register uint32_t __DCCMVAC         __ASM("cp15:0:c7:c10:1");
-    __DCCMVAC = (uint32_t)va;
-#endif
-    __DMB();     //ensure the ordering of data cache maintenance operations and their effects
-}
-
-/** \brief  Invalidate D$ by MVA
-
-    DCIMVAC. Data cache invalidate by MVA to PoC
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_inv_dcache_mva(void *va) {
-#if 1
-    __ASM volatile ("mcr p15, 0, %0, c7, c6, 1" : : "r" ((uint32_t)va));
-#else
-    register uint32_t __DCIMVAC         __ASM("cp15:0:c7:c6:1");
-    __DCIMVAC = (uint32_t)va;
-#endif
-    __DMB();     //ensure the ordering of data cache maintenance operations and their effects
-}
-
-/** \brief  Clean and Invalidate D$ by MVA
-
-    DCCIMVAC. Data cache clean and invalidate by MVA to PoC
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_clean_inv_dcache_mva(void *va) {
-#if 1
-    __ASM volatile ("mcr p15, 0, %0, c7, c14, 1" : : "r" ((uint32_t)va));
-#else
-    register uint32_t __DCCIMVAC        __ASM("cp15:0:c7:c14:1");
-    __DCCIMVAC = (uint32_t)va;
-#endif
-    __DMB();     //ensure the ordering of data cache maintenance operations and their effects
-}
-
-/** \brief
- * Generic mechanism for cleaning/invalidating the entire data or unified cache to the point of coherency.
- */
-
-/** \brief  __v7_all_cache - helper function
-
- */
-
-extern void __v7_all_cache(uint32_t op);
-
-
-/** \brief  Invalidate the whole D$
-
-    DCISW. Invalidate by Set/Way
- */
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_inv_dcache_all(void) {
-    __v7_all_cache(0);
-}
-
-/** \brief  Clean the whole D$
-
-    DCCSW. Clean by Set/Way
- */
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_clean_dcache_all(void) {
-    __v7_all_cache(1);
-}
-
-/** \brief  Clean and invalidate the whole D$
-
-    DCCISW. Clean and Invalidate by Set/Way
- */
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE void __v7_clean_inv_dcache_all(void) {
-    __v7_all_cache(2);
-}
-
-#include "core_ca_mmu.h"
-
-#elif (defined (__TASKING__)) /*--------------- TASKING Compiler -----------------*/
-
-#error TASKING Compiler support not implemented for Cortex-A
-
-#endif
-
-/*@} end of CMSIS_Core_RegAccFunctions */
-
-
-#endif /* __CORE_CAFUNC_H__ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/cmsis-core/src/ext/core_caInstr.h
----------------------------------------------------------------------
diff --git a/libs/cmsis-core/src/ext/core_caInstr.h b/libs/cmsis-core/src/ext/core_caInstr.h
deleted file mode 100644
index b1d3435..0000000
--- a/libs/cmsis-core/src/ext/core_caInstr.h
+++ /dev/null
@@ -1,45 +0,0 @@
-/**************************************************************************//**
- * @file     core_caInstr.h
- * @brief    CMSIS Cortex-A9 Core Peripheral Access Layer Header File
- * @version
- * @date     04. December 2012
- *
- * @note
- *
- ******************************************************************************/
-/* Copyright (c) 2009 - 2012 ARM LIMITED
-
-   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 ARM 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 COPYRIGHT HOLDERS AND 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.
-   ---------------------------------------------------------------------------*/
-
-#ifndef __CORE_CAINSTR_H__
-#define __CORE_CAINSTR_H__
-
-#define __CORTEX_M 0x3
-#include "core_cmInstr.h"
-#undef  __CORTEX_M
-
-#endif
-


[14/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/src/arch/cortex_m0/os_fault.c
----------------------------------------------------------------------
diff --git a/libs/os/src/arch/cortex_m0/os_fault.c b/libs/os/src/arch/cortex_m0/os_fault.c
deleted file mode 100644
index 4167682..0000000
--- a/libs/os/src/arch/cortex_m0/os_fault.c
+++ /dev/null
@@ -1,158 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include <stdint.h>
-#include <unistd.h>
-
-#include "syscfg/syscfg.h"
-#include "console/console.h"
-#include "hal/hal_system.h"
-#if MYNEWT_VAL(OS_COREDUMP)
-#include "coredump/coredump.h"
-#endif
-#include "os/os.h"
-
-
-struct exception_frame {
-    uint32_t r0;
-    uint32_t r1;
-    uint32_t r2;
-    uint32_t r3;
-    uint32_t r12;
-    uint32_t lr;
-    uint32_t pc;
-    uint32_t psr;
-};
-
-struct trap_frame {
-    struct exception_frame *ef;
-    uint32_t r4;
-    uint32_t r5;
-    uint32_t r6;
-    uint32_t r7;
-    uint32_t r8;
-    uint32_t r9;
-    uint32_t r10;
-    uint32_t r11;
-    uint32_t lr;    /* this LR holds EXC_RETURN */
-};
-
-struct coredump_regs {
-    uint32_t r0;
-    uint32_t r1;
-    uint32_t r2;
-    uint32_t r3;
-    uint32_t r4;
-    uint32_t r5;
-    uint32_t r6;
-    uint32_t r7;
-    uint32_t r8;
-    uint32_t r9;
-    uint32_t r10;
-    uint32_t r11;
-    uint32_t r12;
-    uint32_t sp;
-    uint32_t lr;
-    uint32_t pc;
-    uint32_t psr;
-};
-
-void __assert_func(const char *file, int line, const char *func, const char *e);
-
-#if MYNEWT_VAL(OS_COREDUMP)
-static void
-trap_to_coredump(struct trap_frame *tf, struct coredump_regs *regs)
-{
-    regs->r0 = tf->ef->r0;
-    regs->r1 = tf->ef->r1;
-    regs->r2 = tf->ef->r2;
-    regs->r3 = tf->ef->r3;
-    regs->r4 = tf->r4;
-    regs->r5 = tf->r5;
-    regs->r6 = tf->r6;
-    regs->r7 = tf->r7;
-    regs->r8 = tf->r8;
-    regs->r9 = tf->r9;
-    regs->r10 = tf->r10;
-    regs->r11 = tf->r11;
-    regs->r12 = tf->ef->r12;
-    /*
-     * SP just before exception for the coredump.
-     * See ARMv7-M Architecture Ref Manual, sections B1.5.6 - B1.5.8
-     * SP is adjusted by 0x20.
-     * If SCB->CCR.STKALIGN is set, SP is aligned to 8-byte boundary on
-     * exception entry.
-     * If this alignment adjustment happened, xPSR will have bit 9 set.
-     */
-    regs->sp = ((uint32_t)tf->ef) + 0x20;
-    if ((SCB->CCR & SCB_CCR_STKALIGN_Msk) & tf->ef->psr & (1 << 9)) {
-        regs->sp += 4;
-    }
-    regs->lr = tf->ef->lr;
-    regs->pc = tf->ef->pc;
-    regs->psr = tf->ef->psr;
-}
-#endif
-
-void
-__assert_func(const char *file, int line, const char *func, const char *e)
-{
-    int sr;
-
-    OS_ENTER_CRITICAL(sr);
-    (void)sr;
-    console_blocking_mode();
-    console_printf("Assert %s; failed in %s:%d\n", e ? e : "", file, line);
-    if (system_debugger_connected()) {
-       /*
-        * If debugger is attached, breakpoint before the trap.
-        */
-       asm("bkpt");
-    }
-    SCB->ICSR = SCB_ICSR_NMIPENDSET_Msk;
-    /* Exception happens right away. Next line not executed. */
-    system_reset();
-}
-
-void
-os_default_irq(struct trap_frame *tf)
-{
-#if MYNEWT_VAL(OS_COREDUMP)
-    struct coredump_regs regs;
-#endif
-
-    console_blocking_mode();
-    console_printf("Unhandled interrupt (%ld), exception sp 0x%08lx\n",
-      SCB->ICSR & SCB_ICSR_VECTACTIVE_Msk, (uint32_t)tf->ef);
-    console_printf(" r0:0x%08lx  r1:0x%08lx  r2:0x%08lx  r3:0x%08lx\n",
-      tf->ef->r0, tf->ef->r1, tf->ef->r2, tf->ef->r3);
-    console_printf(" r4:0x%08lx  r5:0x%08lx  r6:0x%08lx  r7:0x%08lx\n",
-      tf->r4, tf->r5, tf->r6, tf->r7);
-    console_printf(" r8:0x%08lx  r9:0x%08lx r10:0x%08lx r11:0x%08lx\n",
-      tf->r8, tf->r9, tf->r10, tf->r11);
-    console_printf("r12:0x%08lx  lr:0x%08lx  pc:0x%08lx psr:0x%08lx\n",
-      tf->ef->r12, tf->ef->lr, tf->ef->pc, tf->ef->psr);
-    console_printf("ICSR:0x%08lx\n", SCB->ICSR);
-#if MYNEWT_VAL(OS_COREDUMP)
-    trap_to_coredump(tf, &regs);
-    coredump_dump(&regs, sizeof(regs));
-#endif
-    system_reset();
-}
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/src/arch/cortex_m4/m4/HAL_CM4.s
----------------------------------------------------------------------
diff --git a/libs/os/src/arch/cortex_m4/m4/HAL_CM4.s b/libs/os/src/arch/cortex_m4/m4/HAL_CM4.s
deleted file mode 100755
index 9c6ab52..0000000
--- a/libs/os/src/arch/cortex_m4/m4/HAL_CM4.s
+++ /dev/null
@@ -1,224 +0,0 @@
-/*----------------------------------------------------------------------------
- * Copyright (c) 1999-2009 KEIL, 2009-2013 ARM Germany GmbH
- * 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 ARM  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 COPYRIGHT HOLDERS AND CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- *---------------------------------------------------------------------------*/
-
-        .file   "HAL_CM4.S"
-        .syntax unified
-
-/*----------------------------------------------------------------------------
- *      Functions
- *---------------------------------------------------------------------------*/
-
-        .thumb
-
-        .section ".text"
-        .align  2
-
-/*--------------------------- os_set_env ------------------------------------*/
-#       void os_set_env (void);
-#
-#   Called to switch to privileged or unprivileged thread mode. The variable
-#   'os_flags' contains the CONTROL bit LSB to set the device into the
-#   proper mode. We also use PSP so we set bit 1 (the SPSEL bit) to 1.
-#
-
-        .thumb_func
-        .type   os_set_env, %function
-        .global os_set_env
-os_set_env:
-        .fnstart
-        .cantunwind
-
-        MSR     PSP,R0
-        LDR     R0,=os_flags
-        LDRB    R0,[R0]
-        ADDS    R0, R0, #2
-        MSR     CONTROL,R0
-        ISB
-        BX      LR
-
-        .fnend
-        .size   os_set_env, .-os_set_env
-
-/*--------------------------- os_set_env ------------------------------------*/
-
-
-/*--------------------------- os_arch_init_task_stack------------------------*/
-#       void os_arch_init_task_stack(os_stack_t *sf);
-# NOTE: This function only stores R4 through R11 on stack. The reason we do 
-# this is that the application may have stored some values in some of the
-# registers and we want to preserve those values (position independent code
-# is a good example). The other registers are handled in the C startup code.
-        .thumb_func
-        .type   os_arch_init_task_stack, %function
-        .global os_arch_init_task_stack
-os_arch_init_task_stack:
-        .fnstart
-
-        STMIA   R0,{R4-R11}
-        BX      LR
-
-        .fnend
-        .size   os_arch_init_task_stack, .-os_arch_init_task_stack
-/*--------------------------- os_set_env ------------------------------------*/
-
-
-/*-------------------------- SVC_Handler ------------------------------------*/
-
-#       void SVC_Handler (void);
-
-        .thumb_func
-        .type   SVC_Handler, %function
-        .global SVC_Handler
-SVC_Handler:
-        .fnstart
-        .cantunwind
-
-        MRS     R0,PSP                  /* Read PSP */
-        LDR     R1,[R0,#24]             /* Read Saved PC from Stack */
-        LDRB    R1,[R1,#-2]             /* Load SVC Number */
-        CBNZ    R1,SVC_User
-
-        LDM     R0,{R0-R3,R12}          /* Read R0-R3,R12 from stack */
-        PUSH    {R4,LR}                 /* Save EXC_RETURN */
-        BLX     R12                     /* Call SVC Function */
-        POP     {R4,LR}                 /* Restore EXC_RETURN */
-
-        MRS     R12,PSP                 /* Read PSP */
-        STM     R12,{R0-R2}             /* Store return values */
-        BX      LR                      /* Return from interrupt */
-
-        /*------------------- User SVC ------------------------------*/
-SVC_User:
-        PUSH    {R4,LR}                 /* Save EXC_RETURN */
-        LDR     R2,=SVC_Count
-        LDR     R2,[R2]
-        CMP     R1,R2
-        BHI     SVC_Done                /* Overflow */
-
-        LDR     R4,=SVC_Table-4
-        LDR     R4,[R4,R1,LSL #2]       /* Load SVC Function Address */
-
-        LDM     R0,{R0-R3,R12}          /* Read R0-R3,R12 from stack */
-        BLX     R4                      /* Call SVC Function */
-
-        MRS     R12,PSP
-        STM     R12,{R0-R3}             /* Function return values */
-SVC_Done:
-        POP     {R4,LR}                 /* Restore EXC_RETURN */
-        BX      LR                      /* Return from interrupt */
-
-        .fnend
-        .size   SVC_Handler, .-SVC_Handler
-
-
-/*-------------------------- PendSV_Handler ---------------------------------*/
-
-#       void PendSV_Handler (void);
-
-        .thumb_func
-        .type   PendSV_Handler, %function
-        .global PendSV_Handler
-PendSV_Handler:
-        .fnstart
-        .cantunwind
-
-        LDR     R3,=g_os_run_list       /* Get highest priority task ready to run */
-        LDR     R2,[R3]                 /* Store in R2 */
-        LDR     R3,=g_current_task      /* Get current task */
-        LDR     R1,[R3]                 /* Current task in R1 */
-        CMP     R1,R2
-        IT      EQ
-        BXEQ    LR                      /* RETI, no task switch */
-
-        MRS     R12,PSP                 /* Read PSP */
-        STMDB   R12!,{R4-R11}           /* Save Old context */
-        STR     R12,[R1,#0]             /* Update stack pointer in current task */
-        STR     R2,[R3]                 /* g_current_task = highest ready */
-
-        LDR     R12,[R2,#0]             /* get stack pointer of task we will start */
-        LDMIA   R12!,{R4-R11}           /* Restore New Context */
-        MSR     PSP,R12                 /* Write PSP */
-        BX      LR                      /* Return to Thread Mode */
-
-        .fnend
-        .size   PendSV_Handler, .-PendSV_Handler
-
-
-/*-------------------------- SysTick_Handler --------------------------------*/
-
-#       void SysTick_Handler (void);
-        .thumb_func
-        .type   SysTick_Handler, %function
-        .global SysTick_Handler
-SysTick_Handler:
-        .fnstart
-        .cantunwind
-
-        PUSH    {R4,LR}                 /* Save EXC_RETURN */
-        BL      timer_handler
-        POP     {R4,LR}                 /* Restore EXC_RETURN */
-        BX      LR
-
-        .fnend
-        .size   SysTick_Handler, .-SysTick_Handler
-
-/*-------------------------- Defalt IRQ --------------------------------*/
-        .thumb_func
-        .type   os_default_irq_asm, %function
-        .global os_default_irq_asm
-os_default_irq_asm:
-        .fnstart
-        .cantunwind
-
-        /*
-         * LR = 0xfffffff9 if we were using MSP as SP
-         * LR = 0xfffffffd if we were using PSP as SP
-         */
-        TST     LR,#4
-        ITE     EQ
-        MRSEQ   R3,MSP
-        MRSNE   R3,PSP
-        PUSH    {R3-R11,LR}
-        MOV     R0, SP
-        BL      os_default_irq
-        POP     {R3-R11,LR}                 /* Restore EXC_RETURN */
-        BX      LR
-
-        .fnend
-        .size   os_default_irq_asm, .-os_default_irq_asm
-
-	/*
-	 * Prevent libgcc unwind stuff from getting pulled in.
-	 */
-        .section ".data"
-	.global __aeabi_unwind_cpp_pr0
-__aeabi_unwind_cpp_pr0:
-        .end
-
-/*----------------------------------------------------------------------------
- * end of file
- *---------------------------------------------------------------------------*/

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/src/arch/cortex_m4/m4/SVC_Table.s
----------------------------------------------------------------------
diff --git a/libs/os/src/arch/cortex_m4/m4/SVC_Table.s b/libs/os/src/arch/cortex_m4/m4/SVC_Table.s
deleted file mode 100755
index 2b99321..0000000
--- a/libs/os/src/arch/cortex_m4/m4/SVC_Table.s
+++ /dev/null
@@ -1,56 +0,0 @@
-;/*----------------------------------------------------------------------------
-; *      RL-ARM - RTX
-; *----------------------------------------------------------------------------
-; *      Name:    SVC_TABLE.S
-; *      Purpose: Pre-defined SVC Table for Cortex-M
-; *      Rev.:    V4.70
-; *----------------------------------------------------------------------------
-; *
-; * Copyright (c) 1999-2009 KEIL, 2009-2013 ARM Germany GmbH
-; * 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 ARM  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 COPYRIGHT HOLDERS AND CONTRIBUTORS BE
-; * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-; * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-; * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-; * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-; * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-; * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-; * POSSIBILITY OF SUCH DAMAGE.
-; *---------------------------------------------------------------------------*/
-
-
-        .file   "SVC_Table.S"
-
-
-        .section ".svc_table"
-
-        .global  SVC_Table
-SVC_Table:
-/* Insert user SVC functions here. SVC 0 used by RTL Kernel. */
-#       .long   __SVC_1                 /* user SVC function */
-SVC_End:
-
-        .global  SVC_Count
-SVC_Count:
-        .long   (SVC_End-SVC_Table)/4
-
-
-        .end
-
-/*----------------------------------------------------------------------------
- * end of file
- *---------------------------------------------------------------------------*/

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/src/arch/cortex_m4/os_arch_arm.c
----------------------------------------------------------------------
diff --git a/libs/os/src/arch/cortex_m4/os_arch_arm.c b/libs/os/src/arch/cortex_m4/os_arch_arm.c
deleted file mode 100755
index cef11f9..0000000
--- a/libs/os/src/arch/cortex_m4/os_arch_arm.c
+++ /dev/null
@@ -1,328 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include "os/os.h"
-#include "os/os_arch.h"
-#include <hal/hal_bsp.h>
-#include <hal/hal_os_tick.h>
-#include <bsp/cmsis_nvic.h>
-
-#include "os_priv.h"
-
-/* Initial program status register */
-#define INITIAL_xPSR    0x01000000
-
-/*
- * Exception priorities. The higher the number, the lower the priority. A
- * higher priority exception will interrupt a lower priority exception.
- */
-#define PEND_SV_PRIO    ((1 << __NVIC_PRIO_BITS) - 1)
-#define OS_TICK_PRIO    (PEND_SV_PRIO - 1)
-
-/* Make the SVC instruction highest priority */
-#define SVC_PRIO        (1)
-
-/* Stack frame structure */
-struct stack_frame {
-    uint32_t    r4;
-    uint32_t    r5;
-    uint32_t    r6;
-    uint32_t    r7;
-    uint32_t    r8;
-    uint32_t    r9;
-    uint32_t    r10;
-    uint32_t    r11;
-    uint32_t    r0;
-    uint32_t    r1;
-    uint32_t    r2;
-    uint32_t    r3;
-    uint32_t    r12;
-    uint32_t    lr;
-    uint32_t    pc;
-    uint32_t    xpsr;
-};
-
-#define SVC_ArgN(n) \
-  register int __r##n __asm("r"#n);
-
-#define SVC_Arg0()  \
-  SVC_ArgN(0)       \
-  SVC_ArgN(1)       \
-  SVC_ArgN(2)       \
-  SVC_ArgN(3)
-
-#if (defined (__CORTEX_M0)) || defined (__CORTEX_M0PLUS)
-#define SVC_Call(f)                                                     \
-  __asm volatile                                                        \
-  (                                                                     \
-    "ldr r7,="#f"\n\t"                                                  \
-    "mov r12,r7\n\t"                                                    \
-    "svc 0"                                                             \
-    :               "=r" (__r0), "=r" (__r1), "=r" (__r2), "=r" (__r3)  \
-    :                "r" (__r0),  "r" (__r1),  "r" (__r2),  "r" (__r3)  \
-    : "r7", "r12", "lr", "cc"                                           \
-  );
-#else
-#define SVC_Call(f)                                                     \
-  __asm volatile                                                        \
-  (                                                                     \
-    "ldr r12,="#f"\n\t"                                                 \
-    "svc 0"                                                             \
-    :               "=r" (__r0), "=r" (__r1), "=r" (__r2), "=r" (__r3)  \
-    :                "r" (__r0),  "r" (__r1),  "r" (__r2),  "r" (__r3)  \
-    : "r12", "lr", "cc"                                                 \
-  );
-#endif
-
-/* XXX: determine how we will deal with running un-privileged */
-uint32_t os_flags = OS_RUN_PRIV;
-
-void
-timer_handler(void)
-{
-    os_time_advance(1);
-}
-
-void
-os_arch_ctx_sw(struct os_task *t)
-{
-    os_sched_ctx_sw_hook(t);
-
-    /* Set PendSV interrupt pending bit to force context switch */
-    SCB->ICSR = SCB_ICSR_PENDSVSET_Msk;
-}
-
-os_sr_t
-os_arch_save_sr(void)
-{
-    uint32_t isr_ctx;
-
-    isr_ctx = __get_PRIMASK();
-    __disable_irq();
-    return (isr_ctx & 1);
-}
-
-void
-os_arch_restore_sr(os_sr_t isr_ctx)
-{
-    if (!isr_ctx) {
-        __enable_irq();
-    }
-}
-
-int
-os_arch_in_critical(void)
-{
-    uint32_t isr_ctx;
-
-    isr_ctx = __get_PRIMASK();
-    return (isr_ctx & 1);
-}
-
-os_stack_t *
-os_arch_task_stack_init(struct os_task *t, os_stack_t *stack_top, int size)
-{
-    int i;
-    os_stack_t *s;
-    struct stack_frame *sf;
-
-    /* Get stack frame pointer */
-    s = (os_stack_t *) ((uint8_t *) stack_top - sizeof(*sf));
-
-    /* Zero out R1-R3, R12, LR */
-    for (i = 9; i < 14; ++i) {
-        s[i] = 0;
-    }
-
-    /* Set registers R4 - R11 on stack. */
-    os_arch_init_task_stack(s);
-
-    /* Set remaining portions of stack frame */
-    sf = (struct stack_frame *) s;
-    sf->xpsr = INITIAL_xPSR;
-    sf->pc = (uint32_t)t->t_func;
-    sf->r0 = (uint32_t)t->t_arg;
-
-    return (s);
-}
-
-void
-os_arch_init(void)
-{
-    /*
-     * Trap on divide-by-zero.
-     */
-    SCB->CCR |= SCB_CCR_DIV_0_TRP_Msk;
-    os_init_idle_task();
-}
-
-__attribute__((always_inline))
-static inline void
-svc_os_arch_init(void)
-{
-    SVC_Arg0();
-    SVC_Call(os_arch_init);
-}
-
-os_error_t
-os_arch_os_init(void)
-{
-    os_error_t err;
-    int i;
-
-    /* Cannot be called within an ISR */
-    err = OS_ERR_IN_ISR;
-    if (__get_IPSR() == 0) {
-        err = OS_OK;
-
-        /* Drop priority for all interrupts */
-        for (i = 0; i < sizeof(NVIC->IP); i++) {
-            NVIC->IP[i] = 0xff;
-        }
-
-        /*
-         * Install default interrupt handler, which'll print out system
-         * state at the time of the interrupt, and few other regs which
-         * should help in trying to figure out what went wrong.
-         */
-        NVIC_SetVector(NonMaskableInt_IRQn, (uint32_t)os_default_irq_asm);
-        NVIC_SetVector(-13, (uint32_t)os_default_irq_asm);
-        NVIC_SetVector(MemoryManagement_IRQn, (uint32_t)os_default_irq_asm);
-        NVIC_SetVector(BusFault_IRQn, (uint32_t)os_default_irq_asm);
-        NVIC_SetVector(UsageFault_IRQn, (uint32_t)os_default_irq_asm);
-        for (i = 0; i < NVIC_NUM_VECTORS - NVIC_USER_IRQ_OFFSET; i++) {
-            NVIC_SetVector(i, (uint32_t)os_default_irq_asm);
-        }
-
-        /* Set the PendSV interrupt exception priority to the lowest priority */
-        NVIC_SetPriority(PendSV_IRQn, PEND_SV_PRIO);
-
-        /* Set the SVC interrupt to priority 0 (highest configurable) */
-        NVIC_SetPriority(SVCall_IRQn, SVC_PRIO);
-
-        /* Check if privileged or not */
-        if ((__get_CONTROL() & 1) == 0) {
-            os_arch_init();
-        } else {
-            svc_os_arch_init();
-        }
-    }
-
-    return err;
-}
-
-uint32_t
-os_arch_start(void)
-{
-    struct os_task *t;
-
-    /* Get the highest priority ready to run to set the current task */
-    t = os_sched_next_task();
-    os_sched_set_current_task(t);
-
-    /* Adjust PSP so it looks like this task just took an exception */
-    __set_PSP((uint32_t)t->t_stackptr + offsetof(struct stack_frame, r0));
-
-    /* Intitialize and start system clock timer */
-    os_tick_init(OS_TICKS_PER_SEC, OS_TICK_PRIO);
-
-    /* Mark the OS as started, right before we run our first task */
-    g_os_started = 1;
-
-    /* Perform context switch */
-    os_arch_ctx_sw(t);
-
-    return (uint32_t)(t->t_arg);
-}
-
-__attribute__((always_inline))
-static inline void svc_os_arch_start(void)
-{
-    SVC_Arg0();
-    SVC_Call(os_arch_start);
-}
-
-/**
- * Start the OS. First check to see if we are running with the correct stack
- * pointer set (PSP) and privilege mode (PRIV).
- *
- *
- * @return os_error_t
- */
-os_error_t
-os_arch_os_start(void)
-{
-    os_error_t err;
-
-    /*
-     * Set the os environment. This will set stack pointers and, based
-     * on the contents of os_flags, will determine if the tasks run in
-     * privileged or un-privileged mode.
-     *
-     * We switch to using "empty" part of idle task's stack until
-     * the svc_os_arch_start() executes SVC, and we will never return.
-     */
-    os_set_env(g_idle_task.t_stackptr - 1);
-
-    err = OS_ERR_IN_ISR;
-    if (__get_IPSR() == 0) {
-        /*
-         * The following switch statement is really just a sanity check to
-         * insure that the os initialization routine was called prior to the
-         * os start routine.
-         */
-        err = OS_OK;
-        switch (__get_CONTROL() & 0x03) {
-        /*
-         * These two cases are for completeness. Thread mode should be set
-         * to use PSP already.
-         *
-         * Fall-through intentional!
-         */
-        case 0x00:
-        case 0x01:
-            err = OS_ERR_PRIV;
-            break;
-        case 0x02:
-            /*
-             * We are running in Privileged Thread mode w/SP = PSP but we
-             * are supposed to be un-privileged.
-             */
-            if ((os_flags & 1) == OS_RUN_UNPRIV) {
-                err = OS_ERR_PRIV;
-            }
-            break;
-        case 0x03:
-            /*
-             * We are running in Unprivileged Thread mode w/SP = PSP but we
-             * are supposed to be privileged.
-             */
-            if  ((os_flags & 1) == OS_RUN_PRIV) {
-                err = OS_ERR_PRIV;
-            }
-            break;
-        }
-        if (err == OS_OK) {
-            /* Always start OS through SVC call */
-            svc_os_arch_start();
-        }
-    }
-
-    return err;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/src/arch/cortex_m4/os_fault.c
----------------------------------------------------------------------
diff --git a/libs/os/src/arch/cortex_m4/os_fault.c b/libs/os/src/arch/cortex_m4/os_fault.c
deleted file mode 100644
index d7806db..0000000
--- a/libs/os/src/arch/cortex_m4/os_fault.c
+++ /dev/null
@@ -1,160 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include "syscfg/syscfg.h"
-#include "console/console.h"
-#include "hal/hal_system.h"
-#include "os/os.h"
-
-#if MYNEWT_VAL(OS_COREDUMP)
-#include "coredump/coredump.h"
-#endif
-
-#include <stdint.h>
-#include <unistd.h>
-
-struct exception_frame {
-    uint32_t r0;
-    uint32_t r1;
-    uint32_t r2;
-    uint32_t r3;
-    uint32_t r12;
-    uint32_t lr;
-    uint32_t pc;
-    uint32_t psr;
-};
-
-struct trap_frame {
-    struct exception_frame *ef;
-    uint32_t r4;
-    uint32_t r5;
-    uint32_t r6;
-    uint32_t r7;
-    uint32_t r8;
-    uint32_t r9;
-    uint32_t r10;
-    uint32_t r11;
-    uint32_t lr;    /* this LR holds EXC_RETURN */
-};
-
-struct coredump_regs {
-    uint32_t r0;
-    uint32_t r1;
-    uint32_t r2;
-    uint32_t r3;
-    uint32_t r4;
-    uint32_t r5;
-    uint32_t r6;
-    uint32_t r7;
-    uint32_t r8;
-    uint32_t r9;
-    uint32_t r10;
-    uint32_t r11;
-    uint32_t r12;
-    uint32_t sp;
-    uint32_t lr;
-    uint32_t pc;
-    uint32_t psr;
-};
-
-void __assert_func(const char *file, int line, const char *func, const char *e);
-
-#if MYNEWT_VAL(OS_COREDUMP)
-static void
-trap_to_coredump(struct trap_frame *tf, struct coredump_regs *regs)
-{
-    regs->r0 = tf->ef->r0;
-    regs->r1 = tf->ef->r1;
-    regs->r2 = tf->ef->r2;
-    regs->r3 = tf->ef->r3;
-    regs->r4 = tf->r4;
-    regs->r5 = tf->r5;
-    regs->r6 = tf->r6;
-    regs->r7 = tf->r7;
-    regs->r8 = tf->r8;
-    regs->r9 = tf->r9;
-    regs->r10 = tf->r10;
-    regs->r11 = tf->r11;
-    regs->r12 = tf->ef->r12;
-    /*
-     * SP just before exception for the coredump.
-     * See ARMv7-M Architecture Ref Manual, sections B1.5.6 - B1.5.8
-     * SP is adjusted by 0x20.
-     * If SCB->CCR.STKALIGN is set, SP is aligned to 8-byte boundary on
-     * exception entry.
-     * If this alignment adjustment happened, xPSR will have bit 9 set.
-     */
-    regs->sp = ((uint32_t)tf->ef) + 0x20;
-    if ((SCB->CCR & SCB_CCR_STKALIGN_Msk) & tf->ef->psr & (1 << 9)) {
-        regs->sp += 4;
-    }
-    regs->lr = tf->ef->lr;
-    regs->pc = tf->ef->pc;
-    regs->psr = tf->ef->psr;
-}
-#endif
-
-void
-__assert_func(const char *file, int line, const char *func, const char *e)
-{
-    int sr;
-
-    OS_ENTER_CRITICAL(sr);
-    (void)sr;
-    console_blocking_mode();
-    console_printf("Assert %s; failed in %s:%d\n", e ? e : "", file, line);
-    if (system_debugger_connected()) {
-       /*
-        * If debugger is attached, breakpoint before the trap.
-        */
-       asm("bkpt");
-    }
-    SCB->ICSR = SCB_ICSR_NMIPENDSET_Msk;
-    asm("isb");
-    system_reset();
-}
-
-void
-os_default_irq(struct trap_frame *tf)
-{
-#if MYNEWT_VAL(OS_COREDUMP)
-    struct coredump_regs regs;
-#endif
-
-    console_blocking_mode();
-    console_printf("Unhandled interrupt (%ld), exception sp 0x%08lx\n",
-      SCB->ICSR & SCB_ICSR_VECTACTIVE_Msk, (uint32_t)tf->ef);
-    console_printf(" r0:0x%08lx  r1:0x%08lx  r2:0x%08lx  r3:0x%08lx\n",
-      tf->ef->r0, tf->ef->r1, tf->ef->r2, tf->ef->r3);
-    console_printf(" r4:0x%08lx  r5:0x%08lx  r6:0x%08lx  r7:0x%08lx\n",
-      tf->r4, tf->r5, tf->r6, tf->r7);
-    console_printf(" r8:0x%08lx  r9:0x%08lx r10:0x%08lx r11:0x%08lx\n",
-      tf->r8, tf->r9, tf->r10, tf->r11);
-    console_printf("r12:0x%08lx  lr:0x%08lx  pc:0x%08lx psr:0x%08lx\n",
-      tf->ef->r12, tf->ef->lr, tf->ef->pc, tf->ef->psr);
-    console_printf("ICSR:0x%08lx HFSR:0x%08lx CFSR:0x%08lx\n",
-      SCB->ICSR, SCB->HFSR, SCB->CFSR);
-    console_printf("BFAR:0x%08lx MMFAR:0x%08lx\n", SCB->BFAR, SCB->MMFAR);
-
-#if MYNEWT_VAL(OS_COREDUMP)
-    trap_to_coredump(tf, &regs);
-    coredump_dump(&regs, sizeof(regs));
-#endif
-    system_reset();
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/src/arch/sim/os_arch_sim.c
----------------------------------------------------------------------
diff --git a/libs/os/src/arch/sim/os_arch_sim.c b/libs/os/src/arch/sim/os_arch_sim.c
deleted file mode 100644
index 51731f7..0000000
--- a/libs/os/src/arch/sim/os_arch_sim.c
+++ /dev/null
@@ -1,462 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include "os/os.h"
-#include "os_priv.h"
-
-#include <hal/hal_bsp.h>
-
-#ifdef __APPLE__
-#define _XOPEN_SOURCE
-#endif
-
-#include <string.h>
-#include <stdio.h>
-#include <unistd.h>
-#include <setjmp.h>
-#include <signal.h>
-#include <sys/time.h>
-#include <assert.h>
-#include <util/util.h>
-
-struct stack_frame {
-    int sf_mainsp;              /* stack on which main() is executing */
-    sigjmp_buf sf_jb;
-    struct os_task *sf_task;
-};
-
-/*
- * Assert that 'sf_mainsp' and 'sf_jb' are at the specific offsets where
- * os_arch_frame_init() expects them to be.
- */
-CTASSERT(offsetof(struct stack_frame, sf_mainsp) == 0);
-CTASSERT(offsetof(struct stack_frame, sf_jb) == 4);
-
-extern void os_arch_frame_init(struct stack_frame *sf);
-
-#define sim_setjmp(__jb) sigsetjmp(__jb, 0)
-#define sim_longjmp(__jb, __ret) siglongjmp(__jb, __ret)
-
-#define OS_USEC_PER_TICK    (1000000 / OS_TICKS_PER_SEC)
-
-static pid_t mypid;
-static sigset_t allsigs, nosigs;
-static void timer_handler(int sig);
-
-static bool suspended;      /* process is blocked in sigsuspend() */
-static sigset_t suspsigs;   /* signals delivered in sigsuspend() */
-
-/*
- * Called from 'os_arch_frame_init()' when setjmp returns indirectly via
- * longjmp. The return value of setjmp is passed to this function as 'rc'.
- */
-void
-os_arch_task_start(struct stack_frame *sf, int rc)
-{
-    struct os_task *task;
-
-    /*
-     * Interrupts are disabled when a task starts executing. This happens in
-     * two different ways:
-     * - via os_arch_os_start() for the first task.
-     * - via os_sched() for all other tasks.
-     *
-     * Enable interrupts before starting the task.
-     */
-    OS_EXIT_CRITICAL(0);
-
-    task = sf->sf_task;
-    task->t_func(task->t_arg);
-
-    /* This should never return */
-    assert(0);
-}
-
-os_stack_t *
-os_arch_task_stack_init(struct os_task *t, os_stack_t *stack_top, int size)
-{
-    struct stack_frame *sf;
-
-    sf = (struct stack_frame *) ((uint8_t *) stack_top - sizeof(*sf));
-    sf->sf_task = t;
-
-    os_arch_frame_init(sf);
-
-    return ((os_stack_t *)sf);
-}
-
-void
-os_arch_ctx_sw(struct os_task *next_t)
-{
-    /*
-     * gdb will stop execution of the program on most signals (e.g. SIGUSR1)
-     * whereas it passes SIGURG to the process without any special settings.
-     */
-    kill(mypid, SIGURG);
-}
-
-static void
-ctxsw_handler(int sig)
-{
-    struct os_task *t, *next_t;
-    struct stack_frame *sf;
-    int rc;
-
-    OS_ASSERT_CRITICAL();
-
-    /*
-     * Just record that this handler was called when the process was blocked.
-     * The handler will be called after sigsuspend() returns in the correct
-     * order.
-     */
-    if (suspended) {
-        sigaddset(&suspsigs, sig);
-        return;
-    }
-
-    t = os_sched_get_current_task();
-    next_t = os_sched_next_task();
-    if (t == next_t) {
-        /*
-         * Context switch not needed - just return.
-         */
-        return;
-    }
-
-    if (t) {
-        sf = (struct stack_frame *) t->t_stackptr;
-
-        rc = sim_setjmp(sf->sf_jb);
-        if (rc != 0) {
-            OS_ASSERT_CRITICAL();
-            return;
-        }
-    }
-
-    os_sched_ctx_sw_hook(next_t);
-
-    os_sched_set_current_task(next_t);
-
-    sf = (struct stack_frame *) next_t->t_stackptr;
-    sim_longjmp(sf->sf_jb, 1);
-}
-
-/*
- * Disable signals and enter a critical section.
- *
- * Returns 1 if signals were already blocked and 0 otherwise.
- */
-os_sr_t
-os_arch_save_sr(void)
-{
-    int error;
-    sigset_t omask;
-
-    error = sigprocmask(SIG_BLOCK, &allsigs, &omask);
-    assert(error == 0);
-
-    /*
-     * If any one of the signals in 'allsigs' is present in 'omask' then
-     * we are already inside a critical section.
-     */
-    return (sigismember(&omask, SIGALRM));
-}
-
-void
-os_arch_restore_sr(os_sr_t osr)
-{
-    int error;
-
-    OS_ASSERT_CRITICAL();
-    assert(osr == 0 || osr == 1);
-
-    if (osr == 1) {
-        /* Exiting a nested critical section */
-        return;
-    }
-
-    error = sigprocmask(SIG_UNBLOCK, &allsigs, NULL);
-    assert(error == 0);
-}
-
-int
-os_arch_in_critical(void)
-{
-    int error;
-    sigset_t omask;
-
-    error = sigprocmask(SIG_SETMASK, NULL, &omask);
-    assert(error == 0);
-
-    /*
-     * If any one of the signals in 'allsigs' is present in 'omask' then
-     * we are already inside a critical section.
-     */
-    return (sigismember(&omask, SIGALRM));
-}
-
-static struct {
-    int num;
-    void (*handler)(int sig);
-} signals[] = {
-    { SIGALRM, timer_handler },
-    { SIGURG, ctxsw_handler },
-};
-
-#define NUMSIGS     (sizeof(signals)/sizeof(signals[0]))
-
-void
-os_tick_idle(os_time_t ticks)
-{
-    int i, rc, sig;
-    struct itimerval it;
-    void (*handler)(int sig);
-
-    OS_ASSERT_CRITICAL();
-
-    if (ticks > 0) {
-        /*
-         * Enter tickless regime and set the timer to fire after 'ticks'
-         * worth of time has elapsed.
-         */
-        it.it_value.tv_sec = ticks / OS_TICKS_PER_SEC;
-        it.it_value.tv_usec = (ticks % OS_TICKS_PER_SEC) * OS_USEC_PER_TICK;
-        it.it_interval.tv_sec = 0;
-        it.it_interval.tv_usec = OS_USEC_PER_TICK;
-        rc = setitimer(ITIMER_REAL, &it, NULL);
-        assert(rc == 0);
-    }
-
-    suspended = true;
-    sigemptyset(&suspsigs);
-    sigsuspend(&nosigs);        /* Wait for a signal to wake us up */
-    suspended = false;
-
-    /*
-     * Call handlers for signals delivered to the process during sigsuspend().
-     * The SIGALRM handler is called before any other handlers to ensure that
-     * OS time is always correct.
-     */
-    if (sigismember(&suspsigs, SIGALRM)) {
-        timer_handler(SIGALRM);
-    }
-    for (i = 0; i < NUMSIGS; i++) {
-        sig = signals[i].num;
-        handler = signals[i].handler;
-        if (sig != SIGALRM && sigismember(&suspsigs, sig)) {
-            handler(sig);
-        }
-    }
-
-    if (ticks > 0) {
-        /*
-         * Enable the periodic timer interrupt.
-         */
-        it.it_value.tv_sec = 0;
-        it.it_value.tv_usec = OS_USEC_PER_TICK;
-        it.it_interval.tv_sec = 0;
-        it.it_interval.tv_usec = OS_USEC_PER_TICK;
-        rc = setitimer(ITIMER_REAL, &it, NULL);
-        assert(rc == 0);
-    }
-}
-
-static void
-signals_init(void)
-{
-    int i, error;
-    struct sigaction sa;
-
-    sigemptyset(&nosigs);
-    sigemptyset(&allsigs);
-    for (i = 0; i < NUMSIGS; i++) {
-        sigaddset(&allsigs, signals[i].num);
-    }
-
-    for (i = 0; i < NUMSIGS; i++) {
-        memset(&sa, 0, sizeof sa);
-        sa.sa_handler = signals[i].handler;
-        sa.sa_mask = allsigs;
-        sa.sa_flags = SA_RESTART;
-        error = sigaction(signals[i].num, &sa, NULL);
-        assert(error == 0);
-    }
-
-    /*
-     * We use SIGALRM as a proxy for 'allsigs' to check if we are inside
-     * a critical section (for e.g. see os_arch_in_critical()). Make sure
-     * that SIGALRM is indeed present in 'allsigs'.
-     */
-    assert(sigismember(&allsigs, SIGALRM));
-}
-
-static void
-signals_cleanup(void)
-{
-    int i, error;
-    struct sigaction sa;
-
-    for (i = 0; i < NUMSIGS; i++) {
-        memset(&sa, 0, sizeof sa);
-        sa.sa_handler = SIG_DFL;
-        error = sigaction(signals[i].num, &sa, NULL);
-        assert(error == 0);
-    }
-}
-
-static void
-timer_handler(int sig)
-{
-    struct timeval time_now, time_diff;
-    int ticks;
-
-    static struct timeval time_last;
-    static int time_inited;
-
-    OS_ASSERT_CRITICAL();
-
-    /*
-     * Just record that this handler was called when the process was blocked.
-     * The handler will be called after sigsuspend() returns in the proper
-     * order.
-     */
-    if (suspended) {
-        sigaddset(&suspsigs, sig);
-        return;
-    }
-
-    if (!time_inited) {
-        gettimeofday(&time_last, NULL);
-        time_inited = 1;
-    }
-
-    gettimeofday(&time_now, NULL);
-    if (timercmp(&time_now, &time_last, <)) {
-        /*
-         * System time going backwards.
-         */
-        time_last = time_now;
-    } else {
-        timersub(&time_now, &time_last, &time_diff);
-
-        ticks = time_diff.tv_sec * OS_TICKS_PER_SEC;
-        ticks += time_diff.tv_usec / OS_USEC_PER_TICK;
-
-        /*
-         * Update 'time_last' but account for the remainder usecs that did not
-         * contribute towards whole 'ticks'.
-         */
-        time_diff.tv_sec = 0;
-        time_diff.tv_usec %= OS_USEC_PER_TICK;
-        timersub(&time_now, &time_diff, &time_last);
-
-        os_time_advance(ticks);
-    }
-}
-
-static void
-start_timer(void)
-{
-    struct itimerval it;
-    int rc;
-
-    memset(&it, 0, sizeof(it));
-    it.it_value.tv_sec = 0;
-    it.it_value.tv_usec = OS_USEC_PER_TICK;
-    it.it_interval.tv_sec = 0;
-    it.it_interval.tv_usec = OS_USEC_PER_TICK;
-
-    rc = setitimer(ITIMER_REAL, &it, NULL);
-    assert(rc == 0);
-}
-
-static void
-stop_timer(void)
-{
-    struct itimerval it;
-    int rc;
-
-    memset(&it, 0, sizeof(it));
-
-    rc = setitimer(ITIMER_REAL, &it, NULL);
-    assert(rc == 0);
-}
-
-os_error_t
-os_arch_os_init(void)
-{
-    mypid = getpid();
-    g_current_task = NULL;
-
-    STAILQ_INIT(&g_os_task_list);
-    TAILQ_INIT(&g_os_run_list);
-    TAILQ_INIT(&g_os_sleep_list);
-
-    /*
-     * Setup all interrupt handlers.
-     *
-     * This must be done early because task initialization uses critical
-     * sections which function correctly only when 'allsigs' is initialized.
-     */
-    signals_init();
-
-    os_init_idle_task();
-
-    return OS_OK;
-}
-
-os_error_t
-os_arch_os_start(void)
-{
-    struct stack_frame *sf;
-    struct os_task *t;
-    os_sr_t sr;
-
-    /*
-     * Disable interrupts before enabling any interrupt sources. Pending
-     * interrupts will be recognized when the first task starts executing.
-     */
-    OS_ENTER_CRITICAL(sr);
-    assert(sr == 0);
-
-    /* Enable the interrupt sources */
-    start_timer();
-
-    t = os_sched_next_task();
-    os_sched_set_current_task(t);
-
-    g_os_started = 1;
-
-    sf = (struct stack_frame *) t->t_stackptr;
-    sim_longjmp(sf->sf_jb, 1);
-
-    return 0;
-}
-
-/**
- * Stops the tick timer and clears the "started" flag.  This function is only
- * implemented for sim.
- */
-void
-os_arch_os_stop(void)
-{
-    stop_timer();
-    signals_cleanup();
-    g_os_started = 0;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/src/arch/sim/os_arch_stack_frame.s
----------------------------------------------------------------------
diff --git a/libs/os/src/arch/sim/os_arch_stack_frame.s b/libs/os/src/arch/sim/os_arch_stack_frame.s
deleted file mode 100644
index ecae80d..0000000
--- a/libs/os/src/arch/sim/os_arch_stack_frame.s
+++ /dev/null
@@ -1,101 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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.
- */
-
-#if defined MN_LINUX
-#define sigsetjmp   __sigsetjmp
-#define CNAME(x)    x
-#elif defined MN_OSX
-#define sigsetjmp   sigsetjmp
-#define CNAME(x)    _ ## x
-#else
-#error "unsupported platform"
-#endif
-
-    .text
-    .code32
-    .p2align 4, 0x90    /* align on 16-byte boundary and fill with NOPs */
-
-    .globl CNAME(os_arch_frame_init)
-    .globl _os_arch_frame_init
-    /*
-     * void os_arch_frame_init(struct stack_frame *sf)
-     */
-CNAME(os_arch_frame_init):
-    push    %ebp                    /* function prologue for backtrace */
-    mov     %esp,%ebp
-    push    %esi                    /* save %esi before using it as a tmpreg */
-
-    /*
-     * At this point we are executing on the main() stack:
-     * ----------------
-     * stack_frame ptr      0xc(%esp)
-     * ----------------
-     * return address       0x8(%esp)
-     * ----------------
-     * saved ebp            0x4(%esp)
-     * ----------------
-     * saved esi            0x0(%esp)
-     * ----------------
-     */
-    movl    0xc(%esp),%esi          /* %esi = 'sf' */
-    movl    %esp,0x0(%esi)          /* sf->mainsp = %esp */
-
-    /*
-     * Switch the stack so the stack pointer stored in 'sf->sf_jb' points
-     * to the task stack. This is slightly complicated because OS X wants
-     * the incoming stack pointer to be 16-byte aligned.
-     *
-     * ----------------
-     * sf (other fields)
-     * ----------------
-     * sf (sf_jb)           0x4(%esi)
-     * ----------------
-     * sf (sf_mainsp)       0x0(%esi)
-     * ----------------
-     * alignment padding    variable (0 to 12 bytes)
-     * ----------------
-     * savemask (0)         0x4(%esp)
-     * ----------------
-     * pointer to sf_jb     0x0(%esp)
-     * ----------------
-     */
-    movl    %esi,%esp
-    subl    $0x8,%esp               /* make room for sigsetjmp() arguments */
-    andl    $0xfffffff0,%esp        /* align %esp on 16-byte boundary */
-    leal    0x4(%esi),%eax          /* %eax = &sf->sf_jb */
-    movl    %eax,0x0(%esp)
-    movl    $0, 0x4(%esp)
-    call    CNAME(sigsetjmp)        /* sigsetjmp(sf->sf_jb, 0) */
-    test    %eax,%eax
-    jne     1f
-    movl    0x0(%esi),%esp          /* switch back to the main() stack */
-    pop     %esi
-    pop     %ebp
-    ret                             /* return to os_arch_task_stack_init() */
-1:
-    lea     2f,%ecx
-    push    %ecx                    /* retaddr */
-    push    $0                      /* frame pointer */
-    movl    %esp,%ebp               /* handcrafted prologue for backtrace */
-    push    %eax                    /* rc */
-    push    %esi                    /* sf */
-    call    CNAME(os_arch_task_start) /* os_arch_task_start(sf, rc) */
-    /* never returns */
-2:
-    nop

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/src/arch/sim/os_fault.c
----------------------------------------------------------------------
diff --git a/libs/os/src/arch/sim/os_fault.c b/libs/os/src/arch/sim/os_fault.c
deleted file mode 100644
index 15c40fe..0000000
--- a/libs/os/src/arch/sim/os_fault.c
+++ /dev/null
@@ -1,34 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-#include <stdio.h>
-#include <string.h>
-#include <unistd.h>
-
-#include "os/os.h"
-#include "os_priv.h"
-
-void
-__assert_func(const char *file, int line, const char *func, const char *e)
-{
-    char msg[256];
-
-    snprintf(msg, sizeof(msg), "assert at %s:%d\n", file, line);
-    write(1, msg, strlen(msg));
-    _exit(1);
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/src/os.c
----------------------------------------------------------------------
diff --git a/libs/os/src/os.c b/libs/os/src/os.c
deleted file mode 100644
index 3089a97..0000000
--- a/libs/os/src/os.c
+++ /dev/null
@@ -1,191 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include "sysinit/sysinit.h"
-#include "os/os.h"
-#include "os/queue.h"
-#include "os/os_dev.h"
-#include "os_priv.h"
-
-#include "hal/hal_os_tick.h"
-#include "hal/hal_bsp.h"
-#include "hal/hal_watchdog.h"
-
-#include <assert.h>
-
-struct os_task g_idle_task;
-os_stack_t g_idle_task_stack[OS_STACK_ALIGN(OS_IDLE_STACK_SIZE)];
-
-uint32_t g_os_idle_ctr;
-/* Default zero.  Set by the architecture specific code when os is started.
- */
-int g_os_started;
-
-#ifdef ARCH_sim
-#define MIN_IDLE_TICKS  1
-#else
-#define MIN_IDLE_TICKS  (100 * OS_TICKS_PER_SEC / 1000) /* 100 msec */
-#endif
-#define MAX_IDLE_TICKS  (600 * OS_TICKS_PER_SEC)        /* 10 minutes */
-
-
-/**
- * Idle operating system task, runs when no other tasks are running.
- * The idle task operates in tickless mode, which means it looks for
- * the next time an event in the system needs to run, and then tells
- * the architecture specific functions to sleep until that time.
- *
- * @param arg unused
- */
-void
-os_idle_task(void *arg)
-{
-    os_sr_t sr;
-    os_time_t now;
-    os_time_t iticks, sticks, cticks;
-    os_time_t sanity_last;
-    os_time_t sanity_itvl_ticks;
-
-    sanity_itvl_ticks = (MYNEWT_VAL(SANITY_INTERVAL) * OS_TICKS_PER_SEC) / 1000;
-    sanity_last = 0;
-
-    hal_watchdog_tickle();
-
-    while (1) {
-        ++g_os_idle_ctr;
-
-        now = os_time_get();
-        if (OS_TIME_TICK_GT(now, sanity_last + sanity_itvl_ticks)) {
-            os_sanity_run();
-            /* Tickle the watchdog after successfully running sanity */
-            hal_watchdog_tickle();
-            sanity_last = now;
-        }
-
-        OS_ENTER_CRITICAL(sr);
-        now = os_time_get();
-        sticks = os_sched_wakeup_ticks(now);
-        cticks = os_callout_wakeup_ticks(now);
-        iticks = min(sticks, cticks);
-        /* Wakeup in time to run sanity as well from the idle context,
-         * as the idle task does not schedule itself.
-         */
-        iticks = min(iticks, ((sanity_last + sanity_itvl_ticks) - now));
-
-        if (iticks < MIN_IDLE_TICKS) {
-            iticks = 0;
-        } else if (iticks > MAX_IDLE_TICKS) {
-            iticks = MAX_IDLE_TICKS;
-        } else {
-            /* NOTHING */
-        }
-        /* Tell the architecture specific support to put the processor to sleep
-         * for 'n' ticks.
-         */
-        os_tick_idle(iticks);
-        OS_EXIT_CRITICAL(sr);
-    }
-}
-
-/**
- * Has the operating system started.
- *
- * @return 1 if the operating system has started, 0 if it hasn't
- */
-int
-os_started(void)
-{
-    return (g_os_started);
-}
-
-
-void
-os_init_idle_task(void)
-{
-    int rc;
-
-    rc = os_task_init(&g_idle_task, "idle", os_idle_task, NULL,
-            OS_IDLE_PRIO, OS_WAIT_FOREVER, g_idle_task_stack,
-            OS_STACK_ALIGN(OS_IDLE_STACK_SIZE));
-    assert(rc == 0);
-
-    /* Initialize sanity */
-    rc = os_sanity_init();
-    assert(rc == 0);
-
-    assert(MYNEWT_VAL(WATCHDOG_INTERVAL) - 200 > MYNEWT_VAL(SANITY_INTERVAL));
-
-    hal_watchdog_init(MYNEWT_VAL(WATCHDOG_INTERVAL));
-}
-
-/**
- * Initialize the operating system, calls into the architecture specific
- * support to initialize the operating system.
- */
-void
-os_init(void)
-{
-    os_error_t err;
-
-    TAILQ_INIT(&g_callout_list);
-    STAILQ_INIT(&g_os_task_list);
-
-    /* Initialize device list. */
-    os_dev_reset();
-
-    err = os_arch_os_init();
-    assert(err == OS_OK);
-
-    /* Call bsp related OS initializations */
-    bsp_init();
-
-    err = (os_error_t) os_dev_initialize_all(OS_DEV_INIT_PRIMARY);
-    assert(err == OS_OK);
-
-    err = (os_error_t) os_dev_initialize_all(OS_DEV_INIT_SECONDARY);
-    assert(err == OS_OK);
-
-    /* Initialize target-specific packages. */
-    sysinit();
-}
-
-/**
- * Start the operating system, calls into the architecture specific support
- * to start the operating system.
- */
-void
-os_start(void)
-{
-    os_error_t err;
-
-    err = os_dev_initialize_all(OS_DEV_INIT_KERNEL);
-    assert(err == OS_OK);
-
-    /* Enable the watchdog prior to starting the OS */
-    hal_watchdog_enable();
-
-    err = os_arch_os_start();
-    assert(err == OS_OK);
-}
-
-void
-os_pkg_init(void)
-{
-    os_msys_init();
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/src/os_callout.c
----------------------------------------------------------------------
diff --git a/libs/os/src/os_callout.c b/libs/os/src/os_callout.c
deleted file mode 100644
index bc36a19..0000000
--- a/libs/os/src/os_callout.c
+++ /dev/null
@@ -1,200 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include "os/os.h"
-#include "os_priv.h"
-
-#include <assert.h>
-#include <string.h>
-
-struct os_callout_list g_callout_list;
-
-static void
-_os_callout_init(struct os_callout *c, struct os_eventq *evq, void *ev_arg)
-{
-    memset(c, 0, sizeof(*c));
-    c->c_ev.ev_type = OS_EVENT_T_TIMER;
-    c->c_ev.ev_arg = ev_arg;
-    c->c_evq = evq;
-}
-
-/**
- * Initialize a callout.
- *
- * Callouts are used to schedule events in the future onto a task's event
- * queue.  Callout timers are scheduled using the os_callout_reset()
- * function.  When the timer expires, an event is posted to the event
- * queue specified in os_callout_func_init().  The event argument given here
- * is posted in the ev_arg field of that event.
- *
- * @param c The callout to initialize
- * @param evq The event queue to post an OS_EVENT_T_TIMER event to
- * @param timo_func The function to call on this callout for the host task
- *                  used to provide multiple timer events to a task
- *                  (this can be NULL.)
- * @param ev_arg The argument to provide to the event when posting the
- *               timer.
- */
-void
-os_callout_func_init(struct os_callout_func *cf, struct os_eventq *evq,
-  os_callout_func_t timo_func, void *ev_arg)
-{
-    _os_callout_init(&cf->cf_c, evq, ev_arg);
-    cf->cf_func = timo_func;
-}
-
-/**
- * Stop the callout from firing off, any pending events will be cleared.
- *
- * @param c The callout to stop
- */
-void
-os_callout_stop(struct os_callout *c)
-{
-    os_sr_t sr;
-
-    OS_ENTER_CRITICAL(sr);
-
-    if (os_callout_queued(c)) {
-        TAILQ_REMOVE(&g_callout_list, c, c_next);
-        c->c_next.tqe_prev = NULL;
-    }
-
-    if (c->c_evq) {
-        os_eventq_remove(c->c_evq, &c->c_ev);
-    }
-
-    OS_EXIT_CRITICAL(sr);
-}
-
-/**
- * Reset the callout to fire off in 'ticks' ticks.
- *
- * @param c The callout to reset
- * @param ticks The number of ticks to wait before posting an event
- *
- * @return 0 on success, non-zero on failure
- */
-int
-os_callout_reset(struct os_callout *c, int32_t ticks)
-{
-    struct os_callout *entry;
-    os_sr_t sr;
-    int rc;
-
-    if (ticks < 0) {
-        rc = OS_EINVAL;
-        goto err;
-    }
-
-    OS_ENTER_CRITICAL(sr);
-
-    os_callout_stop(c);
-
-    if (ticks == 0) {
-        ticks = 1;
-    }
-
-    c->c_ticks = os_time_get() + ticks;
-
-    entry = NULL;
-    TAILQ_FOREACH(entry, &g_callout_list, c_next) {
-        if (OS_TIME_TICK_LT(c->c_ticks, entry->c_ticks)) {
-            break;
-        }
-    }
-
-    if (entry) {
-        TAILQ_INSERT_BEFORE(entry, c, c_next);
-    } else {
-        TAILQ_INSERT_TAIL(&g_callout_list, c, c_next);
-    }
-
-    OS_EXIT_CRITICAL(sr);
-
-    return (0);
-err:
-    return (rc);
-}
-
-/**
- * This function is called by the OS in the time tick.  It searches the list
- * of callouts, and sees if any of them are ready to run.  If they are ready
- * to run, it posts an event for each callout that's ready to run,
- * to the event queue provided to os_callout_func_init().
- */
-void
-os_callout_tick(void)
-{
-    os_sr_t sr;
-    struct os_callout *c;
-    uint32_t now;
-
-    now = os_time_get();
-
-    while (1) {
-        OS_ENTER_CRITICAL(sr);
-        c = TAILQ_FIRST(&g_callout_list);
-        if (c) {
-            if (OS_TIME_TICK_GEQ(now, c->c_ticks)) {
-                TAILQ_REMOVE(&g_callout_list, c, c_next);
-                c->c_next.tqe_prev = NULL;
-            } else {
-                c = NULL;
-            }
-        }
-        OS_EXIT_CRITICAL(sr);
-
-        if (c) {
-            os_eventq_put(c->c_evq, &c->c_ev);
-        } else {
-            break;
-        }
-    }
-}
-
-/*
- * Returns the number of ticks to the first pending callout. If there are no
- * pending callouts then return OS_TIMEOUT_NEVER instead.
- *
- * @param now The time now
- *
- * @return Number of ticks to first pending callout
- */
-os_time_t
-os_callout_wakeup_ticks(os_time_t now)
-{
-    os_time_t rt;
-    struct os_callout *c;
-
-    OS_ASSERT_CRITICAL();
-
-    c = TAILQ_FIRST(&g_callout_list);
-    if (c != NULL) {
-        if (OS_TIME_TICK_GEQ(c->c_ticks, now)) {
-            rt = c->c_ticks - now;
-        } else {
-            rt = 0;     /* callout time is in the past */
-        }
-    } else {
-        rt = OS_TIMEOUT_NEVER;
-    }
-
-    return (rt);
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/src/os_dev.c
----------------------------------------------------------------------
diff --git a/libs/os/src/os_dev.c b/libs/os/src/os_dev.c
deleted file mode 100644
index fa8709b..0000000
--- a/libs/os/src/os_dev.c
+++ /dev/null
@@ -1,309 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include "os/os.h"
-#include "os/queue.h"
-#include "os/os_dev.h"
-
-#include <string.h>
-
-static STAILQ_HEAD(, os_dev) g_os_dev_list;
-
-static int
-os_dev_init(struct os_dev *dev, char *name, uint8_t stage,
-        uint8_t priority, os_dev_init_func_t od_init, void *arg)
-{
-    dev->od_name = name;
-    dev->od_stage = stage;
-    dev->od_priority = priority;
-    /* assume these are set after the fact. */
-    dev->od_flags = 0;
-    dev->od_open_ref = 0;
-    dev->od_init = od_init;
-    dev->od_init_arg = arg;
-    memset(&dev->od_handlers, 0, sizeof(dev->od_handlers));
-
-    return (0);
-}
-
-/**
- * Add the device to the device tree.  This is a private function.
- *
- * @param dev The device to add to the device tree.
- *
- * @return 0 on success, non-zero on failure.
- */
-static int
-os_dev_add(struct os_dev *dev)
-{
-    struct os_dev *cur_dev;
-
-    /* If no devices present, insert into head */
-    if (STAILQ_FIRST(&g_os_dev_list) == NULL) {
-        STAILQ_INSERT_HEAD(&g_os_dev_list, dev, od_next);
-        return (0);
-    }
-
-    /* Add devices to the list, sorted first by stage, then by
-     * priority.  Keep sorted in this order for initialization
-     * stage.
-     */
-    cur_dev = NULL;
-    STAILQ_FOREACH(cur_dev, &g_os_dev_list, od_next) {
-        if (cur_dev->od_stage > dev->od_stage) {
-            continue;
-        }
-
-        if (dev->od_priority >= cur_dev->od_priority) {
-            break;
-        }
-    }
-
-    if (cur_dev) {
-        STAILQ_INSERT_AFTER(&g_os_dev_list, cur_dev, dev, od_next);
-    } else {
-        STAILQ_INSERT_TAIL(&g_os_dev_list, dev, od_next);
-    }
-
-    return (0);
-}
-
-
-/**
- * Create a new device in the kernel.
- *
- * @param dev The device to create.
- * @param name The name of the device to create.
- * @param stage The stage to initialize that device to.
- * @param priority The priority of initializing that device
- * @param od_init The initialization function to call for this
- *                device.
- * @param arg The argument to provide this device initialization
- *            function.
- *
- * @return 0 on success, non-zero on failure.
- */
-int
-os_dev_create(struct os_dev *dev, char *name, uint8_t stage,
-        uint8_t priority, os_dev_init_func_t od_init, void *arg)
-{
-    int rc;
-
-    rc = os_dev_init(dev, name, stage, priority, od_init, arg);
-    if (rc != 0) {
-        goto err;
-    }
-
-    rc = os_dev_add(dev);
-    if (rc != 0) {
-        goto err;
-    }
-
-    return (0);
-err:
-    return (rc);
-}
-
-/**
- * Initialize all devices for a given state.
- *
- * @param stage The stage to initialize.
- *
- * @return 0 on success, non-zero on failure.
- */
-int
-os_dev_initialize_all(uint8_t stage)
-{
-    struct os_dev *dev;
-    int rc;
-
-    STAILQ_FOREACH(dev, &g_os_dev_list, od_next) {
-        if (dev->od_stage == stage) {
-            rc = dev->od_init(dev, dev->od_init_arg);
-            if (rc != 0) {
-                if (dev->od_flags & OS_DEV_F_INIT_CRITICAL) {
-                    goto err;
-                }
-            } else {
-                dev->od_flags |= OS_DEV_F_STATUS_READY;
-            }
-        }
-    }
-
-    return (0);
-err:
-    return (rc);
-}
-
-/**
- * Suspend all devices.
- *
- * @param dev The device to suspend
- * @param suspend_t The number of ticks to suspend this device for
- * @param force Whether or not to force suspending the device
- *
- * @return 0 on success, or a non-zero error code if one of the devices
- *                       returned it.
- */
-int
-os_dev_suspend_all(os_time_t suspend_t, uint8_t force)
-{
-    struct os_dev *dev;
-    int suspend_failure;
-    int rc;
-
-    suspend_failure = 0;
-    STAILQ_FOREACH(dev, &g_os_dev_list, od_next) {
-        rc = os_dev_suspend(dev, suspend_t, force);
-        if (rc != 0) {
-            suspend_failure = OS_ERROR;
-        }
-    }
-
-    return (suspend_failure);
-}
-
-/**
- * Resume all the devices that were suspended.
- *
- * @return 0 on success, -1 if any of the devices have failed to resume.
- */
-int
-os_dev_resume_all(void)
-{
-    struct os_dev *dev;
-    int rc;
-
-    STAILQ_FOREACH(dev, &g_os_dev_list, od_next) {
-        rc = os_dev_resume(dev);
-        if (rc != 0) {
-            goto err;
-        }
-    }
-
-    return (0);
-err:
-    return (rc);
-}
-
-/**
- * Lookup a device by name, internal function only.
- *
- * @param name The name of the device to look up.
- *
- * @return A pointer to the device corresponding to name, or NULL if not found.
- */
-static struct os_dev *
-os_dev_lookup(char *name)
-{
-    struct os_dev *dev;
-
-    dev = NULL;
-    STAILQ_FOREACH(dev, &g_os_dev_list, od_next) {
-        if (!strcmp(dev->od_name, name)) {
-            break;
-        }
-    }
-    return (dev);
-}
-
-/**
- * Open a device.
- *
- * @param dev The device to open
- * @param timo The timeout to open the device, if not specified.
- * @param arg The argument to the device open() call.
- *
- * @return 0 on success, non-zero on failure.
- */
-struct os_dev *
-os_dev_open(char *devname, uint32_t timo, void *arg)
-{
-    struct os_dev *dev;
-    os_sr_t sr;
-    int rc;
-
-    dev = os_dev_lookup(devname);
-    if (dev == NULL) {
-        return (NULL);
-    }
-
-    /* Device is not ready to be opened. */
-    if ((dev->od_flags & OS_DEV_F_STATUS_READY) == 0) {
-        return (NULL);
-    }
-
-    if (dev->od_handlers.od_open) {
-        rc = dev->od_handlers.od_open(dev, timo, arg);
-        if (rc != 0) {
-            goto err;
-        }
-    }
-
-    OS_ENTER_CRITICAL(sr);
-    ++dev->od_open_ref;
-    dev->od_flags |= OS_DEV_F_STATUS_OPEN;
-    OS_EXIT_CRITICAL(sr);
-
-    return (dev);
-err:
-    return (NULL);
-}
-
-/**
- * Close a device.
- *
- * @param dev The device to close
- *
- * @return 0 on success, non-zero on failure.
- */
-int
-os_dev_close(struct os_dev *dev)
-{
-    int rc;
-    os_sr_t sr;
-
-    if (dev->od_handlers.od_close) {
-        rc = dev->od_handlers.od_close(dev);
-        if (rc != 0) {
-            goto err;
-        }
-    }
-
-    OS_ENTER_CRITICAL(sr);
-    if (--dev->od_open_ref == 0) {
-        dev->od_flags &= ~OS_DEV_F_STATUS_OPEN;
-    }
-    OS_EXIT_CRITICAL(sr);
-
-    return (0);
-err:
-    return (rc);
-}
-
-/**
- * Clears the device list.  This function does not close any devices or free
- * any resources; its purpose is to allow a full system reset between unit
- * tests.
- */
-void
-os_dev_reset(void)
-{
-    STAILQ_INIT(&g_os_dev_list);
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/src/os_eventq.c
----------------------------------------------------------------------
diff --git a/libs/os/src/os_eventq.c b/libs/os/src/os_eventq.c
deleted file mode 100644
index f9cc283..0000000
--- a/libs/os/src/os_eventq.c
+++ /dev/null
@@ -1,235 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-
-#include "os/os.h"
-
-#include <string.h>
-
-/**
- * Initialize the event queue
- *
- * @param evq The event queue to initialize
- */
-void
-os_eventq_init(struct os_eventq *evq)
-{
-    memset(evq, 0, sizeof(*evq));
-    STAILQ_INIT(&evq->evq_list);
-}
-
-/**
- * Put an event on the event queue.
- *
- * @param evq The event queue to put an event on 
- * @param ev The event to put on the queue
- */
-void
-os_eventq_put(struct os_eventq *evq, struct os_event *ev)
-{
-    int resched;
-    os_sr_t sr;
-
-    OS_ENTER_CRITICAL(sr);
-
-    /* Do not queue if already queued */
-    if (OS_EVENT_QUEUED(ev)) {
-        OS_EXIT_CRITICAL(sr);
-        return;
-    }
-
-    /* Queue the event */
-    ev->ev_queued = 1;
-    STAILQ_INSERT_TAIL(&evq->evq_list, ev, ev_next);
-
-    resched = 0;
-    if (evq->evq_task) {
-        /* If task waiting on event, wake it up.
-         * Check if task is sleeping, because another event 
-         * queue may have woken this task up beforehand.
-         */
-        if (evq->evq_task->t_state == OS_TASK_SLEEP) {
-            os_sched_wakeup(evq->evq_task);
-            resched = 1;
-        }
-        /* Either way, NULL out the task, because the task will
-         * be awake upon exit of this function.
-         */
-        evq->evq_task = NULL;
-    }
-
-    OS_EXIT_CRITICAL(sr);
-
-    if (resched) {
-        os_sched(NULL);
-    }
-}
-
-/**
- * Pull a single item from an event queue.  This function blocks until there 
- * is an item on the event queue to read.
- *
- * @param evq The event queue to pull an event from
- *
- * @return The event from the queue
- */
-struct os_event *
-os_eventq_get(struct os_eventq *evq)
-{
-    struct os_event *ev;
-    os_sr_t sr;
-
-    OS_ENTER_CRITICAL(sr);
-pull_one:
-    ev = STAILQ_FIRST(&evq->evq_list);
-    if (ev) {
-        STAILQ_REMOVE(&evq->evq_list, ev, os_event, ev_next);
-        ev->ev_queued = 0;
-    } else {
-        evq->evq_task = os_sched_get_current_task();
-        os_sched_sleep(evq->evq_task, OS_TIMEOUT_NEVER);
-        OS_EXIT_CRITICAL(sr);
-
-        os_sched(NULL);
-
-        OS_ENTER_CRITICAL(sr);
-        evq->evq_task = NULL;
-        goto pull_one;
-    }
-    OS_EXIT_CRITICAL(sr);
-
-    return (ev);
-}
-
-static struct os_event *
-os_eventq_poll_0timo(struct os_eventq **evq, int nevqs)
-{
-    struct os_event *ev;
-    os_sr_t sr;
-    int i;
-
-    ev = NULL;
-
-    OS_ENTER_CRITICAL(sr);
-    for (i = 0; i < nevqs; i++) {
-        ev = STAILQ_FIRST(&evq[i]->evq_list);
-        if (ev) {
-            STAILQ_REMOVE(&evq[i]->evq_list, ev, os_event, ev_next);
-            ev->ev_queued = 0;
-            break;
-        }
-    }
-    OS_EXIT_CRITICAL(sr);
-
-    return ev;
-}
-
-/**
- * Poll the list of event queues specified by the evq parameter 
- * (size nevqs), and return the "first" event available on any of 
- * the queues.  Event queues are searched in the order that they 
- * are passed in the array.
- *
- * @param evq Array of event queues
- * @param nevqs Number of event queues in evq
- * @param timo Timeout, forever if OS_WAIT_FOREVER is passed to poll.
- *
- * @return An event, or NULL if no events available
- */
-struct os_event *
-os_eventq_poll(struct os_eventq **evq, int nevqs, os_time_t timo)
-{
-    struct os_event *ev;
-    struct os_task *cur_t;
-    int i, j;
-    os_sr_t sr;
-
-    /* If the timeout is 0, don't involve the scheduler at all.  Grab an event
-     * if one is available, else return immediately.
-     */
-    if (timo == 0) {
-        return os_eventq_poll_0timo(evq, nevqs);
-    }
-
-    ev = NULL;
-
-    OS_ENTER_CRITICAL(sr);
-    cur_t = os_sched_get_current_task();
-
-    for (i = 0; i < nevqs; i++) {
-        ev = STAILQ_FIRST(&evq[i]->evq_list);
-        if (ev) {
-            STAILQ_REMOVE(&evq[i]->evq_list, ev, os_event, ev_next);
-            ev->ev_queued = 0;
-            /* Reset the items that already have an evq task set. */
-            for (j = 0; j < i; j++) {
-                evq[j]->evq_task = NULL;
-            }
-
-            OS_EXIT_CRITICAL(sr);
-            goto has_event;
-        }
-        evq[i]->evq_task = cur_t;
-    }
-
-    os_sched_sleep(cur_t, timo);
-    OS_EXIT_CRITICAL(sr);
-
-    os_sched(NULL);
-
-    OS_ENTER_CRITICAL(sr);
-    for (i = 0; i < nevqs; i++) {
-        /* Go through the entire loop to clear the evq_task variable, 
-         * given this task is no longer sleeping on the event queues.
-         * Return the first event found, so only grab the event if 
-         * we haven't found one.
-         */
-        if (!ev) {
-            ev = STAILQ_FIRST(&evq[i]->evq_list);
-            if (ev) {
-                STAILQ_REMOVE(&evq[i]->evq_list, ev, os_event, ev_next);
-                ev->ev_queued = 0;
-            }
-        }
-        evq[i]->evq_task = NULL;
-    }
-    OS_EXIT_CRITICAL(sr);
-
-has_event:
-    return (ev);
-}
-
-/**
- * Remove an event from the queue.
- *
- * @param evq The event queue to remove the event from
- * @param ev  The event to remove from the queue
- */
-void
-os_eventq_remove(struct os_eventq *evq, struct os_event *ev)
-{
-    os_sr_t sr;
-
-    OS_ENTER_CRITICAL(sr);
-    if (OS_EVENT_QUEUED(ev)) {
-        STAILQ_REMOVE(&evq->evq_list, ev, os_event, ev_next);
-    }
-    ev->ev_queued = 0;
-    OS_EXIT_CRITICAL(sr);
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/src/os_heap.c
----------------------------------------------------------------------
diff --git a/libs/os/src/os_heap.c b/libs/os/src/os_heap.c
deleted file mode 100644
index 5f5af95..0000000
--- a/libs/os/src/os_heap.c
+++ /dev/null
@@ -1,106 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-
-#include <assert.h>
-#include "os/os_mutex.h"
-#include "os/os_heap.h"
-
-static struct os_mutex os_malloc_mutex;
-
-static void
-os_malloc_lock(void)
-{
-    int rc;
-
-    if (g_os_started) {
-        rc = os_mutex_pend(&os_malloc_mutex, 0xffffffff);
-        assert(rc == 0);
-    }
-}
-
-static void
-os_malloc_unlock(void)
-{
-    int rc;
-
-    if (g_os_started) {
-        rc = os_mutex_release(&os_malloc_mutex);
-        assert(rc == 0);
-    }
-}
-
-/**
- * Operating system level malloc().   This ensures that a safe malloc occurs
- * within the context of the OS.  Depending on platform, the OS may rely on
- * libc's malloc() implementation, which is not guaranteed to be thread-safe.
- * This malloc() will always be thread-safe.
- *
- * @param size The number of bytes to allocate
- *
- * @return A pointer to the memory region allocated.
- */
-void *
-os_malloc(size_t size)
-{
-    void *ptr;
-
-    os_malloc_lock();
-    ptr = malloc(size);
-    os_malloc_unlock();
-
-    return ptr;
-}
-
-/**
- * Operating system level free().  See description of os_malloc() for reasoning.
- *
- * Free's memory allocated by malloc.
- *
- * @param mem The memory to free.
- */
-void
-os_free(void *mem)
-{
-    os_malloc_lock();
-    free(mem);
-    os_malloc_unlock();
-}
-
-/**
- * Operating system level realloc(). See description of os_malloc() for reasoning.
- *
- * Reallocates the memory at ptr, to be size contiguouos bytes.
- *
- * @param ptr A pointer to the memory to allocate
- * @param size The number of contiguouos bytes to allocate at that location
- *
- * @return A pointer to memory of size, or NULL on failure to allocate
- */
-void *
-os_realloc(void *ptr, size_t size)
-{
-    void *new_ptr;
-
-    os_malloc_lock();
-    new_ptr = realloc(ptr, size);
-    os_malloc_unlock();
-
-    return new_ptr;
-}


[22/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/lbaselib.c
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/lbaselib.c b/libs/elua/elua_base/src/lbaselib.c
deleted file mode 100644
index f204c1b..0000000
--- a/libs/elua/elua_base/src/lbaselib.c
+++ /dev/null
@@ -1,718 +0,0 @@
-/*
-** $Id: lbaselib.c,v 1.191.1.6 2008/02/14 16:46:22 roberto Exp $
-** Basic library
-** See Copyright Notice in lua.h
-*/
-
-
-
-#include <ctype.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#define lbaselib_c
-#define LUA_LIB
-
-#include "lua.h"
-
-#include "lauxlib.h"
-#include "lualib.h"
-#include "lrotable.h"
-
-#ifndef LUA_CROSS_COMPILER
-#include "platform_conf.h"
-#endif
-#ifdef MYNEWT
-#include <console/console.h>
-#endif
-
-/*
-** If your system does not support `stdout', you can just remove this function.
-** If you need, you can define your own `print' function, following this
-** model but changing `fputs' to put the strings at a proper place
-** (a console window or a log file, for instance).
-*/
-static int luaB_print (lua_State *L) {
-  int n = lua_gettop(L);  /* number of arguments */
-  int i;
-  lua_getglobal(L, "tostring");
-  for (i=1; i<=n; i++) {
-    const char *s;
-    lua_pushvalue(L, -1);  /* function to be called */
-    lua_pushvalue(L, i);   /* value to print */
-    lua_call(L, 1, 1);
-    s = lua_tostring(L, -1);  /* get result */
-    if (s == NULL)
-      return luaL_error(L, LUA_QL("tostring") " must return a string to "
-                           LUA_QL("print"));
-#ifndef MYNEWT
-    if (i>1) fputs("\t", stdout);
-    fputs(s, stdout);
-#else
-    if (i>1) console_write("\t", 1);
-    console_write(s, strlen(s));
-#endif
-    lua_pop(L, 1);  /* pop result */
-  }
-#ifndef MYNEWT
-  fputs("\n", stdout);
-#else
-  console_write("\n", 1);
-#endif
-  return 0;
-}
-
-
-static int luaB_tonumber (lua_State *L) {
-  int base = luaL_optint(L, 2, 10);
-  if (base == 10) {  /* standard conversion */
-    luaL_checkany(L, 1);
-    if (lua_isnumber(L, 1)) {
-      lua_pushnumber(L, lua_tonumber(L, 1));
-      return 1;
-    }
-  }
-  else {
-    const char *s1 = luaL_checkstring(L, 1);
-    char *s2;
-    unsigned long n;
-    luaL_argcheck(L, 2 <= base && base <= 36, 2, "base out of range");
-    n = strtoul(s1, &s2, base);
-    if (s1 != s2) {  /* at least one valid digit? */
-      while (isspace((unsigned char)(*s2))) s2++;  /* skip trailing spaces */
-      if (*s2 == '\0') {  /* no invalid trailing characters? */
-        lua_pushnumber(L, (lua_Number)n);
-        return 1;
-      }
-    }
-  }
-  lua_pushnil(L);  /* else not a number */
-  return 1;
-}
-
-
-static int luaB_error (lua_State *L) {
-  int level = luaL_optint(L, 2, 1);
-  lua_settop(L, 1);
-  if (lua_isstring(L, 1) && level > 0) {  /* add extra information? */
-    luaL_where(L, level);
-    lua_pushvalue(L, 1);
-    lua_concat(L, 2);
-  }
-  return lua_error(L);
-}
-
-
-static int luaB_getmetatable (lua_State *L) {
-  luaL_checkany(L, 1);
-  if (!lua_getmetatable(L, 1)) {
-    lua_pushnil(L);
-    return 1;  /* no metatable */
-  }
-  luaL_getmetafield(L, 1, "__metatable");
-  return 1;  /* returns either __metatable field (if present) or metatable */
-}
-
-
-static int luaB_setmetatable (lua_State *L) {
-  int t = lua_type(L, 2);
-  luaL_checktype(L, 1, LUA_TTABLE);
-  luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE || t == LUA_TROTABLE, 2,
-                    "nil or table expected");
-  if (luaL_getmetafield(L, 1, "__metatable"))
-    luaL_error(L, "cannot change a protected metatable");
-  lua_settop(L, 2);
-  lua_setmetatable(L, 1);
-  return 1;
-}
-
-
-static void getfunc (lua_State *L, int opt) {
-  if (lua_isfunction(L, 1)) lua_pushvalue(L, 1);
-  else {
-    lua_Debug ar;
-    int level = opt ? luaL_optint(L, 1, 1) : luaL_checkint(L, 1);
-    luaL_argcheck(L, level >= 0, 1, "level must be non-negative");
-    if (lua_getstack(L, level, &ar) == 0)
-      luaL_argerror(L, 1, "invalid level");
-    lua_getinfo(L, "f", &ar);
-    if (lua_isnil(L, -1))
-      luaL_error(L, "no function environment for tail call at level %d",
-                    level);
-  }
-}
-
-
-static int luaB_getfenv (lua_State *L) {
-  getfunc(L, 1);
-  if (lua_iscfunction(L, -1))  /* is a C function? */
-    lua_pushvalue(L, LUA_GLOBALSINDEX);  /* return the thread's global env. */
-  else
-    lua_getfenv(L, -1);
-  return 1;
-}
-
-
-static int luaB_setfenv (lua_State *L) {
-  luaL_checktype(L, 2, LUA_TTABLE);
-  getfunc(L, 0);
-  lua_pushvalue(L, 2);
-  if (lua_isnumber(L, 1) && lua_tonumber(L, 1) == 0) {
-    /* change environment of current thread */
-    lua_pushthread(L);
-    lua_insert(L, -2);
-    lua_setfenv(L, -2);
-    return 0;
-  }
-  else if (lua_iscfunction(L, -2) || lua_setfenv(L, -2) == 0)
-    luaL_error(L,
-          LUA_QL("setfenv") " cannot change environment of given object");
-  return 1;
-}
-
-
-static int luaB_rawequal (lua_State *L) {
-  luaL_checkany(L, 1);
-  luaL_checkany(L, 2);
-  lua_pushboolean(L, lua_rawequal(L, 1, 2));
-  return 1;
-}
-
-
-static int luaB_rawget (lua_State *L) {
-  luaL_checkanytable(L, 1);
-  luaL_checkany(L, 2);
-  lua_settop(L, 2);
-  lua_rawget(L, 1);
-  return 1;
-}
-
-static int luaB_rawset (lua_State *L) {
-  luaL_checktype(L, 1, LUA_TTABLE);
-  luaL_checkany(L, 2);
-  luaL_checkany(L, 3);
-  lua_settop(L, 3);
-  lua_rawset(L, 1);
-  return 1;
-}
-
-
-static int luaB_gcinfo (lua_State *L) {
-  lua_pushinteger(L, lua_getgccount(L));
-  return 1;
-}
-
-
-static int luaB_collectgarbage (lua_State *L) {
-  static const char *const opts[] = {"stop", "restart", "collect",
-    "count", "step", "setpause", "setstepmul","setmemlimit","getmemlimit", NULL};
-  static const int optsnum[] = {LUA_GCSTOP, LUA_GCRESTART, LUA_GCCOLLECT,
-    LUA_GCCOUNT, LUA_GCSTEP, LUA_GCSETPAUSE, LUA_GCSETSTEPMUL,
-		LUA_GCSETMEMLIMIT,LUA_GCGETMEMLIMIT};
-  int o = luaL_checkoption(L, 1, "collect", opts);
-  int ex = luaL_optint(L, 2, 0);
-  int res = lua_gc(L, optsnum[o], ex);
-  switch (optsnum[o]) {
-    case LUA_GCCOUNT: {
-      int b = lua_gc(L, LUA_GCCOUNTB, 0);
-      lua_pushnumber(L, res + ((lua_Number)b/1024));
-      return 1;
-    }
-    case LUA_GCSTEP: {
-      lua_pushboolean(L, res);
-      return 1;
-    }
-    default: {
-      lua_pushnumber(L, res);
-      return 1;
-    }
-  }
-}
-
-
-static int luaB_type (lua_State *L) {
-  luaL_checkany(L, 1);
-  lua_pushstring(L, luaL_typename(L, 1));
-  return 1;
-}
-
-
-static int luaB_next (lua_State *L) {
-  luaL_checkanytable(L, 1);
-  lua_settop(L, 2);  /* create a 2nd argument if there isn't one */
-  if (lua_next(L, 1))
-    return 2;
-  else {
-    lua_pushnil(L);
-    return 1;
-  }
-}
-
-
-static int luaB_pairs (lua_State *L) {
-  luaL_checkanytable(L, 1);
-  lua_pushvalue(L, lua_upvalueindex(1));  /* return generator, */
-  lua_pushvalue(L, 1);  /* state, */
-  lua_pushnil(L);  /* and initial value */
-  return 3;
-}
-
-
-static int ipairsaux (lua_State *L) {
-  int i = luaL_checkint(L, 2);
-  luaL_checkanytable(L, 1);
-  i++;  /* next value */
-  lua_pushinteger(L, i);
-  lua_rawgeti(L, 1, i);
-  return (lua_isnil(L, -1)) ? 0 : 2;
-}
-
-
-static int luaB_ipairs (lua_State *L) {
-  luaL_checkanytable(L, 1);
-  lua_pushvalue(L, lua_upvalueindex(1));  /* return generator, */
-  lua_pushvalue(L, 1);  /* state, */
-  lua_pushinteger(L, 0);  /* and initial value */
-  return 3;
-}
-
-
-static int load_aux (lua_State *L, int status) {
-  if (status == 0)  /* OK? */
-    return 1;
-  else {
-    lua_pushnil(L);
-    lua_insert(L, -2);  /* put before error message */
-    return 2;  /* return nil plus error message */
-  }
-}
-
-
-static int luaB_loadstring (lua_State *L) {
-  size_t l;
-  const char *s = luaL_checklstring(L, 1, &l);
-  const char *chunkname = luaL_optstring(L, 2, s);
-  return load_aux(L, luaL_loadbuffer(L, s, l, chunkname));
-}
-
-
-static int luaB_loadfile (lua_State *L) {
-  const char *fname = luaL_optstring(L, 1, NULL);
-  return load_aux(L, luaL_loadfile(L, fname));
-}
-
-
-/*
-** Reader for generic `load' function: `lua_load' uses the
-** stack for internal stuff, so the reader cannot change the
-** stack top. Instead, it keeps its resulting string in a
-** reserved slot inside the stack.
-*/
-static const char *generic_reader (lua_State *L, void *ud, size_t *size) {
-  (void)ud;  /* to avoid warnings */
-  if (L == NULL && size == NULL) // direct mode check, doesn't happen
-    return NULL;
-  luaL_checkstack(L, 2, "too many nested functions");
-  lua_pushvalue(L, 1);  /* get function */
-  lua_call(L, 0, 1);  /* call it */
-  if (lua_isnil(L, -1)) {
-    *size = 0;
-    return NULL;
-  }
-  else if (lua_isstring(L, -1)) {
-    lua_replace(L, 3);  /* save string in a reserved stack slot */
-    return lua_tolstring(L, 3, size);
-  }
-  else luaL_error(L, "reader function must return a string");
-  return NULL;  /* to avoid warnings */
-}
-
-
-static int luaB_load (lua_State *L) {
-  int status;
-  const char *cname = luaL_optstring(L, 2, "=(load)");
-  luaL_checktype(L, 1, LUA_TFUNCTION);
-  lua_settop(L, 3);  /* function, eventual name, plus one reserved slot */
-  status = lua_load(L, generic_reader, NULL, cname);
-  return load_aux(L, status);
-}
-
-
-static int luaB_dofile (lua_State *L) {
-  const char *fname = luaL_optstring(L, 1, NULL);
-  int n = lua_gettop(L);
-  if (luaL_loadfile(L, fname) != 0) lua_error(L);
-  lua_call(L, 0, LUA_MULTRET);
-  return lua_gettop(L) - n;
-}
-
-
-static int luaB_assert (lua_State *L) {
-  luaL_checkany(L, 1);
-  if (!lua_toboolean(L, 1))
-    return luaL_error(L, "%s", luaL_optstring(L, 2, "assertion failed!"));
-  return lua_gettop(L);
-}
-
-
-static int luaB_unpack (lua_State *L) {
-  int i, e, n;
-  luaL_checktype(L, 1, LUA_TTABLE);
-  i = luaL_optint(L, 2, 1);
-  e = luaL_opt(L, luaL_checkint, 3, luaL_getn(L, 1));
-  if (i > e) return 0;  /* empty range */
-  n = e - i + 1;  /* number of elements */
-  if (n <= 0 || !lua_checkstack(L, n))  /* n <= 0 means arith. overflow */
-    return luaL_error(L, "too many results to unpack");
-  lua_rawgeti(L, 1, i);  /* push arg[i] (avoiding overflow problems) */
-  while (i++ < e)  /* push arg[i + 1...e] */
-    lua_rawgeti(L, 1, i);
-  return n;
-}
-
-
-static int luaB_select (lua_State *L) {
-  int n = lua_gettop(L);
-  if (lua_type(L, 1) == LUA_TSTRING && *lua_tostring(L, 1) == '#') {
-    lua_pushinteger(L, n-1);
-    return 1;
-  }
-  else {
-    int i = luaL_checkint(L, 1);
-    if (i < 0) i = n + i;
-    else if (i > n) i = n;
-    luaL_argcheck(L, 1 <= i, 1, "index out of range");
-    return n - i;
-  }
-}
-
-
-static int luaB_pcall (lua_State *L) {
-  int status;
-  luaL_checkany(L, 1);
-  status = lua_pcall(L, lua_gettop(L) - 1, LUA_MULTRET, 0);
-  lua_pushboolean(L, (status == 0));
-  lua_insert(L, 1);
-  return lua_gettop(L);  /* return status + all results */
-}
-
-
-static int luaB_xpcall (lua_State *L) {
-  int status;
-  luaL_checkany(L, 2);
-  lua_settop(L, 2);
-  lua_insert(L, 1);  /* put error function under function to be called */
-  status = lua_pcall(L, 0, LUA_MULTRET, 1);
-  lua_pushboolean(L, (status == 0));
-  lua_replace(L, 1);
-  return lua_gettop(L);  /* return status + all results */
-}
-
-
-static int luaB_tostring (lua_State *L) {
-  luaL_checkany(L, 1);
-  if (luaL_callmeta(L, 1, "__tostring"))  /* is there a metafield? */
-    return 1;  /* use its value */
-  switch (lua_type(L, 1)) {
-    case LUA_TNUMBER:
-      lua_pushstring(L, lua_tostring(L, 1));
-      break;
-    case LUA_TSTRING:
-      lua_pushvalue(L, 1);
-      break;
-    case LUA_TBOOLEAN:
-      lua_pushstring(L, (lua_toboolean(L, 1) ? "true" : "false"));
-      break;
-    case LUA_TNIL:
-      lua_pushliteral(L, "nil");
-      break;
-    default:
-      lua_pushfstring(L, "%s: %p", luaL_typename(L, 1), lua_topointer(L, 1));
-      break;
-  }
-  return 1;
-}
-
-
-static int luaB_newproxy (lua_State *L) {
-  lua_settop(L, 1);
-  lua_newuserdata(L, 0);  /* create proxy */
-  if (lua_toboolean(L, 1) == 0)
-    return 1;  /* no metatable */
-  else if (lua_isboolean(L, 1)) {
-    lua_newtable(L);  /* create a new metatable `m' ... */
-    lua_pushvalue(L, -1);  /* ... and mark `m' as a valid metatable */
-    lua_pushboolean(L, 1);
-    lua_rawset(L, lua_upvalueindex(1));  /* weaktable[m] = true */
-  }
-  else {
-    int validproxy = 0;  /* to check if weaktable[metatable(u)] == true */
-    if (lua_getmetatable(L, 1)) {
-      lua_rawget(L, lua_upvalueindex(1));
-      validproxy = lua_toboolean(L, -1);
-      lua_pop(L, 1);  /* remove value */
-    }
-    luaL_argcheck(L, validproxy, 1, "boolean or proxy expected");
-    lua_getmetatable(L, 1);  /* metatable is valid; get it */
-  }
-  lua_setmetatable(L, 2);
-  return 1;
-}
-
-#define LUA_BASELIB_FUNCLIST\
-  {LSTRKEY("assert"), LFUNCVAL(luaB_assert)},\
-  {LSTRKEY("collectgarbage"), LFUNCVAL(luaB_collectgarbage)},\
-  {LSTRKEY("dofile"), LFUNCVAL(luaB_dofile)},\
-  {LSTRKEY("error"), LFUNCVAL(luaB_error)},\
-  {LSTRKEY("gcinfo"), LFUNCVAL(luaB_gcinfo)},\
-  {LSTRKEY("getfenv"), LFUNCVAL(luaB_getfenv)},\
-  {LSTRKEY("getmetatable"), LFUNCVAL(luaB_getmetatable)},\
-  {LSTRKEY("loadfile"), LFUNCVAL(luaB_loadfile)},\
-  {LSTRKEY("load"), LFUNCVAL(luaB_load)},\
-  {LSTRKEY("loadstring"), LFUNCVAL(luaB_loadstring)},\
-  {LSTRKEY("next"), LFUNCVAL(luaB_next)},\
-  {LSTRKEY("pcall"), LFUNCVAL(luaB_pcall)},\
-  {LSTRKEY("print"), LFUNCVAL(luaB_print)},\
-  {LSTRKEY("rawequal"), LFUNCVAL(luaB_rawequal)},\
-  {LSTRKEY("rawget"), LFUNCVAL(luaB_rawget)},\
-  {LSTRKEY("rawset"), LFUNCVAL(luaB_rawset)},\
-  {LSTRKEY("select"), LFUNCVAL(luaB_select)},\
-  {LSTRKEY("setfenv"), LFUNCVAL(luaB_setfenv)},\
-  {LSTRKEY("setmetatable"), LFUNCVAL(luaB_setmetatable)},\
-  {LSTRKEY("tonumber"), LFUNCVAL(luaB_tonumber)},\
-  {LSTRKEY("tostring"), LFUNCVAL(luaB_tostring)},\
-  {LSTRKEY("type"), LFUNCVAL(luaB_type)},\
-  {LSTRKEY("unpack"), LFUNCVAL(luaB_unpack)},\
-  {LSTRKEY("xpcall"), LFUNCVAL(luaB_xpcall)}
-  
-#if LUA_OPTIMIZE_MEMORY == 2
-#define MIN_OPT_LEVEL 2
-#include "lrodefs.h"
-const LUA_REG_TYPE base_funcs_list[] = {
-  LUA_BASELIB_FUNCLIST,
-  {LNILKEY, LNILVAL}
-};
-#endif
-
-
-static int luaB_index(lua_State *L) {
-#if LUA_OPTIMIZE_MEMORY == 2
-  int fres;
-  if ((fres = luaR_findfunction(L, base_funcs_list)) != 0)
-    return fres;
-#endif  
-  const char *keyname = luaL_checkstring(L, 2);
-  if (!strcmp(keyname, "_VERSION")) {
-    lua_pushliteral(L, LUA_VERSION);
-    return 1;
-  }
-  void *res = luaR_findglobal(keyname, strlen(keyname));
-  if (!res)
-    return 0;
-  else {
-    lua_pushrotable(L, res);
-    return 1;
-  }
-}
-
-static const luaL_Reg base_funcs[] = {
-#if LUA_OPTIMIZE_MEMORY != 2
-#undef MIN_OPT_LEVEL
-#define MIN_OPT_LEVEL 0
-#include "lrodefs.h"
-  LUA_BASELIB_FUNCLIST,
-#endif
-  {"__index", luaB_index},
-  {NULL, NULL}
-};
-
-
-/*
-** {======================================================
-** Coroutine library
-** =======================================================
-*/
-
-#define CO_RUN	0	/* running */
-#define CO_SUS	1	/* suspended */
-#define CO_NOR	2	/* 'normal' (it resumed another coroutine) */
-#define CO_DEAD	3
-
-static const char *const statnames[] =
-    {"running", "suspended", "normal", "dead"};
-
-static int costatus (lua_State *L, lua_State *co) {
-  if (L == co) return CO_RUN;
-  switch (lua_status(co)) {
-    case LUA_YIELD:
-      return CO_SUS;
-    case 0: {
-      lua_Debug ar;
-      if (lua_getstack(co, 0, &ar) > 0)  /* does it have frames? */
-        return CO_NOR;  /* it is running */
-      else if (lua_gettop(co) == 0)
-          return CO_DEAD;
-      else
-        return CO_SUS;  /* initial state */
-    }
-    default:  /* some error occured */
-      return CO_DEAD;
-  }
-}
-
-
-static int luaB_costatus (lua_State *L) {
-  lua_State *co = lua_tothread(L, 1);
-  luaL_argcheck(L, co, 1, "coroutine expected");
-  lua_pushstring(L, statnames[costatus(L, co)]);
-  return 1;
-}
-
-
-static int auxresume (lua_State *L, lua_State *co, int narg) {
-  int status = costatus(L, co);
-  if (!lua_checkstack(co, narg))
-    luaL_error(L, "too many arguments to resume");
-  if (status != CO_SUS) {
-    lua_pushfstring(L, "cannot resume %s coroutine", statnames[status]);
-    return -1;  /* error flag */
-  }
-  lua_xmove(L, co, narg);
-  lua_setlevel(L, co);
-  status = lua_resume(co, narg);
-  if (status == 0 || status == LUA_YIELD) {
-    int nres = lua_gettop(co);
-    if (!lua_checkstack(L, nres + 1))
-      luaL_error(L, "too many results to resume");
-    lua_xmove(co, L, nres);  /* move yielded values */
-    return nres;
-  }
-  else {
-    lua_xmove(co, L, 1);  /* move error message */
-    return -1;  /* error flag */
-  }
-}
-
-
-static int luaB_coresume (lua_State *L) {
-  lua_State *co = lua_tothread(L, 1);
-  int r;
-  luaL_argcheck(L, co, 1, "coroutine expected");
-  r = auxresume(L, co, lua_gettop(L) - 1);
-  if (r < 0) {
-    lua_pushboolean(L, 0);
-    lua_insert(L, -2);
-    return 2;  /* return false + error message */
-  }
-  else {
-    lua_pushboolean(L, 1);
-    lua_insert(L, -(r + 1));
-    return r + 1;  /* return true + `resume' returns */
-  }
-}
-
-
-static int luaB_auxwrap (lua_State *L) {
-  lua_State *co = lua_tothread(L, lua_upvalueindex(1));
-  int r = auxresume(L, co, lua_gettop(L));
-  if (r < 0) {
-    if (lua_isstring(L, -1)) {  /* error object is a string? */
-      luaL_where(L, 1);  /* add extra info */
-      lua_insert(L, -2);
-      lua_concat(L, 2);
-    }
-    lua_error(L);  /* propagate error */
-  }
-  return r;
-}
-
-
-static int luaB_cocreate (lua_State *L) {
-  lua_State *NL = lua_newthread(L);
-  luaL_argcheck(L, lua_isfunction(L, 1) && !lua_iscfunction(L, 1), 1,
-    "Lua function expected");
-  lua_pushvalue(L, 1);  /* move function to top */
-  lua_xmove(L, NL, 1);  /* move function from L to NL */
-  return 1;
-}
-
-
-static int luaB_cowrap (lua_State *L) {
-  luaB_cocreate(L);
-  lua_pushcclosure(L, luaB_auxwrap, 1);
-  return 1;
-}
-
-
-static int luaB_yield (lua_State *L) {
-  return lua_yield(L, lua_gettop(L));
-}
-
-
-static int luaB_corunning (lua_State *L) {
-  if (lua_pushthread(L))
-    lua_pushnil(L);  /* main thread is not a coroutine */
-  return 1;
-}
-
-#undef MIN_OPT_LEVEL
-#define MIN_OPT_LEVEL 1
-#include "lrodefs.h"
-const LUA_REG_TYPE co_funcs[] = {
-  {LSTRKEY("create"), LFUNCVAL(luaB_cocreate)},
-  {LSTRKEY("resume"), LFUNCVAL(luaB_coresume)},
-  {LSTRKEY("running"), LFUNCVAL(luaB_corunning)},
-  {LSTRKEY("status"), LFUNCVAL(luaB_costatus)},
-  {LSTRKEY("wrap"), LFUNCVAL(luaB_cowrap)},
-  {LSTRKEY("yield"), LFUNCVAL(luaB_yield)},
-  {LNILKEY, LNILVAL}
-};
-
-/* }====================================================== */
-
-
-static void auxopen (lua_State *L, const char *name,
-                     lua_CFunction f, lua_CFunction u) {
-  lua_pushcfunction(L, u);
-  lua_pushcclosure(L, f, 1);
-  lua_setfield(L, -2, name);
-}
-
-
-static void base_open (lua_State *L) {
-  /* set global _G */
-  lua_pushvalue(L, LUA_GLOBALSINDEX);
-  lua_setglobal(L, "_G");
-  /* open lib into global table */
-  luaL_register_light(L, "_G", base_funcs);
-#if LUA_OPTIMIZE_MEMORY > 0
-  lua_pushvalue(L, -1);
-  lua_setmetatable(L, -2);  
-#else
-  lua_pushliteral(L, LUA_VERSION);
-  lua_setglobal(L, "_VERSION");  /* set global _VERSION */
-#endif
-  /* `ipairs' and `pairs' need auxliliary functions as upvalues */
-  auxopen(L, "ipairs", luaB_ipairs, ipairsaux);
-  auxopen(L, "pairs", luaB_pairs, luaB_next);
-  /* `newproxy' needs a weaktable as upvalue */
-  lua_createtable(L, 0, 1);  /* new table `w' */
-  lua_pushvalue(L, -1);  /* `w' will be its own metatable */
-  lua_setmetatable(L, -2);
-  lua_pushliteral(L, "kv");
-  lua_setfield(L, -2, "__mode");  /* metatable(w).__mode = "kv" */
-  lua_pushcclosure(L, luaB_newproxy, 1);
-  lua_setglobal(L, "newproxy");  /* set global `newproxy' */
-}
-
-
-LUALIB_API int luaopen_base (lua_State *L) {
-  base_open(L);
-#if LUA_OPTIMIZE_MEMORY == 0 && defined( MODULE_LUA_CO_LINE )
-  luaL_register(L, LUA_COLIBNAME, co_funcs);
-  return 2;
-#else
-  return 1;
-#endif
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/lcode.c
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/lcode.c b/libs/elua/elua_base/src/lcode.c
deleted file mode 100644
index 679cb9c..0000000
--- a/libs/elua/elua_base/src/lcode.c
+++ /dev/null
@@ -1,831 +0,0 @@
-/*
-** $Id: lcode.c,v 2.25.1.5 2011/01/31 14:53:16 roberto Exp $
-** Code generator for Lua
-** See Copyright Notice in lua.h
-*/
-
-
-#include <stdlib.h>
-
-#define lcode_c
-#define LUA_CORE
-
-#include "lua.h"
-
-#include "lcode.h"
-#include "ldebug.h"
-#include "ldo.h"
-#include "lgc.h"
-#include "llex.h"
-#include "lmem.h"
-#include "lobject.h"
-#include "lopcodes.h"
-#include "lparser.h"
-#include "ltable.h"
-
-
-#define hasjumps(e)	((e)->t != (e)->f)
-
-
-static int isnumeral(expdesc *e) {
-  return (e->k == VKNUM && e->t == NO_JUMP && e->f == NO_JUMP);
-}
-
-
-void luaK_nil (FuncState *fs, int from, int n) {
-  Instruction *previous;
-  if (fs->pc > fs->lasttarget) {  /* no jumps to current position? */
-    if (fs->pc == 0) {  /* function start? */
-      if (from >= fs->nactvar)
-        return;  /* positions are already clean */
-    }
-    else {
-      previous = &fs->f->code[fs->pc-1];
-      if (GET_OPCODE(*previous) == OP_LOADNIL) {
-        int pfrom = GETARG_A(*previous);
-        int pto = GETARG_B(*previous);
-        if (pfrom <= from && from <= pto+1) {  /* can connect both? */
-          if (from+n-1 > pto)
-            SETARG_B(*previous, from+n-1);
-          return;
-        }
-      }
-    }
-  }
-  luaK_codeABC(fs, OP_LOADNIL, from, from+n-1, 0);  /* else no optimization */
-}
-
-
-int luaK_jump (FuncState *fs) {
-  int jpc = fs->jpc;  /* save list of jumps to here */
-  int j;
-  fs->jpc = NO_JUMP;
-  j = luaK_codeAsBx(fs, OP_JMP, 0, NO_JUMP);
-  luaK_concat(fs, &j, jpc);  /* keep them on hold */
-  return j;
-}
-
-
-void luaK_ret (FuncState *fs, int first, int nret) {
-  luaK_codeABC(fs, OP_RETURN, first, nret+1, 0);
-}
-
-
-static int condjump (FuncState *fs, OpCode op, int A, int B, int C) {
-  luaK_codeABC(fs, op, A, B, C);
-  return luaK_jump(fs);
-}
-
-
-static void fixjump (FuncState *fs, int pc, int dest) {
-  Instruction *jmp = &fs->f->code[pc];
-  int offset = dest-(pc+1);
-  lua_assert(dest != NO_JUMP);
-  if (abs(offset) > MAXARG_sBx)
-    luaX_syntaxerror(fs->ls, "control structure too long");
-  SETARG_sBx(*jmp, offset);
-}
-
-
-/*
-** returns current `pc' and marks it as a jump target (to avoid wrong
-** optimizations with consecutive instructions not in the same basic block).
-*/
-int luaK_getlabel (FuncState *fs) {
-  fs->lasttarget = fs->pc;
-  return fs->pc;
-}
-
-
-static int getjump (FuncState *fs, int pc) {
-  int offset = GETARG_sBx(fs->f->code[pc]);
-  if (offset == NO_JUMP)  /* point to itself represents end of list */
-    return NO_JUMP;  /* end of list */
-  else
-    return (pc+1)+offset;  /* turn offset into absolute position */
-}
-
-
-static Instruction *getjumpcontrol (FuncState *fs, int pc) {
-  Instruction *pi = &fs->f->code[pc];
-  if (pc >= 1 && testTMode(GET_OPCODE(*(pi-1))))
-    return pi-1;
-  else
-    return pi;
-}
-
-
-/*
-** check whether list has any jump that do not produce a value
-** (or produce an inverted value)
-*/
-static int need_value (FuncState *fs, int list) {
-  for (; list != NO_JUMP; list = getjump(fs, list)) {
-    Instruction i = *getjumpcontrol(fs, list);
-    if (GET_OPCODE(i) != OP_TESTSET) return 1;
-  }
-  return 0;  /* not found */
-}
-
-
-static int patchtestreg (FuncState *fs, int node, int reg) {
-  Instruction *i = getjumpcontrol(fs, node);
-  if (GET_OPCODE(*i) != OP_TESTSET)
-    return 0;  /* cannot patch other instructions */
-  if (reg != NO_REG && reg != GETARG_B(*i))
-    SETARG_A(*i, reg);
-  else  /* no register to put value or register already has the value */
-    *i = CREATE_ABC(OP_TEST, GETARG_B(*i), 0, GETARG_C(*i));
-
-  return 1;
-}
-
-
-static void removevalues (FuncState *fs, int list) {
-  for (; list != NO_JUMP; list = getjump(fs, list))
-      patchtestreg(fs, list, NO_REG);
-}
-
-
-static void patchlistaux (FuncState *fs, int list, int vtarget, int reg,
-                          int dtarget) {
-  while (list != NO_JUMP) {
-    int next = getjump(fs, list);
-    if (patchtestreg(fs, list, reg))
-      fixjump(fs, list, vtarget);
-    else
-      fixjump(fs, list, dtarget);  /* jump to default target */
-    list = next;
-  }
-}
-
-
-static void dischargejpc (FuncState *fs) {
-  patchlistaux(fs, fs->jpc, fs->pc, NO_REG, fs->pc);
-  fs->jpc = NO_JUMP;
-}
-
-
-void luaK_patchlist (FuncState *fs, int list, int target) {
-  if (target == fs->pc)
-    luaK_patchtohere(fs, list);
-  else {
-    lua_assert(target < fs->pc);
-    patchlistaux(fs, list, target, NO_REG, target);
-  }
-}
-
-
-void luaK_patchtohere (FuncState *fs, int list) {
-  luaK_getlabel(fs);
-  luaK_concat(fs, &fs->jpc, list);
-}
-
-
-void luaK_concat (FuncState *fs, int *l1, int l2) {
-  if (l2 == NO_JUMP) return;
-  else if (*l1 == NO_JUMP)
-    *l1 = l2;
-  else {
-    int list = *l1;
-    int next;
-    while ((next = getjump(fs, list)) != NO_JUMP)  /* find last element */
-      list = next;
-    fixjump(fs, list, l2);
-  }
-}
-
-
-void luaK_checkstack (FuncState *fs, int n) {
-  int newstack = fs->freereg + n;
-  if (newstack > fs->f->maxstacksize) {
-    if (newstack >= MAXSTACK)
-      luaX_syntaxerror(fs->ls, "function or expression too complex");
-    fs->f->maxstacksize = cast_byte(newstack);
-  }
-}
-
-
-void luaK_reserveregs (FuncState *fs, int n) {
-  luaK_checkstack(fs, n);
-  fs->freereg += n;
-}
-
-
-static void freereg (FuncState *fs, int reg) {
-  if (!ISK(reg) && reg >= fs->nactvar) {
-    fs->freereg--;
-    lua_assert(reg == fs->freereg);
-  }
-}
-
-
-static void freeexp (FuncState *fs, expdesc *e) {
-  if (e->k == VNONRELOC)
-    freereg(fs, e->u.s.info);
-}
-
-
-static int addk (FuncState *fs, TValue *k, TValue *v) {
-  lua_State *L = fs->L;
-  TValue *idx = luaH_set(L, fs->h, k);
-  Proto *f = fs->f;
-  int oldsize = f->sizek;
-  if (ttisnumber(idx)) {
-    lua_assert(luaO_rawequalObj(&fs->f->k[cast_int(nvalue(idx))], v));
-    return cast_int(nvalue(idx));
-  }
-  else {  /* constant not found; create a new entry */
-    setnvalue(idx, cast_num(fs->nk));
-    luaM_growvector(L, f->k, fs->nk, f->sizek, TValue,
-                    MAXARG_Bx, "constant table overflow");
-    while (oldsize < f->sizek) setnilvalue(&f->k[oldsize++]);
-    setobj(L, &f->k[fs->nk], v);
-    luaC_barrier(L, f, v);
-    return fs->nk++;
-  }
-}
-
-
-int luaK_stringK (FuncState *fs, TString *s) {
-  TValue o;
-  setsvalue(fs->L, &o, s);
-  return addk(fs, &o, &o);
-}
-
-
-int luaK_numberK (FuncState *fs, lua_Number r) {
-  TValue o;
-  setnvalue(&o, r);
-  return addk(fs, &o, &o);
-}
-
-
-static int boolK (FuncState *fs, int b) {
-  TValue o;
-  setbvalue(&o, b);
-  return addk(fs, &o, &o);
-}
-
-
-static int nilK (FuncState *fs) {
-  TValue k, v;
-  setnilvalue(&v);
-  /* cannot use nil as key; instead use table itself to represent nil */
-  sethvalue(fs->L, &k, fs->h);
-  return addk(fs, &k, &v);
-}
-
-
-void luaK_setreturns (FuncState *fs, expdesc *e, int nresults) {
-  if (e->k == VCALL) {  /* expression is an open function call? */
-    SETARG_C(getcode(fs, e), nresults+1);
-  }
-  else if (e->k == VVARARG) {
-    SETARG_B(getcode(fs, e), nresults+1);
-    SETARG_A(getcode(fs, e), fs->freereg);
-    luaK_reserveregs(fs, 1);
-  }
-}
-
-
-void luaK_setoneret (FuncState *fs, expdesc *e) {
-  if (e->k == VCALL) {  /* expression is an open function call? */
-    e->k = VNONRELOC;
-    e->u.s.info = GETARG_A(getcode(fs, e));
-  }
-  else if (e->k == VVARARG) {
-    SETARG_B(getcode(fs, e), 2);
-    e->k = VRELOCABLE;  /* can relocate its simple result */
-  }
-}
-
-
-void luaK_dischargevars (FuncState *fs, expdesc *e) {
-  switch (e->k) {
-    case VLOCAL: {
-      e->k = VNONRELOC;
-      break;
-    }
-    case VUPVAL: {
-      e->u.s.info = luaK_codeABC(fs, OP_GETUPVAL, 0, e->u.s.info, 0);
-      e->k = VRELOCABLE;
-      break;
-    }
-    case VGLOBAL: {
-      e->u.s.info = luaK_codeABx(fs, OP_GETGLOBAL, 0, e->u.s.info);
-      e->k = VRELOCABLE;
-      break;
-    }
-    case VINDEXED: {
-      freereg(fs, e->u.s.aux);
-      freereg(fs, e->u.s.info);
-      e->u.s.info = luaK_codeABC(fs, OP_GETTABLE, 0, e->u.s.info, e->u.s.aux);
-      e->k = VRELOCABLE;
-      break;
-    }
-    case VVARARG:
-    case VCALL: {
-      luaK_setoneret(fs, e);
-      break;
-    }
-    default: break;  /* there is one value available (somewhere) */
-  }
-}
-
-
-static int code_label (FuncState *fs, int A, int b, int jump) {
-  luaK_getlabel(fs);  /* those instructions may be jump targets */
-  return luaK_codeABC(fs, OP_LOADBOOL, A, b, jump);
-}
-
-
-static void discharge2reg (FuncState *fs, expdesc *e, int reg) {
-  luaK_dischargevars(fs, e);
-  switch (e->k) {
-    case VNIL: {
-      luaK_nil(fs, reg, 1);
-      break;
-    }
-    case VFALSE:  case VTRUE: {
-      luaK_codeABC(fs, OP_LOADBOOL, reg, e->k == VTRUE, 0);
-      break;
-    }
-    case VK: {
-      luaK_codeABx(fs, OP_LOADK, reg, e->u.s.info);
-      break;
-    }
-    case VKNUM: {
-      luaK_codeABx(fs, OP_LOADK, reg, luaK_numberK(fs, e->u.nval));
-      break;
-    }
-    case VRELOCABLE: {
-      Instruction *pc = &getcode(fs, e);
-      SETARG_A(*pc, reg);
-      break;
-    }
-    case VNONRELOC: {
-      if (reg != e->u.s.info)
-        luaK_codeABC(fs, OP_MOVE, reg, e->u.s.info, 0);
-      break;
-    }
-    default: {
-      lua_assert(e->k == VVOID || e->k == VJMP);
-      return;  /* nothing to do... */
-    }
-  }
-  e->u.s.info = reg;
-  e->k = VNONRELOC;
-}
-
-
-static void discharge2anyreg (FuncState *fs, expdesc *e) {
-  if (e->k != VNONRELOC) {
-    luaK_reserveregs(fs, 1);
-    discharge2reg(fs, e, fs->freereg-1);
-  }
-}
-
-
-static void exp2reg (FuncState *fs, expdesc *e, int reg) {
-  discharge2reg(fs, e, reg);
-  if (e->k == VJMP)
-    luaK_concat(fs, &e->t, e->u.s.info);  /* put this jump in `t' list */
-  if (hasjumps(e)) {
-    int final;  /* position after whole expression */
-    int p_f = NO_JUMP;  /* position of an eventual LOAD false */
-    int p_t = NO_JUMP;  /* position of an eventual LOAD true */
-    if (need_value(fs, e->t) || need_value(fs, e->f)) {
-      int fj = (e->k == VJMP) ? NO_JUMP : luaK_jump(fs);
-      p_f = code_label(fs, reg, 0, 1);
-      p_t = code_label(fs, reg, 1, 0);
-      luaK_patchtohere(fs, fj);
-    }
-    final = luaK_getlabel(fs);
-    patchlistaux(fs, e->f, final, reg, p_f);
-    patchlistaux(fs, e->t, final, reg, p_t);
-  }
-  e->f = e->t = NO_JUMP;
-  e->u.s.info = reg;
-  e->k = VNONRELOC;
-}
-
-
-void luaK_exp2nextreg (FuncState *fs, expdesc *e) {
-  luaK_dischargevars(fs, e);
-  freeexp(fs, e);
-  luaK_reserveregs(fs, 1);
-  exp2reg(fs, e, fs->freereg - 1);
-}
-
-
-int luaK_exp2anyreg (FuncState *fs, expdesc *e) {
-  luaK_dischargevars(fs, e);
-  if (e->k == VNONRELOC) {
-    if (!hasjumps(e)) return e->u.s.info;  /* exp is already in a register */
-    if (e->u.s.info >= fs->nactvar) {  /* reg. is not a local? */
-      exp2reg(fs, e, e->u.s.info);  /* put value on it */
-      return e->u.s.info;
-    }
-  }
-  luaK_exp2nextreg(fs, e);  /* default */
-  return e->u.s.info;
-}
-
-
-void luaK_exp2val (FuncState *fs, expdesc *e) {
-  if (hasjumps(e))
-    luaK_exp2anyreg(fs, e);
-  else
-    luaK_dischargevars(fs, e);
-}
-
-
-int luaK_exp2RK (FuncState *fs, expdesc *e) {
-  luaK_exp2val(fs, e);
-  switch (e->k) {
-    case VKNUM:
-    case VTRUE:
-    case VFALSE:
-    case VNIL: {
-      if (fs->nk <= MAXINDEXRK) {  /* constant fit in RK operand? */
-        e->u.s.info = (e->k == VNIL)  ? nilK(fs) :
-                      (e->k == VKNUM) ? luaK_numberK(fs, e->u.nval) :
-                                        boolK(fs, (e->k == VTRUE));
-        e->k = VK;
-        return RKASK(e->u.s.info);
-      }
-      else break;
-    }
-    case VK: {
-      if (e->u.s.info <= MAXINDEXRK)  /* constant fit in argC? */
-        return RKASK(e->u.s.info);
-      else break;
-    }
-    default: break;
-  }
-  /* not a constant in the right range: put it in a register */
-  return luaK_exp2anyreg(fs, e);
-}
-
-
-void luaK_storevar (FuncState *fs, expdesc *var, expdesc *ex) {
-  switch (var->k) {
-    case VLOCAL: {
-      freeexp(fs, ex);
-      exp2reg(fs, ex, var->u.s.info);
-      return;
-    }
-    case VUPVAL: {
-      int e = luaK_exp2anyreg(fs, ex);
-      luaK_codeABC(fs, OP_SETUPVAL, e, var->u.s.info, 0);
-      break;
-    }
-    case VGLOBAL: {
-      int e = luaK_exp2anyreg(fs, ex);
-      luaK_codeABx(fs, OP_SETGLOBAL, e, var->u.s.info);
-      break;
-    }
-    case VINDEXED: {
-      int e = luaK_exp2RK(fs, ex);
-      luaK_codeABC(fs, OP_SETTABLE, var->u.s.info, var->u.s.aux, e);
-      break;
-    }
-    default: {
-      lua_assert(0);  /* invalid var kind to store */
-      break;
-    }
-  }
-  freeexp(fs, ex);
-}
-
-
-void luaK_self (FuncState *fs, expdesc *e, expdesc *key) {
-  int func;
-  luaK_exp2anyreg(fs, e);
-  freeexp(fs, e);
-  func = fs->freereg;
-  luaK_reserveregs(fs, 2);
-  luaK_codeABC(fs, OP_SELF, func, e->u.s.info, luaK_exp2RK(fs, key));
-  freeexp(fs, key);
-  e->u.s.info = func;
-  e->k = VNONRELOC;
-}
-
-
-static void invertjump (FuncState *fs, expdesc *e) {
-  Instruction *pc = getjumpcontrol(fs, e->u.s.info);
-  lua_assert(testTMode(GET_OPCODE(*pc)) && GET_OPCODE(*pc) != OP_TESTSET &&
-                                           GET_OPCODE(*pc) != OP_TEST);
-  SETARG_A(*pc, !(GETARG_A(*pc)));
-}
-
-
-static int jumponcond (FuncState *fs, expdesc *e, int cond) {
-  if (e->k == VRELOCABLE) {
-    Instruction ie = getcode(fs, e);
-    if (GET_OPCODE(ie) == OP_NOT) {
-      fs->pc--;  /* remove previous OP_NOT */
-      return condjump(fs, OP_TEST, GETARG_B(ie), 0, !cond);
-    }
-    /* else go through */
-  }
-  discharge2anyreg(fs, e);
-  freeexp(fs, e);
-  return condjump(fs, OP_TESTSET, NO_REG, e->u.s.info, cond);
-}
-
-
-void luaK_goiftrue (FuncState *fs, expdesc *e) {
-  int pc;  /* pc of last jump */
-  luaK_dischargevars(fs, e);
-  switch (e->k) {
-    case VK: case VKNUM: case VTRUE: {
-      pc = NO_JUMP;  /* always true; do nothing */
-      break;
-    }
-    case VJMP: {
-      invertjump(fs, e);
-      pc = e->u.s.info;
-      break;
-    }
-    default: {
-      pc = jumponcond(fs, e, 0);
-      break;
-    }
-  }
-  luaK_concat(fs, &e->f, pc);  /* insert last jump in `f' list */
-  luaK_patchtohere(fs, e->t);
-  e->t = NO_JUMP;
-}
-
-
-static void luaK_goiffalse (FuncState *fs, expdesc *e) {
-  int pc;  /* pc of last jump */
-  luaK_dischargevars(fs, e);
-  switch (e->k) {
-    case VNIL: case VFALSE: {
-      pc = NO_JUMP;  /* always false; do nothing */
-      break;
-    }
-    case VJMP: {
-      pc = e->u.s.info;
-      break;
-    }
-    default: {
-      pc = jumponcond(fs, e, 1);
-      break;
-    }
-  }
-  luaK_concat(fs, &e->t, pc);  /* insert last jump in `t' list */
-  luaK_patchtohere(fs, e->f);
-  e->f = NO_JUMP;
-}
-
-
-static void codenot (FuncState *fs, expdesc *e) {
-  luaK_dischargevars(fs, e);
-  switch (e->k) {
-    case VNIL: case VFALSE: {
-      e->k = VTRUE;
-      break;
-    }
-    case VK: case VKNUM: case VTRUE: {
-      e->k = VFALSE;
-      break;
-    }
-    case VJMP: {
-      invertjump(fs, e);
-      break;
-    }
-    case VRELOCABLE:
-    case VNONRELOC: {
-      discharge2anyreg(fs, e);
-      freeexp(fs, e);
-      e->u.s.info = luaK_codeABC(fs, OP_NOT, 0, e->u.s.info, 0);
-      e->k = VRELOCABLE;
-      break;
-    }
-    default: {
-      lua_assert(0);  /* cannot happen */
-      break;
-    }
-  }
-  /* interchange true and false lists */
-  { int temp = e->f; e->f = e->t; e->t = temp; }
-  removevalues(fs, e->f);
-  removevalues(fs, e->t);
-}
-
-
-void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k) {
-  t->u.s.aux = luaK_exp2RK(fs, k);
-  t->k = VINDEXED;
-}
-
-
-static int constfolding (OpCode op, expdesc *e1, expdesc *e2) {
-  lua_Number v1, v2, r;
-  if (!isnumeral(e1) || !isnumeral(e2)) return 0;
-  v1 = e1->u.nval;
-  v2 = e2->u.nval;
-  switch (op) {
-    case OP_ADD: r = luai_numadd(v1, v2); break;
-    case OP_SUB: r = luai_numsub(v1, v2); break;
-    case OP_MUL: r = luai_nummul(v1, v2); break;
-    case OP_DIV:
-      if (v2 == 0) return 0;  /* do not attempt to divide by 0 */
-      r = luai_numdiv(v1, v2); break;
-    case OP_MOD:
-      if (v2 == 0) return 0;  /* do not attempt to divide by 0 */
-      r = luai_nummod(v1, v2); break;
-    case OP_POW: r = luai_numpow(v1, v2); break;
-    case OP_UNM: r = luai_numunm(v1); break;
-    case OP_LEN: return 0;  /* no constant folding for 'len' */
-    default: lua_assert(0); r = 0; break;
-  }
-  if (luai_numisnan(r)) return 0;  /* do not attempt to produce NaN */
-  e1->u.nval = r;
-  return 1;
-}
-
-
-static void codearith (FuncState *fs, OpCode op, expdesc *e1, expdesc *e2) {
-  if (constfolding(op, e1, e2))
-    return;
-  else {
-    int o2 = (op != OP_UNM && op != OP_LEN) ? luaK_exp2RK(fs, e2) : 0;
-    int o1 = luaK_exp2RK(fs, e1);
-    if (o1 > o2) {
-      freeexp(fs, e1);
-      freeexp(fs, e2);
-    }
-    else {
-      freeexp(fs, e2);
-      freeexp(fs, e1);
-    }
-    e1->u.s.info = luaK_codeABC(fs, op, 0, o1, o2);
-    e1->k = VRELOCABLE;
-  }
-}
-
-
-static void codecomp (FuncState *fs, OpCode op, int cond, expdesc *e1,
-                                                          expdesc *e2) {
-  int o1 = luaK_exp2RK(fs, e1);
-  int o2 = luaK_exp2RK(fs, e2);
-  freeexp(fs, e2);
-  freeexp(fs, e1);
-  if (cond == 0 && op != OP_EQ) {
-    int temp;  /* exchange args to replace by `<' or `<=' */
-    temp = o1; o1 = o2; o2 = temp;  /* o1 <==> o2 */
-    cond = 1;
-  }
-  e1->u.s.info = condjump(fs, op, cond, o1, o2);
-  e1->k = VJMP;
-}
-
-
-void luaK_prefix (FuncState *fs, UnOpr op, expdesc *e) {
-  expdesc e2;
-  e2.t = e2.f = NO_JUMP; e2.k = VKNUM; e2.u.nval = 0;
-  switch (op) {
-    case OPR_MINUS: {
-      if (!isnumeral(e))
-        luaK_exp2anyreg(fs, e);  /* cannot operate on non-numeric constants */
-      codearith(fs, OP_UNM, e, &e2);
-      break;
-    }
-    case OPR_NOT: codenot(fs, e); break;
-    case OPR_LEN: {
-      luaK_exp2anyreg(fs, e);  /* cannot operate on constants */
-      codearith(fs, OP_LEN, e, &e2);
-      break;
-    }
-    default: lua_assert(0);
-  }
-}
-
-
-void luaK_infix (FuncState *fs, BinOpr op, expdesc *v) {
-  switch (op) {
-    case OPR_AND: {
-      luaK_goiftrue(fs, v);
-      break;
-    }
-    case OPR_OR: {
-      luaK_goiffalse(fs, v);
-      break;
-    }
-    case OPR_CONCAT: {
-      luaK_exp2nextreg(fs, v);  /* operand must be on the `stack' */
-      break;
-    }
-    case OPR_ADD: case OPR_SUB: case OPR_MUL: case OPR_DIV:
-    case OPR_MOD: case OPR_POW: {
-      if (!isnumeral(v)) luaK_exp2RK(fs, v);
-      break;
-    }
-    default: {
-      luaK_exp2RK(fs, v);
-      break;
-    }
-  }
-}
-
-
-void luaK_posfix (FuncState *fs, BinOpr op, expdesc *e1, expdesc *e2) {
-  switch (op) {
-    case OPR_AND: {
-      lua_assert(e1->t == NO_JUMP);  /* list must be closed */
-      luaK_dischargevars(fs, e2);
-      luaK_concat(fs, &e2->f, e1->f);
-      *e1 = *e2;
-      break;
-    }
-    case OPR_OR: {
-      lua_assert(e1->f == NO_JUMP);  /* list must be closed */
-      luaK_dischargevars(fs, e2);
-      luaK_concat(fs, &e2->t, e1->t);
-      *e1 = *e2;
-      break;
-    }
-    case OPR_CONCAT: {
-      luaK_exp2val(fs, e2);
-      if (e2->k == VRELOCABLE && GET_OPCODE(getcode(fs, e2)) == OP_CONCAT) {
-        lua_assert(e1->u.s.info == GETARG_B(getcode(fs, e2))-1);
-        freeexp(fs, e1);
-        SETARG_B(getcode(fs, e2), e1->u.s.info);
-        e1->k = VRELOCABLE; e1->u.s.info = e2->u.s.info;
-      }
-      else {
-        luaK_exp2nextreg(fs, e2);  /* operand must be on the 'stack' */
-        codearith(fs, OP_CONCAT, e1, e2);
-      }
-      break;
-    }
-    case OPR_ADD: codearith(fs, OP_ADD, e1, e2); break;
-    case OPR_SUB: codearith(fs, OP_SUB, e1, e2); break;
-    case OPR_MUL: codearith(fs, OP_MUL, e1, e2); break;
-    case OPR_DIV: codearith(fs, OP_DIV, e1, e2); break;
-    case OPR_MOD: codearith(fs, OP_MOD, e1, e2); break;
-    case OPR_POW: codearith(fs, OP_POW, e1, e2); break;
-    case OPR_EQ: codecomp(fs, OP_EQ, 1, e1, e2); break;
-    case OPR_NE: codecomp(fs, OP_EQ, 0, e1, e2); break;
-    case OPR_LT: codecomp(fs, OP_LT, 1, e1, e2); break;
-    case OPR_LE: codecomp(fs, OP_LE, 1, e1, e2); break;
-    case OPR_GT: codecomp(fs, OP_LT, 0, e1, e2); break;
-    case OPR_GE: codecomp(fs, OP_LE, 0, e1, e2); break;
-    default: lua_assert(0);
-  }
-}
-
-
-void luaK_fixline (FuncState *fs, int line) {
-  fs->f->lineinfo[fs->pc - 1] = line;
-}
-
-
-static int luaK_code (FuncState *fs, Instruction i, int line) {
-  Proto *f = fs->f;
-  dischargejpc(fs);  /* `pc' will change */
-  /* put new instruction in code array */
-  luaM_growvector(fs->L, f->code, fs->pc, f->sizecode, Instruction,
-                  MAX_INT, "code size overflow");
-  f->code[fs->pc] = i;
-  /* save corresponding line information */
-  luaM_growvector(fs->L, f->lineinfo, fs->pc, f->sizelineinfo, int,
-                  MAX_INT, "code size overflow");
-  f->lineinfo[fs->pc] = line;
-  return fs->pc++;
-}
-
-
-int luaK_codeABC (FuncState *fs, OpCode o, int a, int b, int c) {
-  lua_assert(getOpMode(o) == iABC);
-  lua_assert(getBMode(o) != OpArgN || b == 0);
-  lua_assert(getCMode(o) != OpArgN || c == 0);
-  return luaK_code(fs, CREATE_ABC(o, a, b, c), fs->ls->lastline);
-}
-
-
-int luaK_codeABx (FuncState *fs, OpCode o, int a, unsigned int bc) {
-  lua_assert(getOpMode(o) == iABx || getOpMode(o) == iAsBx);
-  lua_assert(getCMode(o) == OpArgN);
-  return luaK_code(fs, CREATE_ABx(o, a, bc), fs->ls->lastline);
-}
-
-
-void luaK_setlist (FuncState *fs, int base, int nelems, int tostore) {
-  int c =  (nelems - 1)/LFIELDS_PER_FLUSH + 1;
-  int b = (tostore == LUA_MULTRET) ? 0 : tostore;
-  lua_assert(tostore != 0);
-  if (c <= MAXARG_C)
-    luaK_codeABC(fs, OP_SETLIST, base, b, c);
-  else {
-    luaK_codeABC(fs, OP_SETLIST, base, b, 0);
-    luaK_code(fs, cast(Instruction, c), fs->ls->lastline);
-  }
-  fs->freereg = base + 1;  /* free registers with list values */
-}
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/lcode.h
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/lcode.h b/libs/elua/elua_base/src/lcode.h
deleted file mode 100644
index b941c60..0000000
--- a/libs/elua/elua_base/src/lcode.h
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
-** $Id: lcode.h,v 1.48.1.1 2007/12/27 13:02:25 roberto Exp $
-** Code generator for Lua
-** See Copyright Notice in lua.h
-*/
-
-#ifndef lcode_h
-#define lcode_h
-
-#include "llex.h"
-#include "lobject.h"
-#include "lopcodes.h"
-#include "lparser.h"
-
-
-/*
-** Marks the end of a patch list. It is an invalid value both as an absolute
-** address, and as a list link (would link an element to itself).
-*/
-#define NO_JUMP (-1)
-
-
-/*
-** grep "ORDER OPR" if you change these enums
-*/
-typedef enum BinOpr {
-  OPR_ADD, OPR_SUB, OPR_MUL, OPR_DIV, OPR_MOD, OPR_POW,
-  OPR_CONCAT,
-  OPR_NE, OPR_EQ,
-  OPR_LT, OPR_LE, OPR_GT, OPR_GE,
-  OPR_AND, OPR_OR,
-  OPR_NOBINOPR
-} BinOpr;
-
-
-typedef enum UnOpr { OPR_MINUS, OPR_NOT, OPR_LEN, OPR_NOUNOPR } UnOpr;
-
-
-#define getcode(fs,e)	((fs)->f->code[(e)->u.s.info])
-
-#define luaK_codeAsBx(fs,o,A,sBx)	luaK_codeABx(fs,o,A,(sBx)+MAXARG_sBx)
-
-#define luaK_setmultret(fs,e)	luaK_setreturns(fs, e, LUA_MULTRET)
-
-LUAI_FUNC int luaK_codeABx (FuncState *fs, OpCode o, int A, unsigned int Bx);
-LUAI_FUNC int luaK_codeABC (FuncState *fs, OpCode o, int A, int B, int C);
-LUAI_FUNC void luaK_fixline (FuncState *fs, int line);
-LUAI_FUNC void luaK_nil (FuncState *fs, int from, int n);
-LUAI_FUNC void luaK_reserveregs (FuncState *fs, int n);
-LUAI_FUNC void luaK_checkstack (FuncState *fs, int n);
-LUAI_FUNC int luaK_stringK (FuncState *fs, TString *s);
-LUAI_FUNC int luaK_numberK (FuncState *fs, lua_Number r);
-LUAI_FUNC void luaK_dischargevars (FuncState *fs, expdesc *e);
-LUAI_FUNC int luaK_exp2anyreg (FuncState *fs, expdesc *e);
-LUAI_FUNC void luaK_exp2nextreg (FuncState *fs, expdesc *e);
-LUAI_FUNC void luaK_exp2val (FuncState *fs, expdesc *e);
-LUAI_FUNC int luaK_exp2RK (FuncState *fs, expdesc *e);
-LUAI_FUNC void luaK_self (FuncState *fs, expdesc *e, expdesc *key);
-LUAI_FUNC void luaK_indexed (FuncState *fs, expdesc *t, expdesc *k);
-LUAI_FUNC void luaK_goiftrue (FuncState *fs, expdesc *e);
-LUAI_FUNC void luaK_storevar (FuncState *fs, expdesc *var, expdesc *e);
-LUAI_FUNC void luaK_setreturns (FuncState *fs, expdesc *e, int nresults);
-LUAI_FUNC void luaK_setoneret (FuncState *fs, expdesc *e);
-LUAI_FUNC int luaK_jump (FuncState *fs);
-LUAI_FUNC void luaK_ret (FuncState *fs, int first, int nret);
-LUAI_FUNC void luaK_patchlist (FuncState *fs, int list, int target);
-LUAI_FUNC void luaK_patchtohere (FuncState *fs, int list);
-LUAI_FUNC void luaK_concat (FuncState *fs, int *l1, int l2);
-LUAI_FUNC int luaK_getlabel (FuncState *fs);
-LUAI_FUNC void luaK_prefix (FuncState *fs, UnOpr op, expdesc *v);
-LUAI_FUNC void luaK_infix (FuncState *fs, BinOpr op, expdesc *v);
-LUAI_FUNC void luaK_posfix (FuncState *fs, BinOpr op, expdesc *v1, expdesc *v2);
-LUAI_FUNC void luaK_setlist (FuncState *fs, int base, int nelems, int tostore);
-
-
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/ldblib.c
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/ldblib.c b/libs/elua/elua_base/src/ldblib.c
deleted file mode 100644
index 1b9a037..0000000
--- a/libs/elua/elua_base/src/ldblib.c
+++ /dev/null
@@ -1,397 +0,0 @@
-/*
-** $Id: ldblib.c,v 1.104.1.4 2009/08/04 18:50:18 roberto Exp $
-** Interface from Lua to its debug API
-** See Copyright Notice in lua.h
-*/
-
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#define ldblib_c
-#define LUA_LIB
-
-#include "lua.h"
-
-#include "lauxlib.h"
-#include "lualib.h"
-#include "lrotable.h"
-
-
-
-static int db_getregistry (lua_State *L) {
-  lua_pushvalue(L, LUA_REGISTRYINDEX);
-  return 1;
-}
-
-
-static int db_getmetatable (lua_State *L) {
-  luaL_checkany(L, 1);
-  if (!lua_getmetatable(L, 1)) {
-    lua_pushnil(L);  /* no metatable */
-  }
-  return 1;
-}
-
-
-static int db_setmetatable (lua_State *L) {
-  int t = lua_type(L, 2);
-  luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2,
-                    "nil or table expected");
-  lua_settop(L, 2);
-  lua_pushboolean(L, lua_setmetatable(L, 1));
-  return 1;
-}
-
-
-static int db_getfenv (lua_State *L) {
-  luaL_checkany(L, 1);
-  lua_getfenv(L, 1);
-  return 1;
-}
-
-
-static int db_setfenv (lua_State *L) {
-  luaL_checktype(L, 2, LUA_TTABLE);
-  lua_settop(L, 2);
-  if (lua_setfenv(L, 1) == 0)
-    luaL_error(L, LUA_QL("setfenv")
-                  " cannot change environment of given object");
-  return 1;
-}
-
-
-static void settabss (lua_State *L, const char *i, const char *v) {
-  lua_pushstring(L, v);
-  lua_setfield(L, -2, i);
-}
-
-
-static void settabsi (lua_State *L, const char *i, int v) {
-  lua_pushinteger(L, v);
-  lua_setfield(L, -2, i);
-}
-
-
-static lua_State *getthread (lua_State *L, int *arg) {
-  if (lua_isthread(L, 1)) {
-    *arg = 1;
-    return lua_tothread(L, 1);
-  }
-  else {
-    *arg = 0;
-    return L;
-  }
-}
-
-
-static void treatstackoption (lua_State *L, lua_State *L1, const char *fname) {
-  if (L == L1) {
-    lua_pushvalue(L, -2);
-    lua_remove(L, -3);
-  }
-  else
-    lua_xmove(L1, L, 1);
-  lua_setfield(L, -2, fname);
-}
-
-
-static int db_getinfo (lua_State *L) {
-  lua_Debug ar;
-  int arg;
-  lua_State *L1 = getthread(L, &arg);
-  const char *options = luaL_optstring(L, arg+2, "flnSu");
-  if (lua_isnumber(L, arg+1)) {
-    if (!lua_getstack(L1, (int)lua_tointeger(L, arg+1), &ar)) {
-      lua_pushnil(L);  /* level out of range */
-      return 1;
-    }
-  }
-  else if (lua_isfunction(L, arg+1) || lua_islightfunction(L, arg+1)) {
-    lua_pushfstring(L, ">%s", options);
-    options = lua_tostring(L, -1);
-    lua_pushvalue(L, arg+1);
-    lua_xmove(L, L1, 1);
-  }
-  else
-    return luaL_argerror(L, arg+1, "function or level expected");
-  if (!lua_getinfo(L1, options, &ar))
-    return luaL_argerror(L, arg+2, "invalid option");
-  lua_createtable(L, 0, 2);
-  if (strchr(options, 'S')) {
-    settabss(L, "source", ar.source);
-    settabss(L, "short_src", ar.short_src);
-    settabsi(L, "linedefined", ar.linedefined);
-    settabsi(L, "lastlinedefined", ar.lastlinedefined);
-    settabss(L, "what", ar.what);
-  }
-  if (strchr(options, 'l'))
-    settabsi(L, "currentline", ar.currentline);
-  if (strchr(options, 'u'))
-    settabsi(L, "nups", ar.nups);
-  if (strchr(options, 'n')) {
-    settabss(L, "name", ar.name);
-    settabss(L, "namewhat", ar.namewhat);
-  }
-  if (strchr(options, 'L'))
-    treatstackoption(L, L1, "activelines");
-  if (strchr(options, 'f'))
-    treatstackoption(L, L1, "func");
-  return 1;  /* return table */
-}
-    
-
-static int db_getlocal (lua_State *L) {
-  int arg;
-  lua_State *L1 = getthread(L, &arg);
-  lua_Debug ar;
-  const char *name;
-  if (!lua_getstack(L1, luaL_checkint(L, arg+1), &ar))  /* out of range? */
-    return luaL_argerror(L, arg+1, "level out of range");
-  name = lua_getlocal(L1, &ar, luaL_checkint(L, arg+2));
-  if (name) {
-    lua_xmove(L1, L, 1);
-    lua_pushstring(L, name);
-    lua_pushvalue(L, -2);
-    return 2;
-  }
-  else {
-    lua_pushnil(L);
-    return 1;
-  }
-}
-
-
-static int db_setlocal (lua_State *L) {
-  int arg;
-  lua_State *L1 = getthread(L, &arg);
-  lua_Debug ar;
-  if (!lua_getstack(L1, luaL_checkint(L, arg+1), &ar))  /* out of range? */
-    return luaL_argerror(L, arg+1, "level out of range");
-  luaL_checkany(L, arg+3);
-  lua_settop(L, arg+3);
-  lua_xmove(L, L1, 1);
-  lua_pushstring(L, lua_setlocal(L1, &ar, luaL_checkint(L, arg+2)));
-  return 1;
-}
-
-
-static int auxupvalue (lua_State *L, int get) {
-  const char *name;
-  int n = luaL_checkint(L, 2);
-  luaL_checktype(L, 1, LUA_TFUNCTION);
-  if (lua_iscfunction(L, 1)) return 0;  /* cannot touch C upvalues from Lua */
-  name = get ? lua_getupvalue(L, 1, n) : lua_setupvalue(L, 1, n);
-  if (name == NULL) return 0;
-  lua_pushstring(L, name);
-  lua_insert(L, -(get+1));
-  return get + 1;
-}
-
-
-static int db_getupvalue (lua_State *L) {
-  return auxupvalue(L, 1);
-}
-
-
-static int db_setupvalue (lua_State *L) {
-  luaL_checkany(L, 3);
-  return auxupvalue(L, 0);
-}
-
-
-
-static const char KEY_HOOK = 'h';
-
-
-static void hookf (lua_State *L, lua_Debug *ar) {
-  static const char *const hooknames[] =
-    {"call", "return", "line", "count", "tail return"};
-  lua_pushlightuserdata(L, (void *)&KEY_HOOK);
-  lua_rawget(L, LUA_REGISTRYINDEX);
-  lua_pushlightuserdata(L, L);
-  lua_rawget(L, -2);
-  if (lua_isfunction(L, -1)) {
-    lua_pushstring(L, hooknames[(int)ar->event]);
-    if (ar->currentline >= 0)
-      lua_pushinteger(L, ar->currentline);
-    else lua_pushnil(L);
-    lua_assert(lua_getinfo(L, "lS", ar));
-    lua_call(L, 2, 0);
-  }
-}
-
-
-static int makemask (const char *smask, int count) {
-  int mask = 0;
-  if (strchr(smask, 'c')) mask |= LUA_MASKCALL;
-  if (strchr(smask, 'r')) mask |= LUA_MASKRET;
-  if (strchr(smask, 'l')) mask |= LUA_MASKLINE;
-  if (count > 0) mask |= LUA_MASKCOUNT;
-  return mask;
-}
-
-
-static char *unmakemask (int mask, char *smask) {
-  int i = 0;
-  if (mask & LUA_MASKCALL) smask[i++] = 'c';
-  if (mask & LUA_MASKRET) smask[i++] = 'r';
-  if (mask & LUA_MASKLINE) smask[i++] = 'l';
-  smask[i] = '\0';
-  return smask;
-}
-
-
-static void gethooktable (lua_State *L) {
-  lua_pushlightuserdata(L, (void *)&KEY_HOOK);
-  lua_rawget(L, LUA_REGISTRYINDEX);
-  if (!lua_istable(L, -1)) {
-    lua_pop(L, 1);
-    lua_createtable(L, 0, 1);
-    lua_pushlightuserdata(L, (void *)&KEY_HOOK);
-    lua_pushvalue(L, -2);
-    lua_rawset(L, LUA_REGISTRYINDEX);
-  }
-}
-
-
-static int db_sethook (lua_State *L) {
-  int arg, mask, count;
-  lua_Hook func;
-  lua_State *L1 = getthread(L, &arg);
-  if (lua_isnoneornil(L, arg+1)) {
-    lua_settop(L, arg+1);
-    func = NULL; mask = 0; count = 0;  /* turn off hooks */
-  }
-  else {
-    const char *smask = luaL_checkstring(L, arg+2);
-    luaL_checkanyfunction(L, arg+1);
-    count = luaL_optint(L, arg+3, 0);
-    func = hookf; mask = makemask(smask, count);
-  }
-  gethooktable(L);
-  lua_pushlightuserdata(L, L1);
-  lua_pushvalue(L, arg+1);
-  lua_rawset(L, -3);  /* set new hook */
-  lua_pop(L, 1);  /* remove hook table */
-  lua_sethook(L1, func, mask, count);  /* set hooks */
-  return 0;
-}
-
-
-static int db_gethook (lua_State *L) {
-  int arg;
-  lua_State *L1 = getthread(L, &arg);
-  char buff[5];
-  int mask = lua_gethookmask(L1);
-  lua_Hook hook = lua_gethook(L1);
-  if (hook != NULL && hook != hookf)  /* external hook? */
-    lua_pushliteral(L, "external hook");
-  else {
-    gethooktable(L);
-    lua_pushlightuserdata(L, L1);
-    lua_rawget(L, -2);   /* get hook */
-    lua_remove(L, -2);  /* remove hook table */
-  }
-  lua_pushstring(L, unmakemask(mask, buff));
-  lua_pushinteger(L, lua_gethookcount(L1));
-  return 3;
-}
-
-
-static int db_debug (lua_State *L) {
-  for (;;) {
-    char buffer[250];
-    fputs("lua_debug> ", stderr);
-    if (fgets(buffer, sizeof(buffer), stdin) == 0 ||
-        strcmp(buffer, "cont\n") == 0)
-      return 0;
-    if (luaL_loadbuffer(L, buffer, strlen(buffer), "=(debug command)") ||
-        lua_pcall(L, 0, 0, 0)) {
-      fputs(lua_tostring(L, -1), stderr);
-      fputs("\n", stderr);
-    }
-    lua_settop(L, 0);  /* remove eventual returns */
-  }
-}
-
-
-#define LEVELS1	12	/* size of the first part of the stack */
-#define LEVELS2	10	/* size of the second part of the stack */
-
-static int db_errorfb (lua_State *L) {
-  int level;
-  int firstpart = 1;  /* still before eventual `...' */
-  int arg;
-  lua_State *L1 = getthread(L, &arg);
-  lua_Debug ar;
-  if (lua_isnumber(L, arg+2)) {
-    level = (int)lua_tointeger(L, arg+2);
-    lua_pop(L, 1);
-  }
-  else
-    level = (L == L1) ? 1 : 0;  /* level 0 may be this own function */
-  if (lua_gettop(L) == arg)
-    lua_pushliteral(L, "");
-  else if (!lua_isstring(L, arg+1)) return 1;  /* message is not a string */
-  else lua_pushliteral(L, "\n");
-  lua_pushliteral(L, "stack traceback:");
-  while (lua_getstack(L1, level++, &ar)) {
-    if (level > LEVELS1 && firstpart) {
-      /* no more than `LEVELS2' more levels? */
-      if (!lua_getstack(L1, level+LEVELS2, &ar))
-        level--;  /* keep going */
-      else {
-        lua_pushliteral(L, "\n\t...");  /* too many levels */
-        while (lua_getstack(L1, level+LEVELS2, &ar))  /* find last levels */
-          level++;
-      }
-      firstpart = 0;
-      continue;
-    }
-    lua_pushliteral(L, "\n\t");
-    lua_getinfo(L1, "Snl", &ar);
-    lua_pushfstring(L, "%s:", ar.short_src);
-    if (ar.currentline > 0)
-      lua_pushfstring(L, "%d:", ar.currentline);
-    if (*ar.namewhat != '\0')  /* is there a name? */
-        lua_pushfstring(L, " in function " LUA_QS, ar.name);
-    else {
-      if (*ar.what == 'm')  /* main? */
-        lua_pushfstring(L, " in main chunk");
-      else if (*ar.what == 'C' || *ar.what == 't')
-        lua_pushliteral(L, " ?");  /* C function or tail call */
-      else
-        lua_pushfstring(L, " in function <%s:%d>",
-                           ar.short_src, ar.linedefined);
-    }
-    lua_concat(L, lua_gettop(L) - arg);
-  }
-  lua_concat(L, lua_gettop(L) - arg);
-  return 1;
-}
-
-#define MIN_OPT_LEVEL 1
-#include "lrodefs.h"
-const LUA_REG_TYPE dblib[] = {
-  {LSTRKEY("debug"), LFUNCVAL(db_debug)},
-  {LSTRKEY("getfenv"), LFUNCVAL(db_getfenv)},
-  {LSTRKEY("gethook"), LFUNCVAL(db_gethook)},
-  {LSTRKEY("getinfo"), LFUNCVAL(db_getinfo)},
-  {LSTRKEY("getlocal"), LFUNCVAL(db_getlocal)},
-  {LSTRKEY("getregistry"), LFUNCVAL(db_getregistry)},
-  {LSTRKEY("getmetatable"), LFUNCVAL(db_getmetatable)},
-  {LSTRKEY("getupvalue"), LFUNCVAL(db_getupvalue)},
-  {LSTRKEY("setfenv"), LFUNCVAL(db_setfenv)},
-  {LSTRKEY("sethook"), LFUNCVAL(db_sethook)},
-  {LSTRKEY("setlocal"), LFUNCVAL(db_setlocal)},
-  {LSTRKEY("setmetatable"), LFUNCVAL(db_setmetatable)},
-  {LSTRKEY("setupvalue"), LFUNCVAL(db_setupvalue)},
-  {LSTRKEY("traceback"), LFUNCVAL(db_errorfb)},
-  {LNILKEY, LNILVAL}
-};
-
-LUALIB_API int luaopen_debug (lua_State *L) {
-  LREGISTER(L, LUA_DBLIBNAME, dblib);
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/ldebug.c
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/ldebug.c b/libs/elua/elua_base/src/ldebug.c
deleted file mode 100644
index 338cce2..0000000
--- a/libs/elua/elua_base/src/ldebug.c
+++ /dev/null
@@ -1,649 +0,0 @@
-/*
-** $Id: ldebug.c,v 2.29.1.6 2008/05/08 16:56:26 roberto Exp $
-** Debug Interface
-** See Copyright Notice in lua.h
-*/
-
-
-#include <stdarg.h>
-#include <stddef.h>
-#include <string.h>
-
-
-#define ldebug_c
-#define LUA_CORE
-
-#include "lua.h"
-
-#include "lapi.h"
-#include "lcode.h"
-#include "ldebug.h"
-#include "ldo.h"
-#include "lfunc.h"
-#include "lobject.h"
-#include "lopcodes.h"
-#include "lstate.h"
-#include "lstring.h"
-#include "ltable.h"
-#include "ltm.h"
-#include "lvm.h"
-
-
-
-static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name);
-
-
-static int currentpc (lua_State *L, CallInfo *ci) {
-  if (!isLua(ci)) return -1;  /* function is not a Lua function? */
-  if (ci == L->ci)
-    ci->savedpc = L->savedpc;
-  return pcRel(ci->savedpc, ci_func(ci)->l.p);
-}
-
-
-static int currentline (lua_State *L, CallInfo *ci) {
-  int pc = currentpc(L, ci);
-  if (pc < 0)
-    return -1;  /* only active lua functions have current-line information */
-  else
-    return getline(ci_func(ci)->l.p, pc);
-}
-
-
-/*
-** this function can be called asynchronous (e.g. during a signal)
-*/
-LUA_API int lua_sethook (lua_State *L, lua_Hook func, int mask, int count) {
-  if (func == NULL || mask == 0) {  /* turn off hooks? */
-    mask = 0;
-    func = NULL;
-  }
-  L->hook = func;
-  L->basehookcount = count;
-  resethookcount(L);
-  L->hookmask = cast_byte(mask);
-  return 1;
-}
-
-
-LUA_API lua_Hook lua_gethook (lua_State *L) {
-  return L->hook;
-}
-
-
-LUA_API int lua_gethookmask (lua_State *L) {
-  return L->hookmask;
-}
-
-
-LUA_API int lua_gethookcount (lua_State *L) {
-  return L->basehookcount;
-}
-
-
-LUA_API int lua_getstack (lua_State *L, int level, lua_Debug *ar) {
-  int status;
-  CallInfo *ci;
-  lua_lock(L);
-  for (ci = L->ci; level > 0 && ci > L->base_ci; ci--) {
-    level--;
-    if (f_isLua(ci))  /* Lua function? */
-      level -= ci->tailcalls;  /* skip lost tail calls */
-  }
-  if (level == 0 && ci > L->base_ci) {  /* level found? */
-    status = 1;
-    ar->i_ci = cast_int(ci - L->base_ci);
-  }
-  else if (level < 0) {  /* level is of a lost tail call? */
-    status = 1;
-    ar->i_ci = 0;
-  }
-  else status = 0;  /* no such level */
-  lua_unlock(L);
-  return status;
-}
-
-
-static Proto *getluaproto (CallInfo *ci) {
-  return (isLua(ci) ? ci_func(ci)->l.p : NULL);
-}
-
-
-static const char *findlocal (lua_State *L, CallInfo *ci, int n) {
-  const char *name;
-  Proto *fp = getluaproto(ci);
-  if (fp && (name = luaF_getlocalname(fp, n, currentpc(L, ci))) != NULL)
-    return name;  /* is a local variable in a Lua function */
-  else {
-    StkId limit = (ci == L->ci) ? L->top : (ci+1)->func;
-    if (limit - ci->base >= n && n > 0)  /* is 'n' inside 'ci' stack? */
-      return "(*temporary)";
-    else
-      return NULL;
-  }
-}
-
-
-LUA_API const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n) {
-  CallInfo *ci = L->base_ci + ar->i_ci;
-  const char *name = findlocal(L, ci, n);
-  lua_lock(L);
-  if (name)
-      luaA_pushobject(L, ci->base + (n - 1));
-  lua_unlock(L);
-  return name;
-}
-
-
-LUA_API const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n) {
-  CallInfo *ci = L->base_ci + ar->i_ci;
-  const char *name = findlocal(L, ci, n);
-  lua_lock(L);
-  if (name)
-      setobjs2s(L, ci->base + (n - 1), L->top - 1);
-  L->top--;  /* pop value */
-  lua_unlock(L);
-  return name;
-}
-
-
-static void funcinfo (lua_Debug *ar, Closure *cl, void *plight) {
-  if (plight || cl->c.isC) {
-    ar->source = "=[C]";
-    ar->linedefined = -1;
-    ar->lastlinedefined = -1;
-    ar->what = "C";
-  }
-  else {
-    ar->source = getstr(cl->l.p->source);
-    ar->linedefined = cl->l.p->linedefined;
-    ar->lastlinedefined = cl->l.p->lastlinedefined;
-    ar->what = (ar->linedefined == 0) ? "main" : "Lua";
-  }
-  luaO_chunkid(ar->short_src, ar->source, LUA_IDSIZE);
-}
-
-
-static void info_tailcall (lua_Debug *ar) {
-  ar->name = ar->namewhat = "";
-  ar->what = "tail";
-  ar->lastlinedefined = ar->linedefined = ar->currentline = -1;
-  ar->source = "=(tail call)";
-  luaO_chunkid(ar->short_src, ar->source, LUA_IDSIZE);
-  ar->nups = 0;
-}
-
-
-static void collectvalidlines (lua_State *L, Closure *f) {
-  if (f == NULL || f->c.isC) {
-    setnilvalue(L->top);
-  }
-  else {
-    Table *t = luaH_new(L, 0, 0);
-    int *lineinfo = f->l.p->lineinfo;
-    int i;
-    for (i=0; i<f->l.p->sizelineinfo; i++)
-      setbvalue(luaH_setnum(L, t, lineinfo[i]), 1);
-    sethvalue(L, L->top, t); 
-  }
-  incr_top(L);
-}
-
-
-static int auxgetinfo (lua_State *L, const char *what, lua_Debug *ar,
-                    Closure *f, void *plight, CallInfo *ci) {
-  int status = 1;
-  if (plight == NULL && f == NULL) {
-    info_tailcall(ar);
-    return status;
-  }
-  for (; *what; what++) {
-    switch (*what) {
-      case 'S': {
-        funcinfo(ar, f, plight);
-        break;
-      }
-      case 'l': {
-        ar->currentline = (ci) ? currentline(L, ci) : -1;
-        break;
-      }
-      case 'u': {
-        ar->nups = f ? f->c.nupvalues : 0;
-        break;
-      }
-      case 'n': {
-        ar->namewhat = (ci) ? getfuncname(L, ci, &ar->name) : NULL;
-        if (ar->namewhat == NULL) {
-          ar->namewhat = "";  /* not found */
-          ar->name = NULL;
-        }
-        break;
-      }
-      case 'L':
-      case 'f':  /* handled by lua_getinfo */
-        break;
-      default: status = 0;  /* invalid option */
-    }
-  }
-  return status;
-}
-
-
-LUA_API int lua_getinfo (lua_State *L, const char *what, lua_Debug *ar) {
-  int status;
-  Closure *f = NULL;
-  CallInfo *ci = NULL;
-  void *plight = NULL;
-  lua_lock(L);
-  if (*what == '>') {
-    StkId func = L->top - 1;
-    luai_apicheck(L, ttisfunction(func) || ttislightfunction(func));
-    what++;  /* skip the '>' */
-    if (ttisfunction(func))
-      f = clvalue(func);
-    else
-      plight = fvalue(func);
-    L->top--;  /* pop function */
-  }
-  else if (ar->i_ci != 0) {  /* no tail call? */
-    ci = L->base_ci + ar->i_ci;
-    lua_assert(ttisfunction(ci->func) || ttislightfunction(ci->func));
-    if (ttisfunction(ci->func))
-      f = clvalue(ci->func);
-    else
-      plight = fvalue(ci->func);
-  }
-  status = auxgetinfo(L, what, ar, f, plight, ci);
-  if (strchr(what, 'f')) {
-    if (f != NULL) 
-      setclvalue(L, L->top, f)
-    else if (plight != NULL)
-      setfvalue(L->top, plight)
-    else
-      setnilvalue(L->top);
-    incr_top(L);
-  }
-  if (strchr(what, 'L'))
-    collectvalidlines(L, f);
-  lua_unlock(L);
-  return status;
-}
-
-
-/*
-** {======================================================
-** Symbolic Execution and code checker
-** =======================================================
-*/
-
-#define check(x)		if (!(x)) return 0;
-
-#define checkjump(pt,pc)	check(0 <= pc && pc < pt->sizecode)
-
-#define checkreg(pt,reg)	check((reg) < (pt)->maxstacksize)
-
-
-
-static int precheck (const Proto *pt) {
-  check(pt->maxstacksize <= MAXSTACK);
-  check(pt->numparams+(pt->is_vararg & VARARG_HASARG) <= pt->maxstacksize);
-  check(!(pt->is_vararg & VARARG_NEEDSARG) ||
-              (pt->is_vararg & VARARG_HASARG));
-  check(pt->sizeupvalues <= pt->nups);
-  check(pt->sizelineinfo == pt->sizecode || pt->sizelineinfo == 0);
-  check(pt->sizecode > 0 && GET_OPCODE(pt->code[pt->sizecode-1]) == OP_RETURN);
-  return 1;
-}
-
-
-#define checkopenop(pt,pc)	luaG_checkopenop((pt)->code[(pc)+1])
-
-int luaG_checkopenop (Instruction i) {
-  switch (GET_OPCODE(i)) {
-    case OP_CALL:
-    case OP_TAILCALL:
-    case OP_RETURN:
-    case OP_SETLIST: {
-      check(GETARG_B(i) == 0);
-      return 1;
-    }
-    default: return 0;  /* invalid instruction after an open call */
-  }
-}
-
-
-static int checkArgMode (const Proto *pt, int r, enum OpArgMask mode) {
-  switch (mode) {
-    case OpArgN: check(r == 0); break;
-    case OpArgU: break;
-    case OpArgR: checkreg(pt, r); break;
-    case OpArgK:
-      check(ISK(r) ? INDEXK(r) < pt->sizek : r < pt->maxstacksize);
-      break;
-  }
-  return 1;
-}
-
-
-static Instruction symbexec (const Proto *pt, int lastpc, int reg) {
-  int pc;
-  int last;  /* stores position of last instruction that changed `reg' */
-  last = pt->sizecode-1;  /* points to final return (a `neutral' instruction) */
-  check(precheck(pt));
-  for (pc = 0; pc < lastpc; pc++) {
-    Instruction i = pt->code[pc];
-    OpCode op = GET_OPCODE(i);
-    int a = GETARG_A(i);
-    int b = 0;
-    int c = 0;
-    check(op < NUM_OPCODES);
-    checkreg(pt, a);
-    switch (getOpMode(op)) {
-      case iABC: {
-        b = GETARG_B(i);
-        c = GETARG_C(i);
-        check(checkArgMode(pt, b, getBMode(op)));
-        check(checkArgMode(pt, c, getCMode(op)));
-        break;
-      }
-      case iABx: {
-        b = GETARG_Bx(i);
-        if (getBMode(op) == OpArgK) check(b < pt->sizek);
-        break;
-      }
-      case iAsBx: {
-        b = GETARG_sBx(i);
-        if (getBMode(op) == OpArgR) {
-          int dest = pc+1+b;
-          check(0 <= dest && dest < pt->sizecode);
-          if (dest > 0) {
-            int j;
-            /* check that it does not jump to a setlist count; this
-               is tricky, because the count from a previous setlist may
-               have the same value of an invalid setlist; so, we must
-               go all the way back to the first of them (if any) */
-            for (j = 0; j < dest; j++) {
-              Instruction d = pt->code[dest-1-j];
-              if (!(GET_OPCODE(d) == OP_SETLIST && GETARG_C(d) == 0)) break;
-            }
-            /* if 'j' is even, previous value is not a setlist (even if
-               it looks like one) */
-            check((j&1) == 0);
-          }
-        }
-        break;
-      }
-    }
-    if (testAMode(op)) {
-      if (a == reg) last = pc;  /* change register `a' */
-    }
-    if (testTMode(op)) {
-      check(pc+2 < pt->sizecode);  /* check skip */
-      check(GET_OPCODE(pt->code[pc+1]) == OP_JMP);
-    }
-    switch (op) {
-      case OP_LOADBOOL: {
-        if (c == 1) {  /* does it jump? */
-          check(pc+2 < pt->sizecode);  /* check its jump */
-          check(GET_OPCODE(pt->code[pc+1]) != OP_SETLIST ||
-                GETARG_C(pt->code[pc+1]) != 0);
-        }
-        break;
-      }
-      case OP_LOADNIL: {
-        if (a <= reg && reg <= b)
-          last = pc;  /* set registers from `a' to `b' */
-        break;
-      }
-      case OP_GETUPVAL:
-      case OP_SETUPVAL: {
-        check(b < pt->nups);
-        break;
-      }
-      case OP_GETGLOBAL:
-      case OP_SETGLOBAL: {
-        check(ttisstring(&pt->k[b]));
-        break;
-      }
-      case OP_SELF: {
-        checkreg(pt, a+1);
-        if (reg == a+1) last = pc;
-        break;
-      }
-      case OP_CONCAT: {
-        check(b < c);  /* at least two operands */
-        break;
-      }
-      case OP_TFORLOOP: {
-        check(c >= 1);  /* at least one result (control variable) */
-        checkreg(pt, a+2+c);  /* space for results */
-        if (reg >= a+2) last = pc;  /* affect all regs above its base */
-        break;
-      }
-      case OP_FORLOOP:
-      case OP_FORPREP:
-        checkreg(pt, a+3);
-        /* go through */
-      case OP_JMP: {
-        int dest = pc+1+b;
-        /* not full check and jump is forward and do not skip `lastpc'? */
-        if (reg != NO_REG && pc < dest && dest <= lastpc)
-          pc += b;  /* do the jump */
-        break;
-      }
-      case OP_CALL:
-      case OP_TAILCALL: {
-        if (b != 0) {
-          checkreg(pt, a+b-1);
-        }
-        c--;  /* c = num. returns */
-        if (c == LUA_MULTRET) {
-          check(checkopenop(pt, pc));
-        }
-        else if (c != 0)
-          checkreg(pt, a+c-1);
-        if (reg >= a) last = pc;  /* affect all registers above base */
-        break;
-      }
-      case OP_RETURN: {
-        b--;  /* b = num. returns */
-        if (b > 0) checkreg(pt, a+b-1);
-        break;
-      }
-      case OP_SETLIST: {
-        if (b > 0) checkreg(pt, a + b);
-        if (c == 0) {
-          pc++;
-          check(pc < pt->sizecode - 1);
-        }
-        break;
-      }
-      case OP_CLOSURE: {
-        int nup, j;
-        check(b < pt->sizep);
-        nup = pt->p[b]->nups;
-        check(pc + nup < pt->sizecode);
-        for (j = 1; j <= nup; j++) {
-          OpCode op1 = GET_OPCODE(pt->code[pc + j]);
-          check(op1 == OP_GETUPVAL || op1 == OP_MOVE);
-        }
-        if (reg != NO_REG)  /* tracing? */
-          pc += nup;  /* do not 'execute' these pseudo-instructions */
-        break;
-      }
-      case OP_VARARG: {
-        check((pt->is_vararg & VARARG_ISVARARG) &&
-             !(pt->is_vararg & VARARG_NEEDSARG));
-        b--;
-        if (b == LUA_MULTRET) check(checkopenop(pt, pc));
-        checkreg(pt, a+b-1);
-        break;
-      }
-      default: break;
-    }
-  }
-  return pt->code[last];
-}
-
-#undef check
-#undef checkjump
-#undef checkreg
-
-/* }====================================================== */
-
-
-int luaG_checkcode (const Proto *pt) {
-  return (symbexec(pt, pt->sizecode, NO_REG) != 0);
-}
-
-
-static const char *kname (Proto *p, int c) {
-  if (ISK(c) && ttisstring(&p->k[INDEXK(c)]))
-    return svalue(&p->k[INDEXK(c)]);
-  else
-    return "?";
-}
-
-
-static const char *getobjname (lua_State *L, CallInfo *ci, int stackpos,
-                               const char **name) {
-  if (isLua(ci)) {  /* a Lua function? */
-    Proto *p = ci_func(ci)->l.p;
-    int pc = currentpc(L, ci);
-    Instruction i;
-    *name = luaF_getlocalname(p, stackpos+1, pc);
-    if (*name)  /* is a local? */
-      return "local";
-    i = symbexec(p, pc, stackpos);  /* try symbolic execution */
-    lua_assert(pc != -1);
-    switch (GET_OPCODE(i)) {
-      case OP_GETGLOBAL: {
-        int g = GETARG_Bx(i);  /* global index */
-        lua_assert(ttisstring(&p->k[g]));
-        *name = svalue(&p->k[g]);
-        return "global";
-      }
-      case OP_MOVE: {
-        int a = GETARG_A(i);
-        int b = GETARG_B(i);  /* move from `b' to `a' */
-        if (b < a)
-          return getobjname(L, ci, b, name);  /* get name for `b' */
-        break;
-      }
-      case OP_GETTABLE: {
-        int k = GETARG_C(i);  /* key index */
-        *name = kname(p, k);
-        return "field";
-      }
-      case OP_GETUPVAL: {
-        int u = GETARG_B(i);  /* upvalue index */
-        *name = p->upvalues ? getstr(p->upvalues[u]) : "?";
-        return "upvalue";
-      }
-      case OP_SELF: {
-        int k = GETARG_C(i);  /* key index */
-        *name = kname(p, k);
-        return "method";
-      }
-      default: break;
-    }
-  }
-  return NULL;  /* no useful name found */
-}
-
-
-static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name) {
-  Instruction i;
-  if ((isLua(ci) && ci->tailcalls > 0) || !isLua(ci - 1))
-    return NULL;  /* calling function is not Lua (or is unknown) */
-  ci--;  /* calling function */
-  i = ci_func(ci)->l.p->code[currentpc(L, ci)];
-  if (GET_OPCODE(i) == OP_CALL || GET_OPCODE(i) == OP_TAILCALL ||
-      GET_OPCODE(i) == OP_TFORLOOP)
-    return getobjname(L, ci, GETARG_A(i), name);
-  else
-    return NULL;  /* no useful name can be found */
-}
-
-
-/* only ANSI way to check whether a pointer points to an array */
-static int isinstack (CallInfo *ci, const TValue *o) {
-  StkId p;
-  for (p = ci->base; p < ci->top; p++)
-    if (o == p) return 1;
-  return 0;
-}
-
-
-void luaG_typeerror (lua_State *L, const TValue *o, const char *op) {
-  const char *name = NULL;
-  const char *t = luaT_typenames[ttype(o)];
-  const char *kind = (isinstack(L->ci, o)) ?
-                         getobjname(L, L->ci, cast_int(o - L->base), &name) :
-                         NULL;
-  if (kind)
-    luaG_runerror(L, "attempt to %s %s " LUA_QS " (a %s value)",
-                op, kind, name, t);
-  else
-    luaG_runerror(L, "attempt to %s a %s value", op, t);
-}
-
-
-void luaG_concaterror (lua_State *L, StkId p1, StkId p2) {
-  if (ttisstring(p1) || ttisnumber(p1)) p1 = p2;
-  lua_assert(!ttisstring(p1) && !ttisnumber(p1));
-  luaG_typeerror(L, p1, "concatenate");
-}
-
-
-void luaG_aritherror (lua_State *L, const TValue *p1, const TValue *p2) {
-  TValue temp;
-  if (luaV_tonumber(p1, &temp) == NULL)
-    p2 = p1;  /* first operand is wrong */
-  luaG_typeerror(L, p2, "perform arithmetic on");
-}
-
-
-int luaG_ordererror (lua_State *L, const TValue *p1, const TValue *p2) {
-  const char *t1 = luaT_typenames[ttype(p1)];
-  const char *t2 = luaT_typenames[ttype(p2)];
-  if (t1[2] == t2[2])
-    luaG_runerror(L, "attempt to compare two %s values", t1);
-  else
-    luaG_runerror(L, "attempt to compare %s with %s", t1, t2);
-  return 0;
-}
-
-
-static void addinfo (lua_State *L, const char *msg) {
-  CallInfo *ci = L->ci;
-  if (isLua(ci)) {  /* is Lua code? */
-    char buff[LUA_IDSIZE];  /* add file:line information */
-    int line = currentline(L, ci);
-    luaO_chunkid(buff, getstr(getluaproto(ci)->source), LUA_IDSIZE);
-    luaO_pushfstring(L, "%s:%d: %s", buff, line, msg);
-  }
-}
-
-
-void luaG_errormsg (lua_State *L) {
-  if (L->errfunc != 0) {  /* is there an error handling function? */
-    StkId errfunc = restorestack(L, L->errfunc);
-    if (!ttisfunction(errfunc) && !ttislightfunction(errfunc)) luaD_throw(L, LUA_ERRERR);
-    setobjs2s(L, L->top, L->top - 1);  /* move argument */
-    setobjs2s(L, L->top - 1, errfunc);  /* push function */
-    incr_top(L);
-    luaD_call(L, L->top - 2, 1);  /* call it */
-  }
-  luaD_throw(L, LUA_ERRRUN);
-}
-
-
-void luaG_runerror (lua_State *L, const char *fmt, ...) {
-  va_list argp;
-  va_start(argp, fmt);
-  addinfo(L, luaO_pushvfstring(L, fmt, argp));
-  va_end(argp);
-  luaG_errormsg(L);
-}
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/ldebug.h
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/ldebug.h b/libs/elua/elua_base/src/ldebug.h
deleted file mode 100644
index ba28a97..0000000
--- a/libs/elua/elua_base/src/ldebug.h
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
-** $Id: ldebug.h,v 2.3.1.1 2007/12/27 13:02:25 roberto Exp $
-** Auxiliary functions from Debug Interface module
-** See Copyright Notice in lua.h
-*/
-
-#ifndef ldebug_h
-#define ldebug_h
-
-
-#include "lstate.h"
-
-
-#define pcRel(pc, p)	(cast(int, (pc) - (p)->code) - 1)
-
-#define getline(f,pc)	(((f)->lineinfo) ? (f)->lineinfo[pc] : 0)
-
-#define resethookcount(L)	(L->hookcount = L->basehookcount)
-
-
-LUAI_FUNC void luaG_typeerror (lua_State *L, const TValue *o,
-                                             const char *opname);
-LUAI_FUNC void luaG_concaterror (lua_State *L, StkId p1, StkId p2);
-LUAI_FUNC void luaG_aritherror (lua_State *L, const TValue *p1,
-                                              const TValue *p2);
-LUAI_FUNC int luaG_ordererror (lua_State *L, const TValue *p1,
-                                             const TValue *p2);
-LUAI_FUNC void luaG_runerror (lua_State *L, const char *fmt, ...);
-LUAI_FUNC void luaG_errormsg (lua_State *L);
-LUAI_FUNC int luaG_checkcode (const Proto *pt);
-LUAI_FUNC int luaG_checkopenop (Instruction i);
-
-#endif


[36/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/src/arch/cortex_m0/m0/HAL_CM0.s
----------------------------------------------------------------------
diff --git a/kernel/os/src/arch/cortex_m0/m0/HAL_CM0.s b/kernel/os/src/arch/cortex_m0/m0/HAL_CM0.s
new file mode 100644
index 0000000..de7d46c
--- /dev/null
+++ b/kernel/os/src/arch/cortex_m0/m0/HAL_CM0.s
@@ -0,0 +1,277 @@
+/*----------------------------------------------------------------------------
+ * Copyright (c) 1999-2009 KEIL, 2009-2013 ARM Germany GmbH
+ * 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 ARM  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 COPYRIGHT HOLDERS AND CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ *---------------------------------------------------------------------------*/
+
+        .file   "HAL_CM0.S"
+        .syntax unified
+
+/*----------------------------------------------------------------------------
+ *      Functions
+ *---------------------------------------------------------------------------*/
+
+        .thumb
+
+        .section ".text"
+        .align  2
+
+/*--------------------------- os_set_env ------------------------------------*/
+#       void os_set_env (void);
+#
+#   Called to switch to privileged or unprivileged thread mode. The variable
+#   'os_flags' contains the CONTROL bit LSB to set the device into the
+#   proper mode. We also use PSP so we set bit 1 (the SPSEL bit) to 1.
+#
+
+        .thumb_func
+        .type   os_set_env, %function
+        .global os_set_env
+os_set_env:
+        .fnstart
+        .cantunwind
+
+        MSR     PSP,R0
+        LDR     R0,=os_flags
+        LDRB    R0,[R0]
+        ADDS    R0, R0, #2
+        MSR     CONTROL,R0
+        ISB
+        BX      LR
+
+        .fnend
+        .size   os_set_env, .-os_set_env
+/*--------------------------- os_set_env ------------------------------------*/
+
+
+/*--------------------------- os_arch_init_task_stack------------------------*/
+#       void os_arch_init_task_stack(os_stack_t *sf);
+# NOTE: This function only stores R4 through R11 on stack. The reason we do 
+# this is that the application may have stored some values in some of the
+# registers and we want to preserve those values (position independent code
+# is a good example). The other registers are handled in the C startup code.
+        .thumb_func
+        .type   os_arch_init_task_stack, %function
+        .global os_arch_init_task_stack
+os_arch_init_task_stack:
+        .fnstart
+
+        MOV     R3,R0
+        STMIA   R0!,{R4-R7}
+        MOV     R4,R8
+        MOV     R5,R9
+        MOV     R6,R10
+        MOV     R7,R11
+        STMIA   R0!,{R4-R7}
+        LDM     R3!,{R4-R7}
+        BX      LR
+
+        .fnend
+        .size   os_arch_init_task_stack, .-os_arch_init_task_stack
+/*--------------------------- os_set_env ------------------------------------*/
+
+
+/*-------------------------- SVC_Handler ------------------------------------*/
+#       void SVC_Handler (void);
+        .thumb_func
+        .type   SVC_Handler, %function
+        .global SVC_Handler
+SVC_Handler:
+        .fnstart
+        .cantunwind
+        MRS     R0,PSP                  /* Read PSP */
+        LDR     R1,[R0,#24]             /* Read Saved PC from Stack */
+        SUBS    R1,R1,#2                /* Point to SVC Instruction */
+        LDRB    R1,[R1]                 /* Load SVC Number */
+        CMP     R1,#0
+        BNE     SVC_User                /* User SVC Number > 0 */
+        LDR     R1,[R0,#16]             /* Read saved R12 from Stack */
+        MOV     R12, R1                 /* Store in R12 */
+        LDMIA   R0,{R0-R3}              /* Read R0-R3 from stack */
+        PUSH    {LR}                    /* Save LR */
+        BLX     R12                     /* Call SVC Function */
+        MRS     R3,PSP                  /* Read PSP */
+        STMIA   R3!,{R0-R2}             /* Store return values */
+        POP     {PC}                    /* RETI */
+
+        /*------------------- User SVC ------------------------------*/
+SVC_User:
+        PUSH    {R4,LR}                 /* Save Registers */
+        LDR     R2,=SVC_Count
+        LDR     R2,[R2]
+        CMP     R1,R2
+        BHI     SVC_Done                /* Overflow */
+        LDR     R4,=SVC_Table-4
+        LSLS    R1,R1,#2
+        LDR     R4,[R4,R1]              /* Load SVC Function Address */
+        MOV     LR,R4
+        LDMIA   R0,{R0-R3,R4}           /* Read R0-R3,R12 from stack */
+        MOV     R12,R4
+        BLX     LR                      /* Call SVC Function */
+        MRS     R4,PSP                  /* Read PSP */
+        STMIA   R4!,{R0-R3}             /* Function return values */
+SVC_Done:
+        POP     {R4,PC}                 /* RETI */
+        .fnend
+        .size   SVC_Handler, .-SVC_Handler
+/*-------------------------- PendSV_Handler ---------------------------------*/
+#       void PendSV_Handler (void);
+        .thumb_func
+        .type   PendSV_Handler, %function
+        .global PendSV_Handler
+PendSV_Handler:
+        .fnstart
+        .cantunwind
+
+        LDR     R3,=g_os_run_list   /* Get highest priority task ready to run */
+        LDR     R2,[R3]             /* Store in R2 */
+        LDR     R3,=g_current_task  /* Get current task */
+        LDR     R1,[R3]             /* Current task in R1 */
+        CMP     R1,R2
+        BNE     context_switch
+        BX      LR                  /* RETI, no task switch */
+context_switch:
+        MRS     R0,PSP              /* Read PSP */
+        SUBS    R0,R0,#32
+        STMIA   R0!,{R4-R7}         /* Save Old context */
+        MOV     R4,R8
+        MOV     R5,R9
+        MOV     R6,R10
+        MOV     R7,R11
+        STMIA   R0!,{R4-R7}         /* Save Old context */
+        SUBS    R0,R0,#32
+
+        STR     R0,[R1,#0]          /* Update stack pointer in current task */
+        STR     R2,[R3]             /* g_current_task = highest ready */
+
+        LDR     R0,[R2,#0]          /* get stack pointer of task we will start */
+        ADDS    R0,R0, #16
+        LDMIA   R0!,{R4-R7}         /* Restore New Context */
+        MOV     R8,R4
+        MOV     R9,R5
+        MOV     R10,R6
+        MOV     R11,R7
+        MSR     PSP,R0              /* Write PSP */
+        SUBS    R0,R0,#32
+        LDMIA   R0!,{R4-R7}         /* Restore New Context */
+        BX      LR                  /* Return to Thread Mode */
+
+        .fnend
+        .size   PendSV_Handler, .-PendSV_Handler
+
+
+
+/*-------------------------- SysTick_Handler --------------------------------*/
+
+#       void SysTick_Handler (void);
+        .thumb_func
+        .type   SysTick_Handler, %function
+        .global SysTick_Handler
+SysTick_Handler:
+        .fnstart
+        .cantunwind
+
+        PUSH    {R4,LR}                 /* Save EXC_RETURN */
+        BL      timer_handler
+        POP     {R4,PC}                 /* Restore EXC_RETURN */
+
+        .fnend
+        .size   SysTick_Handler, .-SysTick_Handler
+
+/* divide-by-zero */
+        .thumb_func
+	.type __aeabi_idiv0, %function
+	.global __aeabi_idiv0
+	.global __aeabi_ldiv0
+__aeabi_idiv0:
+__aeabi_ldiv0:
+        .fnstart
+        .cantunwind
+	push {r0,r1,r5}
+	ldr r0, =file_name
+	ldr r1, =__LINE__
+	ldr r5, =__assert_func
+	bx r5
+        .fnend
+        .size   __aeabi_idiv0, .-__aeabi_idiv0
+
+/*-------------------------- Defalt IRQ --------------------------------*/
+        .thumb_func
+        .type   os_default_irq_asm, %function
+        .global os_default_irq_asm
+os_default_irq_asm:
+        .fnstart
+        .cantunwind
+
+        /*
+         * LR = 0xfffffff9 if we were using MSP as SP
+         * LR = 0xfffffffd if we were using PSP as SP
+         */
+        MOV     R0,LR
+        MOVS    R1,#4
+        TST     R0,R1
+        MRS     R12,MSP
+        BEQ     using_msp_as_sp
+        MRS     R12,PSP
+using_msp_as_sp:
+        /*
+         * Push the "trap frame" structure onto stack by moving R8-R11 into 
+         * R0-R3 and then pushing R0-R3. LR gets pushed as well with LR 
+         * residing at higher memory, R8 at the lower memory address.
+         */
+        MOV     R0,R8
+        MOV     R1,R9
+        MOV     R2,R10
+        MOV     R3,R11
+        PUSH    {R0-R3, LR}
+        /* Now push r3 - r7. R3 is the lowest memory address. */
+        MOV     R3,R12
+        PUSH    {R3-R7}
+        MOV     R0, SP
+        BL      os_default_irq
+        POP     {R3-R7}
+        POP     {R0-R3}
+        MOV     R8,R0
+        MOV     R9,R1
+        MOV     R10,R2
+        MOV     R11,R3
+        POP     {PC}                 /* Restore EXC_RETURN */
+
+        .fnend
+        .size   os_default_irq_asm, .-os_default_irq_asm
+
+        /*
+         * Prevent libgcc unwind stuff from getting pulled in.
+         */
+        .section ".data"
+        .global __aeabi_unwind_cpp_pr0
+__aeabi_unwind_cpp_pr0:
+	.section ".rodata"
+file_name:
+	.asciz __FILE__
+        .end
+
+/*----------------------------------------------------------------------------
+ * end of file
+ *---------------------------------------------------------------------------*/

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/src/arch/cortex_m0/m0/SVC_Table.s
----------------------------------------------------------------------
diff --git a/kernel/os/src/arch/cortex_m0/m0/SVC_Table.s b/kernel/os/src/arch/cortex_m0/m0/SVC_Table.s
new file mode 100755
index 0000000..2b99321
--- /dev/null
+++ b/kernel/os/src/arch/cortex_m0/m0/SVC_Table.s
@@ -0,0 +1,56 @@
+;/*----------------------------------------------------------------------------
+; *      RL-ARM - RTX
+; *----------------------------------------------------------------------------
+; *      Name:    SVC_TABLE.S
+; *      Purpose: Pre-defined SVC Table for Cortex-M
+; *      Rev.:    V4.70
+; *----------------------------------------------------------------------------
+; *
+; * Copyright (c) 1999-2009 KEIL, 2009-2013 ARM Germany GmbH
+; * 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 ARM  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 COPYRIGHT HOLDERS AND CONTRIBUTORS BE
+; * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+; * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+; * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+; * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+; * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+; * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+; * POSSIBILITY OF SUCH DAMAGE.
+; *---------------------------------------------------------------------------*/
+
+
+        .file   "SVC_Table.S"
+
+
+        .section ".svc_table"
+
+        .global  SVC_Table
+SVC_Table:
+/* Insert user SVC functions here. SVC 0 used by RTL Kernel. */
+#       .long   __SVC_1                 /* user SVC function */
+SVC_End:
+
+        .global  SVC_Count
+SVC_Count:
+        .long   (SVC_End-SVC_Table)/4
+
+
+        .end
+
+/*----------------------------------------------------------------------------
+ * end of file
+ *---------------------------------------------------------------------------*/

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/src/arch/cortex_m0/os_arch_arm.c
----------------------------------------------------------------------
diff --git a/kernel/os/src/arch/cortex_m0/os_arch_arm.c b/kernel/os/src/arch/cortex_m0/os_arch_arm.c
new file mode 100755
index 0000000..65adc28
--- /dev/null
+++ b/kernel/os/src/arch/cortex_m0/os_arch_arm.c
@@ -0,0 +1,333 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include "os/os.h"
+#include "os/os_arch.h"
+#include <hal/hal_bsp.h>
+#include <hal/hal_os_tick.h>
+#include <bsp/cmsis_nvic.h>
+
+#include "os_priv.h"
+
+/*
+ * From HAL_CM0.s
+ */
+extern void SVC_Handler(void);
+extern void PendSV_Handler(void);
+extern void SysTick_Handler(void);
+/* XXX */
+
+/* Initial program status register */
+#define INITIAL_xPSR    0x01000000
+
+/*
+ * Exception priorities. The higher the number, the lower the priority. A
+ * higher priority exception will interrupt a lower priority exception.
+ */
+#define PEND_SV_PRIO    ((1 << __NVIC_PRIO_BITS) - 1)
+#define OS_TICK_PRIO    (PEND_SV_PRIO - 1)
+
+/* Make the SVC instruction highest priority */
+#define SVC_PRIO        (1)
+
+/* Stack frame structure */
+struct stack_frame {
+    uint32_t    r4;
+    uint32_t    r5;
+    uint32_t    r6;
+    uint32_t    r7;
+    uint32_t    r8;
+    uint32_t    r9;
+    uint32_t    r10;
+    uint32_t    r11;
+    uint32_t    r0;
+    uint32_t    r1;
+    uint32_t    r2;
+    uint32_t    r3;
+    uint32_t    r12;
+    uint32_t    lr;
+    uint32_t    pc;
+    uint32_t    xpsr;
+};
+
+#define SVC_ArgN(n) \
+  register int __r##n __asm("r"#n);
+
+#define SVC_Arg0()  \
+  SVC_ArgN(0)       \
+  SVC_ArgN(1)       \
+  SVC_ArgN(2)       \
+  SVC_ArgN(3)
+
+#if (defined (__MCU_CORTEX_M0_H__)) || defined (__CORTEX_M0PLUS)
+#define SVC_Call(f)                                                     \
+  __asm volatile                                                        \
+  (                                                                     \
+    "ldr r7,="#f"\n\t"                                                  \
+    "mov r12,r7\n\t"                                                    \
+    "svc 0"                                                             \
+    :               "=r" (__r0), "=r" (__r1), "=r" (__r2), "=r" (__r3)  \
+    :                "r" (__r0),  "r" (__r1),  "r" (__r2),  "r" (__r3)  \
+    : "r7", "r12", "lr", "cc"                                           \
+  );
+#else
+#define SVC_Call(f)                                                     \
+  __asm volatile                                                        \
+  (                                                                     \
+    "ldr r12,="#f"\n\t"                                                 \
+    "svc 0"                                                             \
+    :               "=r" (__r0), "=r" (__r1), "=r" (__r2), "=r" (__r3)  \
+    :                "r" (__r0),  "r" (__r1),  "r" (__r2),  "r" (__r3)  \
+    : "r12", "lr", "cc"                                                 \
+  );
+#endif
+
+/* XXX: determine how we will deal with running un-privileged */
+uint32_t os_flags = OS_RUN_PRIV;
+
+void
+timer_handler(void)
+{
+    os_time_advance(1);
+}
+
+void
+os_arch_ctx_sw(struct os_task *t)
+{
+    os_sched_ctx_sw_hook(t);
+
+    /* Set PendSV interrupt pending bit to force context switch */
+    SCB->ICSR = SCB_ICSR_PENDSVSET_Msk;
+}
+
+os_sr_t
+os_arch_save_sr(void)
+{
+    uint32_t isr_ctx;
+
+    isr_ctx = __get_PRIMASK();
+    __disable_irq();
+    return (isr_ctx & 1);
+}
+
+void
+os_arch_restore_sr(os_sr_t isr_ctx)
+{
+    if (!isr_ctx) {
+        __enable_irq();
+    }
+}
+
+int
+os_arch_in_critical(void)
+{
+    uint32_t isr_ctx;
+
+    isr_ctx = __get_PRIMASK();
+    return (isr_ctx & 1);
+}
+
+os_stack_t *
+os_arch_task_stack_init(struct os_task *t, os_stack_t *stack_top, int size)
+{
+    int i;
+    os_stack_t *s;
+    struct stack_frame *sf;
+
+    /* Get stack frame pointer */
+    s = (os_stack_t *) ((uint8_t *) stack_top - sizeof(*sf));
+
+    /* Zero out R1-R3, R12, LR */
+    for (i = 9; i < 14; ++i) {
+        s[i] = 0;
+    }
+
+    /* Set registers R4 - R11 on stack. */
+    os_arch_init_task_stack(s);
+
+    /* Set remaining portions of stack frame */
+    sf = (struct stack_frame *) s;
+    sf->xpsr = INITIAL_xPSR;
+    sf->pc = (uint32_t)t->t_func;
+    sf->r0 = (uint32_t)t->t_arg;
+
+    return (s);
+}
+
+void
+os_arch_init(void)
+{
+    os_init_idle_task();
+}
+
+__attribute__((always_inline))
+static inline void
+svc_os_arch_init(void)
+{
+    SVC_Arg0();
+    SVC_Call(os_arch_init);
+}
+
+os_error_t
+os_arch_os_init(void)
+{
+    os_error_t err;
+    int i;
+
+    /* Cannot be called within an ISR */
+    err = OS_ERR_IN_ISR;
+    if (__get_IPSR() == 0) {
+        err = OS_OK;
+
+        /* Drop priority for all interrupts */
+        for (i = 0; i < sizeof(NVIC->IP); i++) {
+            NVIC->IP[i] = 0xff;
+        }
+
+        NVIC_SetVector(SVCall_IRQn, (uint32_t)SVC_Handler);
+        NVIC_SetVector(PendSV_IRQn, (uint32_t)PendSV_Handler);
+        NVIC_SetVector(SysTick_IRQn, (uint32_t)SysTick_Handler);
+
+        /*
+         * Install default interrupt handler, which'll print out system
+         * state at the time of the interrupt, and few other regs which
+         * should help in trying to figure out what went wrong.
+         */
+        NVIC_SetVector(NonMaskableInt_IRQn, (uint32_t)os_default_irq_asm);
+        NVIC_SetVector(HardFault_IRQn, (uint32_t)os_default_irq_asm);
+        NVIC_SetVector(-13, (uint32_t)os_default_irq_asm); /* Hardfault */
+        for (i = 0; i < NVIC_NUM_VECTORS - NVIC_USER_IRQ_OFFSET; i++) {
+            NVIC_SetVector(i, (uint32_t)os_default_irq_asm);
+        }
+
+        /* Set the PendSV interrupt exception priority to the lowest priority */
+        NVIC_SetPriority(PendSV_IRQn, PEND_SV_PRIO);
+
+        /* Set the SVC interrupt to priority 0 (highest configurable) */
+        NVIC_SetPriority(SVCall_IRQn, SVC_PRIO);
+
+        /* Check if privileged or not */
+        if ((__get_CONTROL() & 1) == 0) {
+            os_arch_init();
+        } else {
+            svc_os_arch_init();
+        }
+    }
+
+    return err;
+}
+
+uint32_t
+os_arch_start(void)
+{
+    struct os_task *t;
+
+    /* Get the highest priority ready to run to set the current task */
+    t = os_sched_next_task();
+    os_sched_set_current_task(t);
+
+    /* Adjust PSP so it looks like this task just took an exception */
+    __set_PSP((uint32_t)t->t_stackptr + offsetof(struct stack_frame, r0));
+
+    /* Intitialize and start system clock timer */
+    os_tick_init(OS_TICKS_PER_SEC, OS_TICK_PRIO);
+
+    /* Mark the OS as started, right before we run our first task */
+    g_os_started = 1;
+
+    /* Perform context switch */
+    os_arch_ctx_sw(t);
+
+    return (uint32_t)(t->t_arg);
+}
+
+__attribute__((always_inline))
+static inline void svc_os_arch_start(void)
+{
+    SVC_Arg0();
+    SVC_Call(os_arch_start);
+}
+
+/**
+ * Start the OS. First check to see if we are running with the correct stack
+ * pointer set (PSP) and privilege mode (PRIV).
+ *
+ * @return os_error_t
+ */
+os_error_t
+os_arch_os_start(void)
+{
+    os_error_t err;
+
+    /*
+     * Set the os environment. This will set stack pointers and, based
+     * on the contents of os_flags, will determine if the tasks run in
+     * priviliged or un-privileged mode.
+     *
+     * We switch to using "empty" part of idle task's stack until
+     * the svc_os_arch_start() executes SVC, and we will never return.
+     */
+    os_set_env(g_idle_task.t_stackptr - 1);
+
+    err = OS_ERR_IN_ISR;
+    if (__get_IPSR() == 0) {
+        /*
+         * The following switch statement is really just a sanity check to
+         * insure that the os initialization routine was called prior to the
+         * os start routine.
+         */
+        err = OS_OK;
+        switch (__get_CONTROL() & 0x03) {
+        /*
+         * These two cases are for completeness. Thread mode should be set
+         * to use PSP already.
+         *
+         * Fall-through intentional!
+         */
+        case 0x00:
+        case 0x01:
+            err = OS_ERR_PRIV;
+            break;
+        case 0x02:
+            /*
+             * We are running in Privileged Thread mode w/SP = PSP but we
+             * are supposed to be un-privileged.
+             */
+            if ((os_flags & 1) == OS_RUN_UNPRIV) {
+                err = OS_ERR_PRIV;
+            }
+            break;
+        case 0x03:
+            /*
+             * We are running in Unprivileged Thread mode w/SP = PSP but we
+             * are supposed to be privileged.
+             */
+            if  ((os_flags & 1) == OS_RUN_PRIV) {
+                err = OS_ERR_PRIV;
+            }
+            break;
+        }
+        if (err == OS_OK) {
+            /* Always start OS through SVC call */
+            svc_os_arch_start();
+        }
+    }
+
+    return err;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/src/arch/cortex_m0/os_fault.c
----------------------------------------------------------------------
diff --git a/kernel/os/src/arch/cortex_m0/os_fault.c b/kernel/os/src/arch/cortex_m0/os_fault.c
new file mode 100644
index 0000000..4167682
--- /dev/null
+++ b/kernel/os/src/arch/cortex_m0/os_fault.c
@@ -0,0 +1,158 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include <stdint.h>
+#include <unistd.h>
+
+#include "syscfg/syscfg.h"
+#include "console/console.h"
+#include "hal/hal_system.h"
+#if MYNEWT_VAL(OS_COREDUMP)
+#include "coredump/coredump.h"
+#endif
+#include "os/os.h"
+
+
+struct exception_frame {
+    uint32_t r0;
+    uint32_t r1;
+    uint32_t r2;
+    uint32_t r3;
+    uint32_t r12;
+    uint32_t lr;
+    uint32_t pc;
+    uint32_t psr;
+};
+
+struct trap_frame {
+    struct exception_frame *ef;
+    uint32_t r4;
+    uint32_t r5;
+    uint32_t r6;
+    uint32_t r7;
+    uint32_t r8;
+    uint32_t r9;
+    uint32_t r10;
+    uint32_t r11;
+    uint32_t lr;    /* this LR holds EXC_RETURN */
+};
+
+struct coredump_regs {
+    uint32_t r0;
+    uint32_t r1;
+    uint32_t r2;
+    uint32_t r3;
+    uint32_t r4;
+    uint32_t r5;
+    uint32_t r6;
+    uint32_t r7;
+    uint32_t r8;
+    uint32_t r9;
+    uint32_t r10;
+    uint32_t r11;
+    uint32_t r12;
+    uint32_t sp;
+    uint32_t lr;
+    uint32_t pc;
+    uint32_t psr;
+};
+
+void __assert_func(const char *file, int line, const char *func, const char *e);
+
+#if MYNEWT_VAL(OS_COREDUMP)
+static void
+trap_to_coredump(struct trap_frame *tf, struct coredump_regs *regs)
+{
+    regs->r0 = tf->ef->r0;
+    regs->r1 = tf->ef->r1;
+    regs->r2 = tf->ef->r2;
+    regs->r3 = tf->ef->r3;
+    regs->r4 = tf->r4;
+    regs->r5 = tf->r5;
+    regs->r6 = tf->r6;
+    regs->r7 = tf->r7;
+    regs->r8 = tf->r8;
+    regs->r9 = tf->r9;
+    regs->r10 = tf->r10;
+    regs->r11 = tf->r11;
+    regs->r12 = tf->ef->r12;
+    /*
+     * SP just before exception for the coredump.
+     * See ARMv7-M Architecture Ref Manual, sections B1.5.6 - B1.5.8
+     * SP is adjusted by 0x20.
+     * If SCB->CCR.STKALIGN is set, SP is aligned to 8-byte boundary on
+     * exception entry.
+     * If this alignment adjustment happened, xPSR will have bit 9 set.
+     */
+    regs->sp = ((uint32_t)tf->ef) + 0x20;
+    if ((SCB->CCR & SCB_CCR_STKALIGN_Msk) & tf->ef->psr & (1 << 9)) {
+        regs->sp += 4;
+    }
+    regs->lr = tf->ef->lr;
+    regs->pc = tf->ef->pc;
+    regs->psr = tf->ef->psr;
+}
+#endif
+
+void
+__assert_func(const char *file, int line, const char *func, const char *e)
+{
+    int sr;
+
+    OS_ENTER_CRITICAL(sr);
+    (void)sr;
+    console_blocking_mode();
+    console_printf("Assert %s; failed in %s:%d\n", e ? e : "", file, line);
+    if (system_debugger_connected()) {
+       /*
+        * If debugger is attached, breakpoint before the trap.
+        */
+       asm("bkpt");
+    }
+    SCB->ICSR = SCB_ICSR_NMIPENDSET_Msk;
+    /* Exception happens right away. Next line not executed. */
+    system_reset();
+}
+
+void
+os_default_irq(struct trap_frame *tf)
+{
+#if MYNEWT_VAL(OS_COREDUMP)
+    struct coredump_regs regs;
+#endif
+
+    console_blocking_mode();
+    console_printf("Unhandled interrupt (%ld), exception sp 0x%08lx\n",
+      SCB->ICSR & SCB_ICSR_VECTACTIVE_Msk, (uint32_t)tf->ef);
+    console_printf(" r0:0x%08lx  r1:0x%08lx  r2:0x%08lx  r3:0x%08lx\n",
+      tf->ef->r0, tf->ef->r1, tf->ef->r2, tf->ef->r3);
+    console_printf(" r4:0x%08lx  r5:0x%08lx  r6:0x%08lx  r7:0x%08lx\n",
+      tf->r4, tf->r5, tf->r6, tf->r7);
+    console_printf(" r8:0x%08lx  r9:0x%08lx r10:0x%08lx r11:0x%08lx\n",
+      tf->r8, tf->r9, tf->r10, tf->r11);
+    console_printf("r12:0x%08lx  lr:0x%08lx  pc:0x%08lx psr:0x%08lx\n",
+      tf->ef->r12, tf->ef->lr, tf->ef->pc, tf->ef->psr);
+    console_printf("ICSR:0x%08lx\n", SCB->ICSR);
+#if MYNEWT_VAL(OS_COREDUMP)
+    trap_to_coredump(tf, &regs);
+    coredump_dump(&regs, sizeof(regs));
+#endif
+    system_reset();
+}
+

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/src/arch/cortex_m4/m4/HAL_CM4.s
----------------------------------------------------------------------
diff --git a/kernel/os/src/arch/cortex_m4/m4/HAL_CM4.s b/kernel/os/src/arch/cortex_m4/m4/HAL_CM4.s
new file mode 100755
index 0000000..9c6ab52
--- /dev/null
+++ b/kernel/os/src/arch/cortex_m4/m4/HAL_CM4.s
@@ -0,0 +1,224 @@
+/*----------------------------------------------------------------------------
+ * Copyright (c) 1999-2009 KEIL, 2009-2013 ARM Germany GmbH
+ * 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 ARM  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 COPYRIGHT HOLDERS AND CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ *---------------------------------------------------------------------------*/
+
+        .file   "HAL_CM4.S"
+        .syntax unified
+
+/*----------------------------------------------------------------------------
+ *      Functions
+ *---------------------------------------------------------------------------*/
+
+        .thumb
+
+        .section ".text"
+        .align  2
+
+/*--------------------------- os_set_env ------------------------------------*/
+#       void os_set_env (void);
+#
+#   Called to switch to privileged or unprivileged thread mode. The variable
+#   'os_flags' contains the CONTROL bit LSB to set the device into the
+#   proper mode. We also use PSP so we set bit 1 (the SPSEL bit) to 1.
+#
+
+        .thumb_func
+        .type   os_set_env, %function
+        .global os_set_env
+os_set_env:
+        .fnstart
+        .cantunwind
+
+        MSR     PSP,R0
+        LDR     R0,=os_flags
+        LDRB    R0,[R0]
+        ADDS    R0, R0, #2
+        MSR     CONTROL,R0
+        ISB
+        BX      LR
+
+        .fnend
+        .size   os_set_env, .-os_set_env
+
+/*--------------------------- os_set_env ------------------------------------*/
+
+
+/*--------------------------- os_arch_init_task_stack------------------------*/
+#       void os_arch_init_task_stack(os_stack_t *sf);
+# NOTE: This function only stores R4 through R11 on stack. The reason we do 
+# this is that the application may have stored some values in some of the
+# registers and we want to preserve those values (position independent code
+# is a good example). The other registers are handled in the C startup code.
+        .thumb_func
+        .type   os_arch_init_task_stack, %function
+        .global os_arch_init_task_stack
+os_arch_init_task_stack:
+        .fnstart
+
+        STMIA   R0,{R4-R11}
+        BX      LR
+
+        .fnend
+        .size   os_arch_init_task_stack, .-os_arch_init_task_stack
+/*--------------------------- os_set_env ------------------------------------*/
+
+
+/*-------------------------- SVC_Handler ------------------------------------*/
+
+#       void SVC_Handler (void);
+
+        .thumb_func
+        .type   SVC_Handler, %function
+        .global SVC_Handler
+SVC_Handler:
+        .fnstart
+        .cantunwind
+
+        MRS     R0,PSP                  /* Read PSP */
+        LDR     R1,[R0,#24]             /* Read Saved PC from Stack */
+        LDRB    R1,[R1,#-2]             /* Load SVC Number */
+        CBNZ    R1,SVC_User
+
+        LDM     R0,{R0-R3,R12}          /* Read R0-R3,R12 from stack */
+        PUSH    {R4,LR}                 /* Save EXC_RETURN */
+        BLX     R12                     /* Call SVC Function */
+        POP     {R4,LR}                 /* Restore EXC_RETURN */
+
+        MRS     R12,PSP                 /* Read PSP */
+        STM     R12,{R0-R2}             /* Store return values */
+        BX      LR                      /* Return from interrupt */
+
+        /*------------------- User SVC ------------------------------*/
+SVC_User:
+        PUSH    {R4,LR}                 /* Save EXC_RETURN */
+        LDR     R2,=SVC_Count
+        LDR     R2,[R2]
+        CMP     R1,R2
+        BHI     SVC_Done                /* Overflow */
+
+        LDR     R4,=SVC_Table-4
+        LDR     R4,[R4,R1,LSL #2]       /* Load SVC Function Address */
+
+        LDM     R0,{R0-R3,R12}          /* Read R0-R3,R12 from stack */
+        BLX     R4                      /* Call SVC Function */
+
+        MRS     R12,PSP
+        STM     R12,{R0-R3}             /* Function return values */
+SVC_Done:
+        POP     {R4,LR}                 /* Restore EXC_RETURN */
+        BX      LR                      /* Return from interrupt */
+
+        .fnend
+        .size   SVC_Handler, .-SVC_Handler
+
+
+/*-------------------------- PendSV_Handler ---------------------------------*/
+
+#       void PendSV_Handler (void);
+
+        .thumb_func
+        .type   PendSV_Handler, %function
+        .global PendSV_Handler
+PendSV_Handler:
+        .fnstart
+        .cantunwind
+
+        LDR     R3,=g_os_run_list       /* Get highest priority task ready to run */
+        LDR     R2,[R3]                 /* Store in R2 */
+        LDR     R3,=g_current_task      /* Get current task */
+        LDR     R1,[R3]                 /* Current task in R1 */
+        CMP     R1,R2
+        IT      EQ
+        BXEQ    LR                      /* RETI, no task switch */
+
+        MRS     R12,PSP                 /* Read PSP */
+        STMDB   R12!,{R4-R11}           /* Save Old context */
+        STR     R12,[R1,#0]             /* Update stack pointer in current task */
+        STR     R2,[R3]                 /* g_current_task = highest ready */
+
+        LDR     R12,[R2,#0]             /* get stack pointer of task we will start */
+        LDMIA   R12!,{R4-R11}           /* Restore New Context */
+        MSR     PSP,R12                 /* Write PSP */
+        BX      LR                      /* Return to Thread Mode */
+
+        .fnend
+        .size   PendSV_Handler, .-PendSV_Handler
+
+
+/*-------------------------- SysTick_Handler --------------------------------*/
+
+#       void SysTick_Handler (void);
+        .thumb_func
+        .type   SysTick_Handler, %function
+        .global SysTick_Handler
+SysTick_Handler:
+        .fnstart
+        .cantunwind
+
+        PUSH    {R4,LR}                 /* Save EXC_RETURN */
+        BL      timer_handler
+        POP     {R4,LR}                 /* Restore EXC_RETURN */
+        BX      LR
+
+        .fnend
+        .size   SysTick_Handler, .-SysTick_Handler
+
+/*-------------------------- Defalt IRQ --------------------------------*/
+        .thumb_func
+        .type   os_default_irq_asm, %function
+        .global os_default_irq_asm
+os_default_irq_asm:
+        .fnstart
+        .cantunwind
+
+        /*
+         * LR = 0xfffffff9 if we were using MSP as SP
+         * LR = 0xfffffffd if we were using PSP as SP
+         */
+        TST     LR,#4
+        ITE     EQ
+        MRSEQ   R3,MSP
+        MRSNE   R3,PSP
+        PUSH    {R3-R11,LR}
+        MOV     R0, SP
+        BL      os_default_irq
+        POP     {R3-R11,LR}                 /* Restore EXC_RETURN */
+        BX      LR
+
+        .fnend
+        .size   os_default_irq_asm, .-os_default_irq_asm
+
+	/*
+	 * Prevent libgcc unwind stuff from getting pulled in.
+	 */
+        .section ".data"
+	.global __aeabi_unwind_cpp_pr0
+__aeabi_unwind_cpp_pr0:
+        .end
+
+/*----------------------------------------------------------------------------
+ * end of file
+ *---------------------------------------------------------------------------*/

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/src/arch/cortex_m4/m4/SVC_Table.s
----------------------------------------------------------------------
diff --git a/kernel/os/src/arch/cortex_m4/m4/SVC_Table.s b/kernel/os/src/arch/cortex_m4/m4/SVC_Table.s
new file mode 100755
index 0000000..2b99321
--- /dev/null
+++ b/kernel/os/src/arch/cortex_m4/m4/SVC_Table.s
@@ -0,0 +1,56 @@
+;/*----------------------------------------------------------------------------
+; *      RL-ARM - RTX
+; *----------------------------------------------------------------------------
+; *      Name:    SVC_TABLE.S
+; *      Purpose: Pre-defined SVC Table for Cortex-M
+; *      Rev.:    V4.70
+; *----------------------------------------------------------------------------
+; *
+; * Copyright (c) 1999-2009 KEIL, 2009-2013 ARM Germany GmbH
+; * 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 ARM  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 COPYRIGHT HOLDERS AND CONTRIBUTORS BE
+; * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+; * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+; * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+; * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+; * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+; * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+; * POSSIBILITY OF SUCH DAMAGE.
+; *---------------------------------------------------------------------------*/
+
+
+        .file   "SVC_Table.S"
+
+
+        .section ".svc_table"
+
+        .global  SVC_Table
+SVC_Table:
+/* Insert user SVC functions here. SVC 0 used by RTL Kernel. */
+#       .long   __SVC_1                 /* user SVC function */
+SVC_End:
+
+        .global  SVC_Count
+SVC_Count:
+        .long   (SVC_End-SVC_Table)/4
+
+
+        .end
+
+/*----------------------------------------------------------------------------
+ * end of file
+ *---------------------------------------------------------------------------*/

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/src/arch/cortex_m4/os_arch_arm.c
----------------------------------------------------------------------
diff --git a/kernel/os/src/arch/cortex_m4/os_arch_arm.c b/kernel/os/src/arch/cortex_m4/os_arch_arm.c
new file mode 100755
index 0000000..cef11f9
--- /dev/null
+++ b/kernel/os/src/arch/cortex_m4/os_arch_arm.c
@@ -0,0 +1,328 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include "os/os.h"
+#include "os/os_arch.h"
+#include <hal/hal_bsp.h>
+#include <hal/hal_os_tick.h>
+#include <bsp/cmsis_nvic.h>
+
+#include "os_priv.h"
+
+/* Initial program status register */
+#define INITIAL_xPSR    0x01000000
+
+/*
+ * Exception priorities. The higher the number, the lower the priority. A
+ * higher priority exception will interrupt a lower priority exception.
+ */
+#define PEND_SV_PRIO    ((1 << __NVIC_PRIO_BITS) - 1)
+#define OS_TICK_PRIO    (PEND_SV_PRIO - 1)
+
+/* Make the SVC instruction highest priority */
+#define SVC_PRIO        (1)
+
+/* Stack frame structure */
+struct stack_frame {
+    uint32_t    r4;
+    uint32_t    r5;
+    uint32_t    r6;
+    uint32_t    r7;
+    uint32_t    r8;
+    uint32_t    r9;
+    uint32_t    r10;
+    uint32_t    r11;
+    uint32_t    r0;
+    uint32_t    r1;
+    uint32_t    r2;
+    uint32_t    r3;
+    uint32_t    r12;
+    uint32_t    lr;
+    uint32_t    pc;
+    uint32_t    xpsr;
+};
+
+#define SVC_ArgN(n) \
+  register int __r##n __asm("r"#n);
+
+#define SVC_Arg0()  \
+  SVC_ArgN(0)       \
+  SVC_ArgN(1)       \
+  SVC_ArgN(2)       \
+  SVC_ArgN(3)
+
+#if (defined (__CORTEX_M0)) || defined (__CORTEX_M0PLUS)
+#define SVC_Call(f)                                                     \
+  __asm volatile                                                        \
+  (                                                                     \
+    "ldr r7,="#f"\n\t"                                                  \
+    "mov r12,r7\n\t"                                                    \
+    "svc 0"                                                             \
+    :               "=r" (__r0), "=r" (__r1), "=r" (__r2), "=r" (__r3)  \
+    :                "r" (__r0),  "r" (__r1),  "r" (__r2),  "r" (__r3)  \
+    : "r7", "r12", "lr", "cc"                                           \
+  );
+#else
+#define SVC_Call(f)                                                     \
+  __asm volatile                                                        \
+  (                                                                     \
+    "ldr r12,="#f"\n\t"                                                 \
+    "svc 0"                                                             \
+    :               "=r" (__r0), "=r" (__r1), "=r" (__r2), "=r" (__r3)  \
+    :                "r" (__r0),  "r" (__r1),  "r" (__r2),  "r" (__r3)  \
+    : "r12", "lr", "cc"                                                 \
+  );
+#endif
+
+/* XXX: determine how we will deal with running un-privileged */
+uint32_t os_flags = OS_RUN_PRIV;
+
+void
+timer_handler(void)
+{
+    os_time_advance(1);
+}
+
+void
+os_arch_ctx_sw(struct os_task *t)
+{
+    os_sched_ctx_sw_hook(t);
+
+    /* Set PendSV interrupt pending bit to force context switch */
+    SCB->ICSR = SCB_ICSR_PENDSVSET_Msk;
+}
+
+os_sr_t
+os_arch_save_sr(void)
+{
+    uint32_t isr_ctx;
+
+    isr_ctx = __get_PRIMASK();
+    __disable_irq();
+    return (isr_ctx & 1);
+}
+
+void
+os_arch_restore_sr(os_sr_t isr_ctx)
+{
+    if (!isr_ctx) {
+        __enable_irq();
+    }
+}
+
+int
+os_arch_in_critical(void)
+{
+    uint32_t isr_ctx;
+
+    isr_ctx = __get_PRIMASK();
+    return (isr_ctx & 1);
+}
+
+os_stack_t *
+os_arch_task_stack_init(struct os_task *t, os_stack_t *stack_top, int size)
+{
+    int i;
+    os_stack_t *s;
+    struct stack_frame *sf;
+
+    /* Get stack frame pointer */
+    s = (os_stack_t *) ((uint8_t *) stack_top - sizeof(*sf));
+
+    /* Zero out R1-R3, R12, LR */
+    for (i = 9; i < 14; ++i) {
+        s[i] = 0;
+    }
+
+    /* Set registers R4 - R11 on stack. */
+    os_arch_init_task_stack(s);
+
+    /* Set remaining portions of stack frame */
+    sf = (struct stack_frame *) s;
+    sf->xpsr = INITIAL_xPSR;
+    sf->pc = (uint32_t)t->t_func;
+    sf->r0 = (uint32_t)t->t_arg;
+
+    return (s);
+}
+
+void
+os_arch_init(void)
+{
+    /*
+     * Trap on divide-by-zero.
+     */
+    SCB->CCR |= SCB_CCR_DIV_0_TRP_Msk;
+    os_init_idle_task();
+}
+
+__attribute__((always_inline))
+static inline void
+svc_os_arch_init(void)
+{
+    SVC_Arg0();
+    SVC_Call(os_arch_init);
+}
+
+os_error_t
+os_arch_os_init(void)
+{
+    os_error_t err;
+    int i;
+
+    /* Cannot be called within an ISR */
+    err = OS_ERR_IN_ISR;
+    if (__get_IPSR() == 0) {
+        err = OS_OK;
+
+        /* Drop priority for all interrupts */
+        for (i = 0; i < sizeof(NVIC->IP); i++) {
+            NVIC->IP[i] = 0xff;
+        }
+
+        /*
+         * Install default interrupt handler, which'll print out system
+         * state at the time of the interrupt, and few other regs which
+         * should help in trying to figure out what went wrong.
+         */
+        NVIC_SetVector(NonMaskableInt_IRQn, (uint32_t)os_default_irq_asm);
+        NVIC_SetVector(-13, (uint32_t)os_default_irq_asm);
+        NVIC_SetVector(MemoryManagement_IRQn, (uint32_t)os_default_irq_asm);
+        NVIC_SetVector(BusFault_IRQn, (uint32_t)os_default_irq_asm);
+        NVIC_SetVector(UsageFault_IRQn, (uint32_t)os_default_irq_asm);
+        for (i = 0; i < NVIC_NUM_VECTORS - NVIC_USER_IRQ_OFFSET; i++) {
+            NVIC_SetVector(i, (uint32_t)os_default_irq_asm);
+        }
+
+        /* Set the PendSV interrupt exception priority to the lowest priority */
+        NVIC_SetPriority(PendSV_IRQn, PEND_SV_PRIO);
+
+        /* Set the SVC interrupt to priority 0 (highest configurable) */
+        NVIC_SetPriority(SVCall_IRQn, SVC_PRIO);
+
+        /* Check if privileged or not */
+        if ((__get_CONTROL() & 1) == 0) {
+            os_arch_init();
+        } else {
+            svc_os_arch_init();
+        }
+    }
+
+    return err;
+}
+
+uint32_t
+os_arch_start(void)
+{
+    struct os_task *t;
+
+    /* Get the highest priority ready to run to set the current task */
+    t = os_sched_next_task();
+    os_sched_set_current_task(t);
+
+    /* Adjust PSP so it looks like this task just took an exception */
+    __set_PSP((uint32_t)t->t_stackptr + offsetof(struct stack_frame, r0));
+
+    /* Intitialize and start system clock timer */
+    os_tick_init(OS_TICKS_PER_SEC, OS_TICK_PRIO);
+
+    /* Mark the OS as started, right before we run our first task */
+    g_os_started = 1;
+
+    /* Perform context switch */
+    os_arch_ctx_sw(t);
+
+    return (uint32_t)(t->t_arg);
+}
+
+__attribute__((always_inline))
+static inline void svc_os_arch_start(void)
+{
+    SVC_Arg0();
+    SVC_Call(os_arch_start);
+}
+
+/**
+ * Start the OS. First check to see if we are running with the correct stack
+ * pointer set (PSP) and privilege mode (PRIV).
+ *
+ *
+ * @return os_error_t
+ */
+os_error_t
+os_arch_os_start(void)
+{
+    os_error_t err;
+
+    /*
+     * Set the os environment. This will set stack pointers and, based
+     * on the contents of os_flags, will determine if the tasks run in
+     * privileged or un-privileged mode.
+     *
+     * We switch to using "empty" part of idle task's stack until
+     * the svc_os_arch_start() executes SVC, and we will never return.
+     */
+    os_set_env(g_idle_task.t_stackptr - 1);
+
+    err = OS_ERR_IN_ISR;
+    if (__get_IPSR() == 0) {
+        /*
+         * The following switch statement is really just a sanity check to
+         * insure that the os initialization routine was called prior to the
+         * os start routine.
+         */
+        err = OS_OK;
+        switch (__get_CONTROL() & 0x03) {
+        /*
+         * These two cases are for completeness. Thread mode should be set
+         * to use PSP already.
+         *
+         * Fall-through intentional!
+         */
+        case 0x00:
+        case 0x01:
+            err = OS_ERR_PRIV;
+            break;
+        case 0x02:
+            /*
+             * We are running in Privileged Thread mode w/SP = PSP but we
+             * are supposed to be un-privileged.
+             */
+            if ((os_flags & 1) == OS_RUN_UNPRIV) {
+                err = OS_ERR_PRIV;
+            }
+            break;
+        case 0x03:
+            /*
+             * We are running in Unprivileged Thread mode w/SP = PSP but we
+             * are supposed to be privileged.
+             */
+            if  ((os_flags & 1) == OS_RUN_PRIV) {
+                err = OS_ERR_PRIV;
+            }
+            break;
+        }
+        if (err == OS_OK) {
+            /* Always start OS through SVC call */
+            svc_os_arch_start();
+        }
+    }
+
+    return err;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/src/arch/cortex_m4/os_fault.c
----------------------------------------------------------------------
diff --git a/kernel/os/src/arch/cortex_m4/os_fault.c b/kernel/os/src/arch/cortex_m4/os_fault.c
new file mode 100644
index 0000000..d7806db
--- /dev/null
+++ b/kernel/os/src/arch/cortex_m4/os_fault.c
@@ -0,0 +1,160 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include "syscfg/syscfg.h"
+#include "console/console.h"
+#include "hal/hal_system.h"
+#include "os/os.h"
+
+#if MYNEWT_VAL(OS_COREDUMP)
+#include "coredump/coredump.h"
+#endif
+
+#include <stdint.h>
+#include <unistd.h>
+
+struct exception_frame {
+    uint32_t r0;
+    uint32_t r1;
+    uint32_t r2;
+    uint32_t r3;
+    uint32_t r12;
+    uint32_t lr;
+    uint32_t pc;
+    uint32_t psr;
+};
+
+struct trap_frame {
+    struct exception_frame *ef;
+    uint32_t r4;
+    uint32_t r5;
+    uint32_t r6;
+    uint32_t r7;
+    uint32_t r8;
+    uint32_t r9;
+    uint32_t r10;
+    uint32_t r11;
+    uint32_t lr;    /* this LR holds EXC_RETURN */
+};
+
+struct coredump_regs {
+    uint32_t r0;
+    uint32_t r1;
+    uint32_t r2;
+    uint32_t r3;
+    uint32_t r4;
+    uint32_t r5;
+    uint32_t r6;
+    uint32_t r7;
+    uint32_t r8;
+    uint32_t r9;
+    uint32_t r10;
+    uint32_t r11;
+    uint32_t r12;
+    uint32_t sp;
+    uint32_t lr;
+    uint32_t pc;
+    uint32_t psr;
+};
+
+void __assert_func(const char *file, int line, const char *func, const char *e);
+
+#if MYNEWT_VAL(OS_COREDUMP)
+static void
+trap_to_coredump(struct trap_frame *tf, struct coredump_regs *regs)
+{
+    regs->r0 = tf->ef->r0;
+    regs->r1 = tf->ef->r1;
+    regs->r2 = tf->ef->r2;
+    regs->r3 = tf->ef->r3;
+    regs->r4 = tf->r4;
+    regs->r5 = tf->r5;
+    regs->r6 = tf->r6;
+    regs->r7 = tf->r7;
+    regs->r8 = tf->r8;
+    regs->r9 = tf->r9;
+    regs->r10 = tf->r10;
+    regs->r11 = tf->r11;
+    regs->r12 = tf->ef->r12;
+    /*
+     * SP just before exception for the coredump.
+     * See ARMv7-M Architecture Ref Manual, sections B1.5.6 - B1.5.8
+     * SP is adjusted by 0x20.
+     * If SCB->CCR.STKALIGN is set, SP is aligned to 8-byte boundary on
+     * exception entry.
+     * If this alignment adjustment happened, xPSR will have bit 9 set.
+     */
+    regs->sp = ((uint32_t)tf->ef) + 0x20;
+    if ((SCB->CCR & SCB_CCR_STKALIGN_Msk) & tf->ef->psr & (1 << 9)) {
+        regs->sp += 4;
+    }
+    regs->lr = tf->ef->lr;
+    regs->pc = tf->ef->pc;
+    regs->psr = tf->ef->psr;
+}
+#endif
+
+void
+__assert_func(const char *file, int line, const char *func, const char *e)
+{
+    int sr;
+
+    OS_ENTER_CRITICAL(sr);
+    (void)sr;
+    console_blocking_mode();
+    console_printf("Assert %s; failed in %s:%d\n", e ? e : "", file, line);
+    if (system_debugger_connected()) {
+       /*
+        * If debugger is attached, breakpoint before the trap.
+        */
+       asm("bkpt");
+    }
+    SCB->ICSR = SCB_ICSR_NMIPENDSET_Msk;
+    asm("isb");
+    system_reset();
+}
+
+void
+os_default_irq(struct trap_frame *tf)
+{
+#if MYNEWT_VAL(OS_COREDUMP)
+    struct coredump_regs regs;
+#endif
+
+    console_blocking_mode();
+    console_printf("Unhandled interrupt (%ld), exception sp 0x%08lx\n",
+      SCB->ICSR & SCB_ICSR_VECTACTIVE_Msk, (uint32_t)tf->ef);
+    console_printf(" r0:0x%08lx  r1:0x%08lx  r2:0x%08lx  r3:0x%08lx\n",
+      tf->ef->r0, tf->ef->r1, tf->ef->r2, tf->ef->r3);
+    console_printf(" r4:0x%08lx  r5:0x%08lx  r6:0x%08lx  r7:0x%08lx\n",
+      tf->r4, tf->r5, tf->r6, tf->r7);
+    console_printf(" r8:0x%08lx  r9:0x%08lx r10:0x%08lx r11:0x%08lx\n",
+      tf->r8, tf->r9, tf->r10, tf->r11);
+    console_printf("r12:0x%08lx  lr:0x%08lx  pc:0x%08lx psr:0x%08lx\n",
+      tf->ef->r12, tf->ef->lr, tf->ef->pc, tf->ef->psr);
+    console_printf("ICSR:0x%08lx HFSR:0x%08lx CFSR:0x%08lx\n",
+      SCB->ICSR, SCB->HFSR, SCB->CFSR);
+    console_printf("BFAR:0x%08lx MMFAR:0x%08lx\n", SCB->BFAR, SCB->MMFAR);
+
+#if MYNEWT_VAL(OS_COREDUMP)
+    trap_to_coredump(tf, &regs);
+    coredump_dump(&regs, sizeof(regs));
+#endif
+    system_reset();
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/src/arch/sim/os_arch_sim.c
----------------------------------------------------------------------
diff --git a/kernel/os/src/arch/sim/os_arch_sim.c b/kernel/os/src/arch/sim/os_arch_sim.c
new file mode 100644
index 0000000..51731f7
--- /dev/null
+++ b/kernel/os/src/arch/sim/os_arch_sim.c
@@ -0,0 +1,462 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include "os/os.h"
+#include "os_priv.h"
+
+#include <hal/hal_bsp.h>
+
+#ifdef __APPLE__
+#define _XOPEN_SOURCE
+#endif
+
+#include <string.h>
+#include <stdio.h>
+#include <unistd.h>
+#include <setjmp.h>
+#include <signal.h>
+#include <sys/time.h>
+#include <assert.h>
+#include <util/util.h>
+
+struct stack_frame {
+    int sf_mainsp;              /* stack on which main() is executing */
+    sigjmp_buf sf_jb;
+    struct os_task *sf_task;
+};
+
+/*
+ * Assert that 'sf_mainsp' and 'sf_jb' are at the specific offsets where
+ * os_arch_frame_init() expects them to be.
+ */
+CTASSERT(offsetof(struct stack_frame, sf_mainsp) == 0);
+CTASSERT(offsetof(struct stack_frame, sf_jb) == 4);
+
+extern void os_arch_frame_init(struct stack_frame *sf);
+
+#define sim_setjmp(__jb) sigsetjmp(__jb, 0)
+#define sim_longjmp(__jb, __ret) siglongjmp(__jb, __ret)
+
+#define OS_USEC_PER_TICK    (1000000 / OS_TICKS_PER_SEC)
+
+static pid_t mypid;
+static sigset_t allsigs, nosigs;
+static void timer_handler(int sig);
+
+static bool suspended;      /* process is blocked in sigsuspend() */
+static sigset_t suspsigs;   /* signals delivered in sigsuspend() */
+
+/*
+ * Called from 'os_arch_frame_init()' when setjmp returns indirectly via
+ * longjmp. The return value of setjmp is passed to this function as 'rc'.
+ */
+void
+os_arch_task_start(struct stack_frame *sf, int rc)
+{
+    struct os_task *task;
+
+    /*
+     * Interrupts are disabled when a task starts executing. This happens in
+     * two different ways:
+     * - via os_arch_os_start() for the first task.
+     * - via os_sched() for all other tasks.
+     *
+     * Enable interrupts before starting the task.
+     */
+    OS_EXIT_CRITICAL(0);
+
+    task = sf->sf_task;
+    task->t_func(task->t_arg);
+
+    /* This should never return */
+    assert(0);
+}
+
+os_stack_t *
+os_arch_task_stack_init(struct os_task *t, os_stack_t *stack_top, int size)
+{
+    struct stack_frame *sf;
+
+    sf = (struct stack_frame *) ((uint8_t *) stack_top - sizeof(*sf));
+    sf->sf_task = t;
+
+    os_arch_frame_init(sf);
+
+    return ((os_stack_t *)sf);
+}
+
+void
+os_arch_ctx_sw(struct os_task *next_t)
+{
+    /*
+     * gdb will stop execution of the program on most signals (e.g. SIGUSR1)
+     * whereas it passes SIGURG to the process without any special settings.
+     */
+    kill(mypid, SIGURG);
+}
+
+static void
+ctxsw_handler(int sig)
+{
+    struct os_task *t, *next_t;
+    struct stack_frame *sf;
+    int rc;
+
+    OS_ASSERT_CRITICAL();
+
+    /*
+     * Just record that this handler was called when the process was blocked.
+     * The handler will be called after sigsuspend() returns in the correct
+     * order.
+     */
+    if (suspended) {
+        sigaddset(&suspsigs, sig);
+        return;
+    }
+
+    t = os_sched_get_current_task();
+    next_t = os_sched_next_task();
+    if (t == next_t) {
+        /*
+         * Context switch not needed - just return.
+         */
+        return;
+    }
+
+    if (t) {
+        sf = (struct stack_frame *) t->t_stackptr;
+
+        rc = sim_setjmp(sf->sf_jb);
+        if (rc != 0) {
+            OS_ASSERT_CRITICAL();
+            return;
+        }
+    }
+
+    os_sched_ctx_sw_hook(next_t);
+
+    os_sched_set_current_task(next_t);
+
+    sf = (struct stack_frame *) next_t->t_stackptr;
+    sim_longjmp(sf->sf_jb, 1);
+}
+
+/*
+ * Disable signals and enter a critical section.
+ *
+ * Returns 1 if signals were already blocked and 0 otherwise.
+ */
+os_sr_t
+os_arch_save_sr(void)
+{
+    int error;
+    sigset_t omask;
+
+    error = sigprocmask(SIG_BLOCK, &allsigs, &omask);
+    assert(error == 0);
+
+    /*
+     * If any one of the signals in 'allsigs' is present in 'omask' then
+     * we are already inside a critical section.
+     */
+    return (sigismember(&omask, SIGALRM));
+}
+
+void
+os_arch_restore_sr(os_sr_t osr)
+{
+    int error;
+
+    OS_ASSERT_CRITICAL();
+    assert(osr == 0 || osr == 1);
+
+    if (osr == 1) {
+        /* Exiting a nested critical section */
+        return;
+    }
+
+    error = sigprocmask(SIG_UNBLOCK, &allsigs, NULL);
+    assert(error == 0);
+}
+
+int
+os_arch_in_critical(void)
+{
+    int error;
+    sigset_t omask;
+
+    error = sigprocmask(SIG_SETMASK, NULL, &omask);
+    assert(error == 0);
+
+    /*
+     * If any one of the signals in 'allsigs' is present in 'omask' then
+     * we are already inside a critical section.
+     */
+    return (sigismember(&omask, SIGALRM));
+}
+
+static struct {
+    int num;
+    void (*handler)(int sig);
+} signals[] = {
+    { SIGALRM, timer_handler },
+    { SIGURG, ctxsw_handler },
+};
+
+#define NUMSIGS     (sizeof(signals)/sizeof(signals[0]))
+
+void
+os_tick_idle(os_time_t ticks)
+{
+    int i, rc, sig;
+    struct itimerval it;
+    void (*handler)(int sig);
+
+    OS_ASSERT_CRITICAL();
+
+    if (ticks > 0) {
+        /*
+         * Enter tickless regime and set the timer to fire after 'ticks'
+         * worth of time has elapsed.
+         */
+        it.it_value.tv_sec = ticks / OS_TICKS_PER_SEC;
+        it.it_value.tv_usec = (ticks % OS_TICKS_PER_SEC) * OS_USEC_PER_TICK;
+        it.it_interval.tv_sec = 0;
+        it.it_interval.tv_usec = OS_USEC_PER_TICK;
+        rc = setitimer(ITIMER_REAL, &it, NULL);
+        assert(rc == 0);
+    }
+
+    suspended = true;
+    sigemptyset(&suspsigs);
+    sigsuspend(&nosigs);        /* Wait for a signal to wake us up */
+    suspended = false;
+
+    /*
+     * Call handlers for signals delivered to the process during sigsuspend().
+     * The SIGALRM handler is called before any other handlers to ensure that
+     * OS time is always correct.
+     */
+    if (sigismember(&suspsigs, SIGALRM)) {
+        timer_handler(SIGALRM);
+    }
+    for (i = 0; i < NUMSIGS; i++) {
+        sig = signals[i].num;
+        handler = signals[i].handler;
+        if (sig != SIGALRM && sigismember(&suspsigs, sig)) {
+            handler(sig);
+        }
+    }
+
+    if (ticks > 0) {
+        /*
+         * Enable the periodic timer interrupt.
+         */
+        it.it_value.tv_sec = 0;
+        it.it_value.tv_usec = OS_USEC_PER_TICK;
+        it.it_interval.tv_sec = 0;
+        it.it_interval.tv_usec = OS_USEC_PER_TICK;
+        rc = setitimer(ITIMER_REAL, &it, NULL);
+        assert(rc == 0);
+    }
+}
+
+static void
+signals_init(void)
+{
+    int i, error;
+    struct sigaction sa;
+
+    sigemptyset(&nosigs);
+    sigemptyset(&allsigs);
+    for (i = 0; i < NUMSIGS; i++) {
+        sigaddset(&allsigs, signals[i].num);
+    }
+
+    for (i = 0; i < NUMSIGS; i++) {
+        memset(&sa, 0, sizeof sa);
+        sa.sa_handler = signals[i].handler;
+        sa.sa_mask = allsigs;
+        sa.sa_flags = SA_RESTART;
+        error = sigaction(signals[i].num, &sa, NULL);
+        assert(error == 0);
+    }
+
+    /*
+     * We use SIGALRM as a proxy for 'allsigs' to check if we are inside
+     * a critical section (for e.g. see os_arch_in_critical()). Make sure
+     * that SIGALRM is indeed present in 'allsigs'.
+     */
+    assert(sigismember(&allsigs, SIGALRM));
+}
+
+static void
+signals_cleanup(void)
+{
+    int i, error;
+    struct sigaction sa;
+
+    for (i = 0; i < NUMSIGS; i++) {
+        memset(&sa, 0, sizeof sa);
+        sa.sa_handler = SIG_DFL;
+        error = sigaction(signals[i].num, &sa, NULL);
+        assert(error == 0);
+    }
+}
+
+static void
+timer_handler(int sig)
+{
+    struct timeval time_now, time_diff;
+    int ticks;
+
+    static struct timeval time_last;
+    static int time_inited;
+
+    OS_ASSERT_CRITICAL();
+
+    /*
+     * Just record that this handler was called when the process was blocked.
+     * The handler will be called after sigsuspend() returns in the proper
+     * order.
+     */
+    if (suspended) {
+        sigaddset(&suspsigs, sig);
+        return;
+    }
+
+    if (!time_inited) {
+        gettimeofday(&time_last, NULL);
+        time_inited = 1;
+    }
+
+    gettimeofday(&time_now, NULL);
+    if (timercmp(&time_now, &time_last, <)) {
+        /*
+         * System time going backwards.
+         */
+        time_last = time_now;
+    } else {
+        timersub(&time_now, &time_last, &time_diff);
+
+        ticks = time_diff.tv_sec * OS_TICKS_PER_SEC;
+        ticks += time_diff.tv_usec / OS_USEC_PER_TICK;
+
+        /*
+         * Update 'time_last' but account for the remainder usecs that did not
+         * contribute towards whole 'ticks'.
+         */
+        time_diff.tv_sec = 0;
+        time_diff.tv_usec %= OS_USEC_PER_TICK;
+        timersub(&time_now, &time_diff, &time_last);
+
+        os_time_advance(ticks);
+    }
+}
+
+static void
+start_timer(void)
+{
+    struct itimerval it;
+    int rc;
+
+    memset(&it, 0, sizeof(it));
+    it.it_value.tv_sec = 0;
+    it.it_value.tv_usec = OS_USEC_PER_TICK;
+    it.it_interval.tv_sec = 0;
+    it.it_interval.tv_usec = OS_USEC_PER_TICK;
+
+    rc = setitimer(ITIMER_REAL, &it, NULL);
+    assert(rc == 0);
+}
+
+static void
+stop_timer(void)
+{
+    struct itimerval it;
+    int rc;
+
+    memset(&it, 0, sizeof(it));
+
+    rc = setitimer(ITIMER_REAL, &it, NULL);
+    assert(rc == 0);
+}
+
+os_error_t
+os_arch_os_init(void)
+{
+    mypid = getpid();
+    g_current_task = NULL;
+
+    STAILQ_INIT(&g_os_task_list);
+    TAILQ_INIT(&g_os_run_list);
+    TAILQ_INIT(&g_os_sleep_list);
+
+    /*
+     * Setup all interrupt handlers.
+     *
+     * This must be done early because task initialization uses critical
+     * sections which function correctly only when 'allsigs' is initialized.
+     */
+    signals_init();
+
+    os_init_idle_task();
+
+    return OS_OK;
+}
+
+os_error_t
+os_arch_os_start(void)
+{
+    struct stack_frame *sf;
+    struct os_task *t;
+    os_sr_t sr;
+
+    /*
+     * Disable interrupts before enabling any interrupt sources. Pending
+     * interrupts will be recognized when the first task starts executing.
+     */
+    OS_ENTER_CRITICAL(sr);
+    assert(sr == 0);
+
+    /* Enable the interrupt sources */
+    start_timer();
+
+    t = os_sched_next_task();
+    os_sched_set_current_task(t);
+
+    g_os_started = 1;
+
+    sf = (struct stack_frame *) t->t_stackptr;
+    sim_longjmp(sf->sf_jb, 1);
+
+    return 0;
+}
+
+/**
+ * Stops the tick timer and clears the "started" flag.  This function is only
+ * implemented for sim.
+ */
+void
+os_arch_os_stop(void)
+{
+    stop_timer();
+    signals_cleanup();
+    g_os_started = 0;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/src/arch/sim/os_arch_stack_frame.s
----------------------------------------------------------------------
diff --git a/kernel/os/src/arch/sim/os_arch_stack_frame.s b/kernel/os/src/arch/sim/os_arch_stack_frame.s
new file mode 100644
index 0000000..ecae80d
--- /dev/null
+++ b/kernel/os/src/arch/sim/os_arch_stack_frame.s
@@ -0,0 +1,101 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.
+ */
+
+#if defined MN_LINUX
+#define sigsetjmp   __sigsetjmp
+#define CNAME(x)    x
+#elif defined MN_OSX
+#define sigsetjmp   sigsetjmp
+#define CNAME(x)    _ ## x
+#else
+#error "unsupported platform"
+#endif
+
+    .text
+    .code32
+    .p2align 4, 0x90    /* align on 16-byte boundary and fill with NOPs */
+
+    .globl CNAME(os_arch_frame_init)
+    .globl _os_arch_frame_init
+    /*
+     * void os_arch_frame_init(struct stack_frame *sf)
+     */
+CNAME(os_arch_frame_init):
+    push    %ebp                    /* function prologue for backtrace */
+    mov     %esp,%ebp
+    push    %esi                    /* save %esi before using it as a tmpreg */
+
+    /*
+     * At this point we are executing on the main() stack:
+     * ----------------
+     * stack_frame ptr      0xc(%esp)
+     * ----------------
+     * return address       0x8(%esp)
+     * ----------------
+     * saved ebp            0x4(%esp)
+     * ----------------
+     * saved esi            0x0(%esp)
+     * ----------------
+     */
+    movl    0xc(%esp),%esi          /* %esi = 'sf' */
+    movl    %esp,0x0(%esi)          /* sf->mainsp = %esp */
+
+    /*
+     * Switch the stack so the stack pointer stored in 'sf->sf_jb' points
+     * to the task stack. This is slightly complicated because OS X wants
+     * the incoming stack pointer to be 16-byte aligned.
+     *
+     * ----------------
+     * sf (other fields)
+     * ----------------
+     * sf (sf_jb)           0x4(%esi)
+     * ----------------
+     * sf (sf_mainsp)       0x0(%esi)
+     * ----------------
+     * alignment padding    variable (0 to 12 bytes)
+     * ----------------
+     * savemask (0)         0x4(%esp)
+     * ----------------
+     * pointer to sf_jb     0x0(%esp)
+     * ----------------
+     */
+    movl    %esi,%esp
+    subl    $0x8,%esp               /* make room for sigsetjmp() arguments */
+    andl    $0xfffffff0,%esp        /* align %esp on 16-byte boundary */
+    leal    0x4(%esi),%eax          /* %eax = &sf->sf_jb */
+    movl    %eax,0x0(%esp)
+    movl    $0, 0x4(%esp)
+    call    CNAME(sigsetjmp)        /* sigsetjmp(sf->sf_jb, 0) */
+    test    %eax,%eax
+    jne     1f
+    movl    0x0(%esi),%esp          /* switch back to the main() stack */
+    pop     %esi
+    pop     %ebp
+    ret                             /* return to os_arch_task_stack_init() */
+1:
+    lea     2f,%ecx
+    push    %ecx                    /* retaddr */
+    push    $0                      /* frame pointer */
+    movl    %esp,%ebp               /* handcrafted prologue for backtrace */
+    push    %eax                    /* rc */
+    push    %esi                    /* sf */
+    call    CNAME(os_arch_task_start) /* os_arch_task_start(sf, rc) */
+    /* never returns */
+2:
+    nop

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/src/arch/sim/os_fault.c
----------------------------------------------------------------------
diff --git a/kernel/os/src/arch/sim/os_fault.c b/kernel/os/src/arch/sim/os_fault.c
new file mode 100644
index 0000000..15c40fe
--- /dev/null
+++ b/kernel/os/src/arch/sim/os_fault.c
@@ -0,0 +1,34 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+#include <stdio.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "os/os.h"
+#include "os_priv.h"
+
+void
+__assert_func(const char *file, int line, const char *func, const char *e)
+{
+    char msg[256];
+
+    snprintf(msg, sizeof(msg), "assert at %s:%d\n", file, line);
+    write(1, msg, strlen(msg));
+    _exit(1);
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/src/os.c
----------------------------------------------------------------------
diff --git a/kernel/os/src/os.c b/kernel/os/src/os.c
new file mode 100644
index 0000000..3089a97
--- /dev/null
+++ b/kernel/os/src/os.c
@@ -0,0 +1,191 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include "sysinit/sysinit.h"
+#include "os/os.h"
+#include "os/queue.h"
+#include "os/os_dev.h"
+#include "os_priv.h"
+
+#include "hal/hal_os_tick.h"
+#include "hal/hal_bsp.h"
+#include "hal/hal_watchdog.h"
+
+#include <assert.h>
+
+struct os_task g_idle_task;
+os_stack_t g_idle_task_stack[OS_STACK_ALIGN(OS_IDLE_STACK_SIZE)];
+
+uint32_t g_os_idle_ctr;
+/* Default zero.  Set by the architecture specific code when os is started.
+ */
+int g_os_started;
+
+#ifdef ARCH_sim
+#define MIN_IDLE_TICKS  1
+#else
+#define MIN_IDLE_TICKS  (100 * OS_TICKS_PER_SEC / 1000) /* 100 msec */
+#endif
+#define MAX_IDLE_TICKS  (600 * OS_TICKS_PER_SEC)        /* 10 minutes */
+
+
+/**
+ * Idle operating system task, runs when no other tasks are running.
+ * The idle task operates in tickless mode, which means it looks for
+ * the next time an event in the system needs to run, and then tells
+ * the architecture specific functions to sleep until that time.
+ *
+ * @param arg unused
+ */
+void
+os_idle_task(void *arg)
+{
+    os_sr_t sr;
+    os_time_t now;
+    os_time_t iticks, sticks, cticks;
+    os_time_t sanity_last;
+    os_time_t sanity_itvl_ticks;
+
+    sanity_itvl_ticks = (MYNEWT_VAL(SANITY_INTERVAL) * OS_TICKS_PER_SEC) / 1000;
+    sanity_last = 0;
+
+    hal_watchdog_tickle();
+
+    while (1) {
+        ++g_os_idle_ctr;
+
+        now = os_time_get();
+        if (OS_TIME_TICK_GT(now, sanity_last + sanity_itvl_ticks)) {
+            os_sanity_run();
+            /* Tickle the watchdog after successfully running sanity */
+            hal_watchdog_tickle();
+            sanity_last = now;
+        }
+
+        OS_ENTER_CRITICAL(sr);
+        now = os_time_get();
+        sticks = os_sched_wakeup_ticks(now);
+        cticks = os_callout_wakeup_ticks(now);
+        iticks = min(sticks, cticks);
+        /* Wakeup in time to run sanity as well from the idle context,
+         * as the idle task does not schedule itself.
+         */
+        iticks = min(iticks, ((sanity_last + sanity_itvl_ticks) - now));
+
+        if (iticks < MIN_IDLE_TICKS) {
+            iticks = 0;
+        } else if (iticks > MAX_IDLE_TICKS) {
+            iticks = MAX_IDLE_TICKS;
+        } else {
+            /* NOTHING */
+        }
+        /* Tell the architecture specific support to put the processor to sleep
+         * for 'n' ticks.
+         */
+        os_tick_idle(iticks);
+        OS_EXIT_CRITICAL(sr);
+    }
+}
+
+/**
+ * Has the operating system started.
+ *
+ * @return 1 if the operating system has started, 0 if it hasn't
+ */
+int
+os_started(void)
+{
+    return (g_os_started);
+}
+
+
+void
+os_init_idle_task(void)
+{
+    int rc;
+
+    rc = os_task_init(&g_idle_task, "idle", os_idle_task, NULL,
+            OS_IDLE_PRIO, OS_WAIT_FOREVER, g_idle_task_stack,
+            OS_STACK_ALIGN(OS_IDLE_STACK_SIZE));
+    assert(rc == 0);
+
+    /* Initialize sanity */
+    rc = os_sanity_init();
+    assert(rc == 0);
+
+    assert(MYNEWT_VAL(WATCHDOG_INTERVAL) - 200 > MYNEWT_VAL(SANITY_INTERVAL));
+
+    hal_watchdog_init(MYNEWT_VAL(WATCHDOG_INTERVAL));
+}
+
+/**
+ * Initialize the operating system, calls into the architecture specific
+ * support to initialize the operating system.
+ */
+void
+os_init(void)
+{
+    os_error_t err;
+
+    TAILQ_INIT(&g_callout_list);
+    STAILQ_INIT(&g_os_task_list);
+
+    /* Initialize device list. */
+    os_dev_reset();
+
+    err = os_arch_os_init();
+    assert(err == OS_OK);
+
+    /* Call bsp related OS initializations */
+    bsp_init();
+
+    err = (os_error_t) os_dev_initialize_all(OS_DEV_INIT_PRIMARY);
+    assert(err == OS_OK);
+
+    err = (os_error_t) os_dev_initialize_all(OS_DEV_INIT_SECONDARY);
+    assert(err == OS_OK);
+
+    /* Initialize target-specific packages. */
+    sysinit();
+}
+
+/**
+ * Start the operating system, calls into the architecture specific support
+ * to start the operating system.
+ */
+void
+os_start(void)
+{
+    os_error_t err;
+
+    err = os_dev_initialize_all(OS_DEV_INIT_KERNEL);
+    assert(err == OS_OK);
+
+    /* Enable the watchdog prior to starting the OS */
+    hal_watchdog_enable();
+
+    err = os_arch_os_start();
+    assert(err == OS_OK);
+}
+
+void
+os_pkg_init(void)
+{
+    os_msys_init();
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/src/os_callout.c
----------------------------------------------------------------------
diff --git a/kernel/os/src/os_callout.c b/kernel/os/src/os_callout.c
new file mode 100644
index 0000000..bc36a19
--- /dev/null
+++ b/kernel/os/src/os_callout.c
@@ -0,0 +1,200 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include "os/os.h"
+#include "os_priv.h"
+
+#include <assert.h>
+#include <string.h>
+
+struct os_callout_list g_callout_list;
+
+static void
+_os_callout_init(struct os_callout *c, struct os_eventq *evq, void *ev_arg)
+{
+    memset(c, 0, sizeof(*c));
+    c->c_ev.ev_type = OS_EVENT_T_TIMER;
+    c->c_ev.ev_arg = ev_arg;
+    c->c_evq = evq;
+}
+
+/**
+ * Initialize a callout.
+ *
+ * Callouts are used to schedule events in the future onto a task's event
+ * queue.  Callout timers are scheduled using the os_callout_reset()
+ * function.  When the timer expires, an event is posted to the event
+ * queue specified in os_callout_func_init().  The event argument given here
+ * is posted in the ev_arg field of that event.
+ *
+ * @param c The callout to initialize
+ * @param evq The event queue to post an OS_EVENT_T_TIMER event to
+ * @param timo_func The function to call on this callout for the host task
+ *                  used to provide multiple timer events to a task
+ *                  (this can be NULL.)
+ * @param ev_arg The argument to provide to the event when posting the
+ *               timer.
+ */
+void
+os_callout_func_init(struct os_callout_func *cf, struct os_eventq *evq,
+  os_callout_func_t timo_func, void *ev_arg)
+{
+    _os_callout_init(&cf->cf_c, evq, ev_arg);
+    cf->cf_func = timo_func;
+}
+
+/**
+ * Stop the callout from firing off, any pending events will be cleared.
+ *
+ * @param c The callout to stop
+ */
+void
+os_callout_stop(struct os_callout *c)
+{
+    os_sr_t sr;
+
+    OS_ENTER_CRITICAL(sr);
+
+    if (os_callout_queued(c)) {
+        TAILQ_REMOVE(&g_callout_list, c, c_next);
+        c->c_next.tqe_prev = NULL;
+    }
+
+    if (c->c_evq) {
+        os_eventq_remove(c->c_evq, &c->c_ev);
+    }
+
+    OS_EXIT_CRITICAL(sr);
+}
+
+/**
+ * Reset the callout to fire off in 'ticks' ticks.
+ *
+ * @param c The callout to reset
+ * @param ticks The number of ticks to wait before posting an event
+ *
+ * @return 0 on success, non-zero on failure
+ */
+int
+os_callout_reset(struct os_callout *c, int32_t ticks)
+{
+    struct os_callout *entry;
+    os_sr_t sr;
+    int rc;
+
+    if (ticks < 0) {
+        rc = OS_EINVAL;
+        goto err;
+    }
+
+    OS_ENTER_CRITICAL(sr);
+
+    os_callout_stop(c);
+
+    if (ticks == 0) {
+        ticks = 1;
+    }
+
+    c->c_ticks = os_time_get() + ticks;
+
+    entry = NULL;
+    TAILQ_FOREACH(entry, &g_callout_list, c_next) {
+        if (OS_TIME_TICK_LT(c->c_ticks, entry->c_ticks)) {
+            break;
+        }
+    }
+
+    if (entry) {
+        TAILQ_INSERT_BEFORE(entry, c, c_next);
+    } else {
+        TAILQ_INSERT_TAIL(&g_callout_list, c, c_next);
+    }
+
+    OS_EXIT_CRITICAL(sr);
+
+    return (0);
+err:
+    return (rc);
+}
+
+/**
+ * This function is called by the OS in the time tick.  It searches the list
+ * of callouts, and sees if any of them are ready to run.  If they are ready
+ * to run, it posts an event for each callout that's ready to run,
+ * to the event queue provided to os_callout_func_init().
+ */
+void
+os_callout_tick(void)
+{
+    os_sr_t sr;
+    struct os_callout *c;
+    uint32_t now;
+
+    now = os_time_get();
+
+    while (1) {
+        OS_ENTER_CRITICAL(sr);
+        c = TAILQ_FIRST(&g_callout_list);
+        if (c) {
+            if (OS_TIME_TICK_GEQ(now, c->c_ticks)) {
+                TAILQ_REMOVE(&g_callout_list, c, c_next);
+                c->c_next.tqe_prev = NULL;
+            } else {
+                c = NULL;
+            }
+        }
+        OS_EXIT_CRITICAL(sr);
+
+        if (c) {
+            os_eventq_put(c->c_evq, &c->c_ev);
+        } else {
+            break;
+        }
+    }
+}
+
+/*
+ * Returns the number of ticks to the first pending callout. If there are no
+ * pending callouts then return OS_TIMEOUT_NEVER instead.
+ *
+ * @param now The time now
+ *
+ * @return Number of ticks to first pending callout
+ */
+os_time_t
+os_callout_wakeup_ticks(os_time_t now)
+{
+    os_time_t rt;
+    struct os_callout *c;
+
+    OS_ASSERT_CRITICAL();
+
+    c = TAILQ_FIRST(&g_callout_list);
+    if (c != NULL) {
+        if (OS_TIME_TICK_GEQ(c->c_ticks, now)) {
+            rt = c->c_ticks - now;
+        } else {
+            rt = 0;     /* callout time is in the past */
+        }
+    } else {
+        rt = OS_TIMEOUT_NEVER;
+    }
+
+    return (rt);
+}


[33/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/kernel/os/test/src/sem_test.c
----------------------------------------------------------------------
diff --git a/kernel/os/test/src/sem_test.c b/kernel/os/test/src/sem_test.c
new file mode 100644
index 0000000..6b40069
--- /dev/null
+++ b/kernel/os/test/src/sem_test.c
@@ -0,0 +1,401 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+#include <stdio.h>
+#include <string.h>
+#include "testutil/testutil.h"
+#include "os/os.h"
+#include "os/os_cfg.h"
+#include "os/os_sem.h"
+#include "os_test_priv.h"
+
+#ifdef ARCH_sim
+#define SEM_TEST_STACK_SIZE     1024
+#else 
+#define SEM_TEST_STACK_SIZE     512
+#endif
+
+struct os_task task1;
+os_stack_t stack1[OS_STACK_ALIGN(SEM_TEST_STACK_SIZE)];
+
+struct os_task task2;
+os_stack_t stack2[OS_STACK_ALIGN(SEM_TEST_STACK_SIZE)];
+
+struct os_task task3;
+os_stack_t stack3[OS_STACK_ALIGN(SEM_TEST_STACK_SIZE)];
+
+struct os_task task4;
+os_stack_t stack4[OS_STACK_ALIGN(SEM_TEST_STACK_SIZE)];
+
+#define TASK1_PRIO (1) 
+#define TASK2_PRIO (2) 
+#define TASK3_PRIO (3) 
+#define TASK4_PRIO (4) 
+
+struct os_sem g_sem1;
+
+/* 
+ * TEST NUMBERS:
+ *  10: In this test we have the highest priority task getting the semaphore
+ *  then sleeping. Two lower priority tasks then wake up and attempt to get
+ *  the semaphore. They are blocked until the higher priority task releases
+ *  the semaphore, at which point the lower priority tasks should wake up in
+ *  order, get the semaphore, then release it and go back to sleep.
+ * 
+ */
+
+/**
+ * sem test disp sem
+ *  
+ * Display semaphore contents 
+ * 
+ * @param sem 
+ */
+static const char *
+sem_test_sem_to_s(const struct os_sem *sem)
+{
+    static char buf[128];
+
+    snprintf(buf, sizeof buf, "\tSemaphore: tokens=%u head=%p",
+             sem->sem_tokens, SLIST_FIRST(&sem->sem_head));
+
+    return buf;
+}
+
+static void 
+sem_test_sleep_task_handler(void *arg)
+{
+    struct os_task *t;
+
+    t = os_sched_get_current_task();
+    TEST_ASSERT(t->t_func == sem_test_sleep_task_handler);
+
+    os_time_delay(2 * OS_TICKS_PER_SEC);
+    os_test_restart();
+}
+
+static void
+sem_test_pend_release_loop(int delay, int timeout, int itvl)
+{
+    os_error_t err;
+
+    os_time_delay(delay);
+
+    while (1) {
+        err = os_sem_pend(&g_sem1, timeout);
+        TEST_ASSERT((err == OS_OK) || (err == OS_TIMEOUT));
+
+        err = os_sem_release(&g_sem1);
+        TEST_ASSERT(err == OS_OK);
+
+        os_time_delay(itvl);
+    }
+}
+
+/**
+ * sem test basic 
+ *  
+ * Basic semaphore tests
+ * 
+ * @return int 
+ */
+static void 
+sem_test_basic_handler(void *arg)
+{
+    struct os_task *t;
+    struct os_sem *sem;
+    os_error_t err;
+
+    sem = &g_sem1;
+    t = os_sched_get_current_task();
+
+    /* Test some error cases */
+    TEST_ASSERT(os_sem_init(NULL, 1)    == OS_INVALID_PARM);
+    TEST_ASSERT(os_sem_release(NULL)    == OS_INVALID_PARM);
+    TEST_ASSERT(os_sem_pend(NULL, 1)    == OS_INVALID_PARM);
+
+    /* Get the semaphore */
+    err = os_sem_pend(sem, 0);
+    TEST_ASSERT(err == 0,
+                "Did not get free semaphore immediately (err=%d)", err);
+
+    /* Check semaphore internals */
+    TEST_ASSERT(sem->sem_tokens == 0 && SLIST_EMPTY(&sem->sem_head),
+                "Semaphore internals wrong after getting semaphore\n"
+                "%s\n"
+                "Task: task=%p prio=%u", sem_test_sem_to_s(sem), t, t->t_prio);
+
+    /* Get the semaphore again; should fail */
+    err = os_sem_pend(sem, 0);
+    TEST_ASSERT(err == OS_TIMEOUT,
+                "Did not time out waiting for semaphore (err=%d)", err);
+
+    /* Check semaphore internals */
+    TEST_ASSERT(sem->sem_tokens == 0 && SLIST_EMPTY(&sem->sem_head),
+                "Semaphore internals wrong after getting semaphore\n"
+                "%s\n"
+                "Task: task=%p prio=%u\n", sem_test_sem_to_s(sem), t,
+                t->t_prio);
+
+    /* Release semaphore */
+    err = os_sem_release(sem);
+    TEST_ASSERT(err == 0,
+                "Could not release semaphore I own (err=%d)", err);
+
+    /* Check semaphore internals */
+    TEST_ASSERT(sem->sem_tokens == 1 && SLIST_EMPTY(&sem->sem_head),
+                "Semaphore internals wrong after releasing semaphore\n"
+                "%s\n"
+                "Task: task=%p prio=%u\n", sem_test_sem_to_s(sem), t,
+                t->t_prio);
+
+    /* Release it again */
+    err = os_sem_release(sem);
+    TEST_ASSERT(err == 0,
+                "Could not release semaphore again (err=%d)\n", err);
+
+    /* Check semaphore internals */
+    TEST_ASSERT(sem->sem_tokens == 2 && SLIST_EMPTY(&sem->sem_head),
+                "Semaphore internals wrong after releasing semaphore\n"
+                "%s\n"
+                "Task: task=%p prio=%u\n", sem_test_sem_to_s(sem), t,
+                t->t_prio);
+
+    os_test_restart();
+}
+
+static void 
+sem_test_1_task1_handler(void *arg)
+{
+    os_error_t err;
+    struct os_task *t;
+    int i;;
+
+    for (i = 0; i < 3; i++) {
+        t = os_sched_get_current_task();
+        TEST_ASSERT(t->t_func == sem_test_1_task1_handler);
+
+
+        err = os_sem_pend(&g_sem1, 0);
+        TEST_ASSERT(err == OS_OK);
+
+        /* Sleep to let other tasks run */
+        os_time_delay(OS_TICKS_PER_SEC / 10);
+
+        /* Release the semaphore */
+        err = os_sem_release(&g_sem1);
+        TEST_ASSERT(err == OS_OK);
+
+        /* Sleep to let other tasks run */
+        os_time_delay(OS_TICKS_PER_SEC / 10);
+    }
+
+    os_test_restart();
+}
+
+TEST_CASE(os_sem_test_basic)
+{
+    os_error_t err;
+
+    os_init();
+
+    err = os_sem_init(&g_sem1, 1);
+    TEST_ASSERT(err == OS_OK);
+
+    os_task_init(&task1, "task1", sem_test_basic_handler, NULL, TASK1_PRIO, 
+            OS_WAIT_FOREVER, stack1, OS_STACK_ALIGN(SEM_TEST_STACK_SIZE));
+
+    os_start();
+}
+
+static void 
+sem_test_1_task2_handler(void *arg) 
+{
+    sem_test_pend_release_loop(0, OS_TICKS_PER_SEC / 10, OS_TICKS_PER_SEC / 10);
+}
+
+static void 
+sem_test_1_task3_handler(void *arg) 
+{
+    sem_test_pend_release_loop(0, OS_TIMEOUT_NEVER, OS_TICKS_PER_SEC * 2);
+}
+
+TEST_CASE(os_sem_test_case_1)
+{
+    os_error_t err;
+
+    os_init();
+
+    err = os_sem_init(&g_sem1, 1);
+    TEST_ASSERT(err == OS_OK);
+
+    os_task_init(&task1, "task1", sem_test_1_task1_handler, NULL,
+                 TASK1_PRIO, OS_WAIT_FOREVER, stack1,
+                 OS_STACK_ALIGN(SEM_TEST_STACK_SIZE));
+
+    os_task_init(&task2, "task2", sem_test_1_task2_handler, NULL,
+                 TASK2_PRIO, OS_WAIT_FOREVER, stack2,
+                 OS_STACK_ALIGN(SEM_TEST_STACK_SIZE));
+
+    os_task_init(&task3, "task3", sem_test_1_task3_handler, NULL, TASK3_PRIO, 
+                 OS_WAIT_FOREVER, stack3, OS_STACK_ALIGN(SEM_TEST_STACK_SIZE));
+
+    os_start();
+}
+
+static void 
+sem_test_2_task2_handler(void *arg) 
+{
+    sem_test_pend_release_loop(0, 2000, 2000);
+}
+
+static void 
+sem_test_2_task3_handler(void *arg) 
+{
+    sem_test_pend_release_loop(0, OS_TIMEOUT_NEVER, 2000);
+}
+
+static void 
+sem_test_2_task4_handler(void *arg) 
+{
+    sem_test_pend_release_loop(0, 2000, 2000);
+}
+
+TEST_CASE(os_sem_test_case_2)
+{
+    os_error_t err;
+
+    os_init();
+
+    err = os_sem_init(&g_sem1, 1);
+    TEST_ASSERT(err == OS_OK);
+
+    os_task_init(&task1, "task1", sem_test_sleep_task_handler, NULL,
+                 TASK1_PRIO, OS_WAIT_FOREVER, stack1,
+                 OS_STACK_ALIGN(SEM_TEST_STACK_SIZE));
+
+    os_task_init(&task2, "task2", sem_test_2_task2_handler, NULL,
+                 TASK2_PRIO, OS_WAIT_FOREVER, stack2,
+                 OS_STACK_ALIGN(SEM_TEST_STACK_SIZE));
+
+    os_task_init(&task3, "task3", sem_test_2_task3_handler, NULL, TASK3_PRIO,
+            OS_WAIT_FOREVER, stack3, OS_STACK_ALIGN(SEM_TEST_STACK_SIZE));
+
+    os_task_init(&task4, "task4", sem_test_2_task4_handler, NULL, TASK4_PRIO,
+            OS_WAIT_FOREVER, stack4, OS_STACK_ALIGN(SEM_TEST_STACK_SIZE));
+
+    os_start();
+}
+
+static void 
+sem_test_3_task2_handler(void *arg) 
+{
+    sem_test_pend_release_loop(100, 2000, 2000);
+}
+
+static void 
+sem_test_3_task3_handler(void *arg) 
+{
+    sem_test_pend_release_loop(150, 2000, 2000);
+}
+
+static void 
+sem_test_3_task4_handler(void *arg) 
+{
+    sem_test_pend_release_loop(0, 2000, 2000);
+}
+
+TEST_CASE(os_sem_test_case_3)
+{
+    os_error_t err;
+
+    os_init();
+
+    err = os_sem_init(&g_sem1, 1);
+    TEST_ASSERT(err == OS_OK);
+
+    os_task_init(&task1, "task1", sem_test_sleep_task_handler, NULL,
+                 TASK1_PRIO, OS_WAIT_FOREVER, stack1,
+                 OS_STACK_ALIGN(SEM_TEST_STACK_SIZE));
+
+    os_task_init(&task2, "task2", sem_test_3_task2_handler, NULL,
+                 TASK2_PRIO, OS_WAIT_FOREVER, stack2,
+                 OS_STACK_ALIGN(SEM_TEST_STACK_SIZE));
+
+    os_task_init(&task3, "task3", sem_test_3_task3_handler, NULL, TASK3_PRIO,
+            OS_WAIT_FOREVER, stack3, OS_STACK_ALIGN(SEM_TEST_STACK_SIZE));
+
+    os_task_init(&task4, "task4", sem_test_3_task4_handler, NULL, TASK4_PRIO,
+            OS_WAIT_FOREVER, stack4, OS_STACK_ALIGN(SEM_TEST_STACK_SIZE));
+
+    os_start();
+}
+
+static void 
+sem_test_4_task2_handler(void *arg) 
+{
+    sem_test_pend_release_loop(60, 2000, 2000);
+}
+
+static void 
+sem_test_4_task3_handler(void *arg) 
+{
+    sem_test_pend_release_loop(60, 2000, 2000);
+}
+
+static void 
+sem_test_4_task4_handler(void *arg) 
+{
+    sem_test_pend_release_loop(0, 2000, 2000);
+}
+
+
+TEST_CASE(os_sem_test_case_4)
+{
+    os_error_t err;
+
+    os_init();
+
+    err = os_sem_init(&g_sem1, 1);
+    TEST_ASSERT(err == OS_OK);
+
+    os_task_init(&task1, "task1", sem_test_sleep_task_handler, NULL,
+                 TASK1_PRIO, OS_WAIT_FOREVER, stack1,
+                 OS_STACK_ALIGN(SEM_TEST_STACK_SIZE));
+
+    os_task_init(&task2, "task2", sem_test_4_task2_handler, NULL,
+                 TASK2_PRIO, OS_WAIT_FOREVER, stack2,
+                 OS_STACK_ALIGN(SEM_TEST_STACK_SIZE));
+
+    os_task_init(&task3, "task3", sem_test_4_task3_handler, NULL, TASK3_PRIO,
+                 OS_WAIT_FOREVER, stack3, OS_STACK_ALIGN(SEM_TEST_STACK_SIZE));
+
+    os_task_init(&task4, "task4", sem_test_4_task4_handler, NULL, TASK4_PRIO,
+                 OS_WAIT_FOREVER, stack4, OS_STACK_ALIGN(SEM_TEST_STACK_SIZE));
+
+    os_start();
+}
+
+TEST_SUITE(os_sem_test_suite)
+{
+    os_sem_test_basic();
+    os_sem_test_case_1();
+    os_sem_test_case_2();
+    os_sem_test_case_3();
+    os_sem_test_case_4();
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/LICENSE
----------------------------------------------------------------------
diff --git a/libc/baselibc/LICENSE b/libc/baselibc/LICENSE
new file mode 100644
index 0000000..b791574
--- /dev/null
+++ b/libc/baselibc/LICENSE
@@ -0,0 +1,133 @@
+Baselibc is based on klibc 1.5.23 and tinyprintf modules.
+None of the GPL-licensed parts of klibc are used.
+
+Baselibc is licensed under the BSD license:
+
+Copyright (c) 2012 Petteri Aimonen <jpa at blc.mail.kapsi.fi>
+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 Kustaa Nyholm or SpareTimeLabs 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 COPYRIGHT HOLDER BE LIABLE FOR ANY
+DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+The original licenses of the modules are included below:
+
+------------------ Tinyprintf license ------------------
+
+Copyright (c) 2004,2012 Kustaa Nyholm / SpareTimeLabs
+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 Kustaa Nyholm or SpareTimeLabs 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 COPYRIGHT HOLDER 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.
+
+------------------- klibc license -------------------------
+This license applies to all files in directory and its subdirectories,
+unless otherwise noted in individual files.
+
+
+Some files are derived from files derived from the include/ directory
+of the Linux kernel, and are licensed under the terms of the GNU
+General Public License, version 2, as released by the Free Software
+Foundation, Inc.; incorporated herein by reference.
+[These files are not included in the baselibc.]
+
+                                -----
+
+Some files are derived from files copyrighted by the Regents of The
+University of California, and are available under the following
+license:
+
+Note: The advertising clause in the license appearing on BSD Unix
+files was officially rescinded by the Director of the Office of
+Technology Licensing of the University of California on July 22
+1999. He states that clause 3 is "hereby deleted in its entirety."
+
+ * Copyright (c)
+ *      The Regents of the University of California.  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.
+ * 3. All advertising materials mentioning features or use of this software
+ *    must display the following acknowledgement:
+ *      This product includes software developed by the University of
+ *      California, Berkeley and its contributors.
+ * 4. Neither the name of the University 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 REGENTS 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 REGENTS 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.
+
+For all remaining files [of klibc], the following license applies:
+
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * Any copyright notice(s) and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+ * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+ * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/Makefile
----------------------------------------------------------------------
diff --git a/libc/baselibc/Makefile b/libc/baselibc/Makefile
new file mode 100644
index 0000000..88c8987
--- /dev/null
+++ b/libc/baselibc/Makefile
@@ -0,0 +1,46 @@
+# You can override the CFLAGS and C compiler externally,
+# e.g. make PLATFORM=cortex-m3
+CFLAGS += -g -Wall -Werror -I include
+
+ifeq ($(PLATFORM),cortex-m3)
+  CC      = arm-none-eabi-gcc
+  AR      = arm-none-eabi-ar
+  CFLAGS += -mcpu=cortex-m3 -mthumb
+  CFLAGS += -fno-common -Os
+  CFLAGS += -ffunction-sections -fdata-sections
+endif
+
+# With this, the makefile should work on Windows also.
+ifdef windir
+  RM = del
+endif
+
+# Just include all the source files in the build.
+CSRC = $(wildcard src/*.c)
+OBJS = $(CSRC:.c=.o)
+
+# And the files for the test suite
+TESTS_CSRC = $(wildcard tests/*_tests.c)
+TESTS_OBJS = $(TESTS_CSRC:.c=)
+
+# Some of the files uses "templates", i.e. common pieces
+# of code included from multiple files.
+CFLAGS += -Isrc/templates
+
+all: libc.a
+
+clean:
+	$(RM) $(OBJS) $(TESTS_OBJS) libc.a
+
+libc.a: $(OBJS)
+	$(RM) $@
+	$(AR) ru $@ $^
+
+run_tests: $(TESTS_OBJS)
+	$(foreach f,$^,$f)
+
+tests/%: tests/%.c tests/tests_glue.c libc.a
+	$(CC) $(CFLAGS) -o $@ $^
+
+%.o: %.c
+	$(CC) $(CFLAGS) -c -o $@ $<

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/README.md
----------------------------------------------------------------------
diff --git a/libc/baselibc/README.md b/libc/baselibc/README.md
new file mode 100644
index 0000000..f7e9e49
--- /dev/null
+++ b/libc/baselibc/README.md
@@ -0,0 +1,6 @@
+Baselibc
+========
+This is a very simple libc for embedded systems. Mainly geared for 32-bit microcontrollers in the 10-100kB memory range.
+The library compiles to less than 5kB total on Cortex-M3, and much less if some functions aren't used.
+
+The code is based on klibc and tinyprintf modules, and licensed under the BSD license.

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/include/assert.h
----------------------------------------------------------------------
diff --git a/libc/baselibc/include/assert.h b/libc/baselibc/include/assert.h
new file mode 100644
index 0000000..273058f
--- /dev/null
+++ b/libc/baselibc/include/assert.h
@@ -0,0 +1,28 @@
+/*
+ * assert.h
+ */
+
+#ifndef _ASSERT_H
+#define _ASSERT_H
+
+#ifdef NDEBUG
+
+/*
+ * NDEBUG doesn't just suppress the faulting behavior of assert(),
+ * but also all side effects of the assert() argument.  This behavior
+ * is required by the C standard, and allows the argument to reference
+ * variables that are not defined without NDEBUG.
+ */
+#define assert(x) ((void)(0))
+
+#else
+#include <stddef.h>
+
+extern void __assert_func(const char *, int, const char *, const char *)
+    __attribute((noreturn));
+
+#define assert(x) ((x) ? (void)0 : __assert_func(__FILE__, __LINE__, NULL, NULL))
+
+#endif
+
+#endif				/* _ASSERT_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/include/ctype.h
----------------------------------------------------------------------
diff --git a/libc/baselibc/include/ctype.h b/libc/baselibc/include/ctype.h
new file mode 100644
index 0000000..4670b6a
--- /dev/null
+++ b/libc/baselibc/include/ctype.h
@@ -0,0 +1,86 @@
+/*
+ * ctype.h
+ *
+ * This assumes ASCII.
+ */
+
+#ifndef _CTYPE_H
+#define _CTYPE_H
+
+#include <klibc/extern.h>
+#include <klibc/inline.h>
+
+__extern_inline int isupper(int __c)
+{
+	return __c >= 'A' && __c <= 'Z';
+}
+
+__extern_inline int islower(int __c)
+{
+	return __c >= 'a' && __c <= 'z';
+}
+
+__extern_inline int isalpha(int __c)
+{
+	return islower(__c) || isupper(__c);
+}
+
+__extern_inline int isdigit(int __c)
+{
+	return ((unsigned)__c - '0') <= 9;
+}
+
+__extern_inline int isalnum(int __c)
+{
+	return isalpha(__c) || isdigit(__c);
+}
+
+__extern_inline int isascii(int __c)
+{
+	return !(__c & ~0x7f);
+}
+
+__extern_inline int isblank(int __c)
+{
+	return (__c == '\t') || (__c == ' ');
+}
+
+__extern_inline int iscntrl(int __c)
+{
+	return __c < 0x20;
+}
+
+__extern_inline int isspace(int __c)
+{
+	return __c == ' ' || __c == '\n' || __c == '\t' || __c == '\r';
+}
+
+__extern_inline int isxdigit(int __c)
+{
+	return isdigit(__c) || (__c >= 'a' && __c <= 'f') || (__c >= 'A' && __c <= 'F');
+}
+
+__extern_inline int ispunct(int __c)
+{
+	return (__c >= '!' && __c <= '/') ||
+	    (__c >= ':' && __c <= '@') ||
+	    (__c >= '[' && __c <= '`') ||
+	    (__c >= '{' && __c <= '~');
+}
+
+__extern_inline int isprint(int __c)
+{
+	return (__c >= 0x20 && __c <= 0x7e);
+}
+
+__extern_inline int toupper(int __c)
+{
+	return islower(__c) ? (__c & ~32) : __c;
+}
+
+__extern_inline int tolower(int __c)
+{
+	return isupper(__c) ? (__c | 32) : __c;
+}
+
+#endif				/* _CTYPE_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/include/inttypes.h
----------------------------------------------------------------------
diff --git a/libc/baselibc/include/inttypes.h b/libc/baselibc/include/inttypes.h
new file mode 100644
index 0000000..e9ee426
--- /dev/null
+++ b/libc/baselibc/include/inttypes.h
@@ -0,0 +1,229 @@
+/*
+ * inttypes.h
+ */
+
+#ifndef _INTTYPES_H
+#define _INTTYPES_H
+
+#include <klibc/extern.h>
+#include <stdint.h>
+#include <stddef.h>
+
+static __inline__ intmax_t imaxabs(intmax_t __n)
+{
+	return (__n < (intmax_t) 0) ? -__n : __n;
+}
+
+__extern intmax_t strtoimax(const char *, char **, int);
+__extern uintmax_t strtoumax(const char *, char **, int);
+
+/* extensions */
+__extern intmax_t strntoimax(const char *, char **, int, size_t);
+__extern uintmax_t strntoumax(const char *, char **, int, size_t);
+
+#if !defined(__cplusplus) || defined(__STDC_FORMAT_MACROS)
+
+#define __PRI64_RANK "ll"
+#define __PRI32_RANK "l"
+
+#define PRId8	"d"
+#define PRId16	"d"
+#define PRId32	"d"
+#define PRId64	__PRI64_RANK "d"
+
+#define PRIdLEAST8	"d"
+#define PRIdLEAST16	"d"
+#define PRIdLEAST32	"d"
+#define PRIdLEAST64	__PRI64_RANK "d"
+
+#define PRIdFAST8	"d"
+#define PRIdFAST16	__PRIFAST_RANK "d"
+#define PRIdFAST32	__PRIFAST_RANK "d"
+#define PRIdFAST64	__PRI64_RANK "d"
+
+#define PRIdMAX	 __PRI64_RANK "d"
+#define PRIdPTR  __PRIPTR_RANK "d"
+
+#define PRIi8	"i"
+#define PRIi16	"i"
+#define PRIi32	"i"
+#define PRIi64	__PRI64_RANK "i"
+
+#define PRIiLEAST8	"i"
+#define PRIiLEAST16	"i"
+#define PRIiLEAST32	"i"
+#define PRIiLEAST64	__PRI64_RANK "i"
+
+#define PRIiFAST8	"i"
+#define PRIiFAST16	__PRIFAST_RANK "i"
+#define PRIiFAST32	__PRIFAST_RANK "i"
+#define PRIiFAST64	__PRI64_RANK "i"
+
+#define PRIiMAX	 __PRI64_RANK "i"
+#define PRIiPTR  __PRIPTR_RANK "i"
+
+#define PRIo8	"o"
+#define PRIo16	"o"
+#define PRIo32	"o"
+#define PRIo64	__PRI64_RANK "o"
+
+#define PRIoLEAST8	"o"
+#define PRIoLEAST16	"o"
+#define PRIoLEAST32	"o"
+#define PRIoLEAST64	__PRI64_RANK "o"
+
+#define PRIoFAST8	"o"
+#define PRIoFAST16	__PRIFAST_RANK "o"
+#define PRIoFAST32	__PRIFAST_RANK "o"
+#define PRIoFAST64	__PRI64_RANK "o"
+
+#define PRIoMAX	 __PRI64_RANK "o"
+#define PRIoPTR  __PRIPTR_RANK "o"
+
+#define PRIu8	"u"
+#define PRIu16	"u"
+#define PRIu32	"u"
+#define PRIu64	__PRI64_RANK "u"
+
+#define PRIuLEAST8	"u"
+#define PRIuLEAST16	"u"
+#define PRIuLEAST32	"u"
+#define PRIuLEAST64	__PRI64_RANK "u"
+
+#define PRIuFAST8	"u"
+#define PRIuFAST16	__PRIFAST_RANK "u"
+#define PRIuFAST32	__PRIFAST_RANK "u"
+#define PRIuFAST64	__PRI64_RANK "u"
+
+#define PRIuMAX	 __PRI64_RANK "u"
+#define PRIuPTR  __PRIPTR_RANK "u"
+
+#define PRIx8	"x"
+#define PRIx16	"x"
+#define PRIx32	__PRI32_RANK "x"
+#define PRIx64	__PRI64_RANK "x"
+
+#define PRIxLEAST8	"x"
+#define PRIxLEAST16	"x"
+#define PRIxLEAST32	"x"
+#define PRIxLEAST64	__PRI64_RANK "x"
+
+#define PRIxFAST8	"x"
+#define PRIxFAST16	__PRIFAST_RANK "x"
+#define PRIxFAST32	__PRIFAST_RANK "x"
+#define PRIxFAST64	__PRI64_RANK "x"
+
+#define PRIxMAX	 __PRI64_RANK "x"
+#define PRIxPTR  __PRIPTR_RANK "x"
+
+#define PRIX8	"X"
+#define PRIX16	"X"
+#define PRIX32	__PRI32_RANK "X"
+#define PRIX64	__PRI64_RANK "X"
+
+#define PRIXLEAST8	"X"
+#define PRIXLEAST16	"X"
+#define PRIXLEAST32	"X"
+#define PRIXLEAST64	__PRI64_RANK "X"
+
+#define PRIXFAST8	"X"
+#define PRIXFAST16	__PRIFAST_RANK "X"
+#define PRIXFAST32	__PRIFAST_RANK "X"
+#define PRIXFAST64	__PRI64_RANK "X"
+
+#define PRIXMAX	 __PRI64_RANK "X"
+#define PRIXPTR  __PRIPTR_RANK "X"
+
+#define SCNd8	"hhd"
+#define SCNd16	"hd"
+#define SCNd32	"d"
+#define SCNd64	__PRI64_RANK "d"
+
+#define SCNdLEAST8	"hhd"
+#define SCNdLEAST16	"hd"
+#define SCNdLEAST32	"d"
+#define SCNdLEAST64	__PRI64_RANK "d"
+
+#define SCNdFAST8	"hhd"
+#define SCNdFAST16	__PRIFAST_RANK "d"
+#define SCNdFAST32	__PRIFAST_RANK "d"
+#define SCNdFAST64	__PRI64_RANK "d"
+
+#define SCNdMAX	 __PRI64_RANK "d"
+#define SCNdPTR  __PRIPTR_RANK "d"
+
+#define SCNi8	"hhi"
+#define SCNi16	"hi"
+#define SCNi32	"i"
+#define SCNi64	__PRI64_RANK "i"
+
+#define SCNiLEAST8	"hhi"
+#define SCNiLEAST16	"hi"
+#define SCNiLEAST32	"i"
+#define SCNiLEAST64	__PRI64_RANK "i"
+
+#define SCNiFAST8	"hhi"
+#define SCNiFAST16	__PRIFAST_RANK "i"
+#define SCNiFAST32	__PRIFAST_RANK "i"
+#define SCNiFAST64	__PRI64_RANK "i"
+
+#define SCNiMAX	 __PRI64_RANK "i"
+#define SCNiPTR  __PRIPTR_RANK "i"
+
+#define SCNo8	"hho"
+#define SCNo16	"ho"
+#define SCNo32	"o"
+#define SCNo64	__PRI64_RANK "o"
+
+#define SCNoLEAST8	"hho"
+#define SCNoLEAST16	"ho"
+#define SCNoLEAST32	"o"
+#define SCNoLEAST64	__PRI64_RANK "o"
+
+#define SCNoFAST8	"hho"
+#define SCNoFAST16	__PRIFAST_RANK "o"
+#define SCNoFAST32	__PRIFAST_RANK "o"
+#define SCNoFAST64	__PRI64_RANK "o"
+
+#define SCNoMAX	 __PRI64_RANK "o"
+#define SCNoPTR  __PRIPTR_RANK "o"
+
+#define SCNu8	"hhu"
+#define SCNu16	"hu"
+#define SCNu32	"u"
+#define SCNu64	__PRI64_RANK "u"
+
+#define SCNuLEAST8	"hhu"
+#define SCNuLEAST16	"hu"
+#define SCNuLEAST32	"u"
+#define SCNuLEAST64	__PRI64_RANK "u"
+
+#define SCNuFAST8	"hhu"
+#define SCNuFAST16	__PRIFAST_RANK "u"
+#define SCNuFAST32	__PRIFAST_RANK "u"
+#define SCNuFAST64	__PRI64_RANK "u"
+
+#define SCNuMAX	 __PRI64_RANK "u"
+#define SCNuPTR  __PRIPTR_RANK "u"
+
+#define SCNx8	"hhx"
+#define SCNx16	"hx"
+#define SCNx32	"x"
+#define SCNx64	__PRI64_RANK "x"
+
+#define SCNxLEAST8	"hhx"
+#define SCNxLEAST16	"hx"
+#define SCNxLEAST32	"x"
+#define SCNxLEAST64	__PRI64_RANK "x"
+
+#define SCNxFAST8	"hhx"
+#define SCNxFAST16	__PRIFAST_RANK "x"
+#define SCNxFAST32	__PRIFAST_RANK "x"
+#define SCNxFAST64	__PRI64_RANK "x"
+
+#define SCNxMAX	 __PRI64_RANK "x"
+#define SCNxPTR  __PRIPTR_RANK "x"
+
+#endif
+
+#endif				/* _INTTYPES_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/include/klibc/extern.h
----------------------------------------------------------------------
diff --git a/libc/baselibc/include/klibc/extern.h b/libc/baselibc/include/klibc/extern.h
new file mode 100644
index 0000000..7d7c7b8
--- /dev/null
+++ b/libc/baselibc/include/klibc/extern.h
@@ -0,0 +1,16 @@
+/*
+ * klibc/extern.h
+ */
+
+#ifndef _KLIBC_EXTERN_H
+#define _KLIBC_EXTERN_H
+
+#ifdef __cplusplus
+#define __extern extern "C"
+#else
+#define __extern extern
+#endif
+
+#define __alias(x) __attribute__((weak, alias(x)))
+
+#endif				/* _KLIBC_EXTERN_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/include/klibc/inline.h
----------------------------------------------------------------------
diff --git a/libc/baselibc/include/klibc/inline.h b/libc/baselibc/include/klibc/inline.h
new file mode 100644
index 0000000..0e54743
--- /dev/null
+++ b/libc/baselibc/include/klibc/inline.h
@@ -0,0 +1,12 @@
+/*
+ * klibc/inline.h
+ */
+
+#ifndef _KLIBC_INLINE_H
+#define _KLIBC_INLINE_H
+
+#ifndef __extern_inline
+#define __extern_inline extern inline __attribute__((gnu_inline))
+#endif
+
+#endif				/* _KLIBC_INLINE_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/include/stdio.h
----------------------------------------------------------------------
diff --git a/libc/baselibc/include/stdio.h b/libc/baselibc/include/stdio.h
new file mode 100644
index 0000000..3f93340
--- /dev/null
+++ b/libc/baselibc/include/stdio.h
@@ -0,0 +1,124 @@
+/*
+ * stdio.h
+ */
+
+#ifndef _STDIO_H
+#define _STDIO_H
+
+#include <klibc/extern.h>
+#include <klibc/inline.h>
+#include <stdarg.h>
+#include <stddef.h>
+#include <string.h>
+
+/* The File structure is designed to be compatible with ChibiOS/RT type
+ * BaseSequentialStream.
+ */
+struct File;
+
+typedef struct File FILE;
+
+struct File_methods
+{
+    size_t (*write)(FILE* instance, const char *bp, size_t n);
+    size_t (*read)(FILE* instance, char *bp, size_t n);
+};
+
+struct File
+{
+    const struct File_methods *vmt;
+};
+
+#ifndef EOF
+# define EOF (-1)
+#endif
+
+#ifndef BUFSIZ
+# define BUFSIZ 1
+#endif
+
+/* Standard file descriptors - implement these globals yourself. */
+extern FILE* const stdin;
+extern FILE* const stdout;
+extern FILE* const stderr;
+
+/* Wrappers around stream write and read */
+__extern_inline size_t fread(void *buf, size_t size, size_t nmemb, FILE *stream)
+{
+    if (stream->vmt->read == NULL) return 0;
+    return stream->vmt->read(stream, buf, size*nmemb) / size;
+}
+
+__extern_inline size_t fwrite(const void *buf, size_t size, size_t nmemb, FILE *stream)
+{
+    if (stream->vmt->write == NULL) return 0;
+    return stream->vmt->write(stream, buf, size*nmemb) / size;
+}
+
+__extern_inline int fputs(const char *s, FILE *f)
+{
+	return fwrite(s, 1, strlen(s), f);
+}
+
+__extern_inline int puts(const char *s)
+{
+	return fwrite(s, 1, strlen(s), stdout) + fwrite("\n", 1, 1, stdout);
+}
+
+__extern_inline int fputc(int c, FILE *f)
+{
+	unsigned char ch = c;
+	return fwrite(&ch, 1, 1, f) == 1 ? ch : EOF;
+}
+
+__extern char *fgets(char *, int, FILE *);
+__extern_inline int fgetc(FILE *f)
+{
+	unsigned char ch;
+	return fread(&ch, 1, 1, f) == 1 ? ch : EOF;
+}
+
+__extern int errno;
+__extern_inline char *strerror(int errnum)
+{
+	return "error_str";
+}
+
+#define putc(c,f)  fputc((c),(f))
+#define putchar(c) fputc((c),stdout)
+#define getc(f) fgetc(f)
+#define getchar() fgetc(stdin)
+
+__extern_inline int fflush(FILE *stream)
+{
+	return 0;
+}
+
+__extern int printf(const char *, ...);
+__extern int vprintf(const char *, va_list);
+__extern int fprintf(FILE *, const char *, ...);
+__extern int vfprintf(FILE *, const char *, va_list);
+__extern int sprintf(char *, const char *, ...);
+__extern int vsprintf(char *, const char *, va_list);
+__extern int snprintf(char *, size_t n, const char *, ...);
+__extern int vsnprintf(char *, size_t n, const char *, va_list);
+__extern int asprintf(char **, const char *, ...);
+__extern int vasprintf(char **, const char *, va_list);
+
+__extern int sscanf(const char *, const char *, ...);
+__extern int vsscanf(const char *, const char *, va_list);
+
+/* Open a memory buffer for writing.
+ Note: Does not write null terminator.*/
+struct MemFile
+{
+    struct File file;
+    char *buffer;
+    size_t bytes_written;
+    size_t size;
+};
+
+FILE *fmemopen_w(struct MemFile* storage, char *buffer, size_t size);
+
+
+#endif				/* _STDIO_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/include/stdlib.h
----------------------------------------------------------------------
diff --git a/libc/baselibc/include/stdlib.h b/libc/baselibc/include/stdlib.h
new file mode 100644
index 0000000..847cda7
--- /dev/null
+++ b/libc/baselibc/include/stdlib.h
@@ -0,0 +1,101 @@
+/*
+ * stdlib.h
+ */
+
+#ifndef _STDLIB_H
+#define _STDLIB_H
+
+#include <klibc/extern.h>
+#include <klibc/inline.h>
+#include <stddef.h>
+#include <stdbool.h>
+
+__extern_inline int abs(int __n)
+{
+	return (__n < 0) ? -__n : __n;
+}
+
+__extern int atoi(const char *);
+__extern long atol(const char *);
+__extern long long atoll(const char *);
+
+__extern double atof(const char *str);
+__extern double strtod(const char *nptr, char **endptr);
+
+__extern_inline long labs(long __n)
+{
+	return (__n < 0L) ? -__n : __n;
+}
+
+__extern_inline long long llabs(long long __n)
+{
+	return (__n < 0LL) ? -__n : __n;
+}
+
+__extern void free(void *);
+__extern void *malloc(size_t);
+__extern void *calloc(size_t, size_t);
+__extern void *realloc(void *, size_t);
+
+/* Giving malloc some memory from which to allocate */
+__extern void add_malloc_block(void *, size_t);
+__extern void get_malloc_memory_status(size_t *, size_t *);
+
+/* Malloc locking
+ * Until the callbacks are set, malloc doesn't do any locking.
+ * malloc_lock() *may* timeout, in which case malloc() will return NULL.
+ */
+typedef bool (*malloc_lock_t)();
+typedef void (*malloc_unlock_t)();
+__extern void set_malloc_locking(malloc_lock_t, malloc_unlock_t);
+
+__extern long strtol(const char *, char **, int);
+__extern long long strtoll(const char *, char **, int);
+__extern unsigned long strtoul(const char *, char **, int);
+__extern unsigned long long strtoull(const char *, char **, int);
+
+typedef int (*__comparefunc_t) (const void *, const void *);
+__extern void *bsearch(const void *, const void *, size_t, size_t,
+		       __comparefunc_t);
+__extern void qsort(void *, size_t, size_t, __comparefunc_t);
+
+__extern long jrand48(unsigned short *);
+__extern long mrand48(void);
+__extern long nrand48(unsigned short *);
+__extern long lrand48(void);
+__extern unsigned short *seed48(const unsigned short *);
+__extern void srand48(long);
+
+__extern_inline char *getenv(const char *name)
+{
+	return NULL;
+}
+
+#define EXIT_SUCCESS	0
+#define EXIT_FAILURE	1
+__extern_inline void exit(int err)
+{
+	__extern void _exit(int s);
+
+	_exit(err);
+}
+
+#define RAND_MAX 0x7fffffff
+__extern_inline int rand(void)
+{
+	return (int)lrand48();
+}
+__extern_inline void srand(unsigned int __s)
+{
+	srand48(__s);
+}
+__extern_inline long random(void)
+{
+	return lrand48();
+}
+__extern_inline void srandom(unsigned int __s)
+{
+	srand48(__s);
+}
+
+#endif				/* _STDLIB_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/include/string.h
----------------------------------------------------------------------
diff --git a/libc/baselibc/include/string.h b/libc/baselibc/include/string.h
new file mode 100644
index 0000000..b3c1988
--- /dev/null
+++ b/libc/baselibc/include/string.h
@@ -0,0 +1,59 @@
+/*
+ * string.h
+ */
+
+#ifndef _STRING_H
+#define _STRING_H
+
+#include <klibc/extern.h>
+#include <stddef.h>
+
+__extern void *memccpy(void *, const void *, int, size_t);
+__extern void *memchr(const void *, int, size_t);
+__extern void *memrchr(const void *, int, size_t);
+__extern int memcmp(const void *, const void *, size_t);
+__extern void *memcpy(void *, const void *, size_t);
+__extern void *memmove(void *, const void *, size_t);
+__extern void *memset(void *, int, size_t);
+__extern void *memmem(const void *, size_t, const void *, size_t);
+__extern void memswap(void *, void *, size_t);
+__extern void bzero(void *, size_t);
+__extern int strcasecmp(const char *, const char *);
+__extern int strncasecmp(const char *, const char *, size_t);
+__extern char *strcat(char *, const char *);
+__extern char *strchr(const char *, int);
+__extern char *index(const char *, int);
+__extern char *strrchr(const char *, int);
+__extern char *rindex(const char *, int);
+__extern int strcmp(const char *, const char *);
+__extern char *strcpy(char *, const char *);
+__extern size_t strcspn(const char *, const char *);
+__extern char *strdup(const char *);
+__extern char *strndup(const char *, size_t);
+__extern size_t strlen(const char *);
+__extern size_t strnlen(const char *, size_t);
+__extern char *strncat(char *, const char *, size_t);
+__extern size_t strlcat(char *, const char *, size_t);
+__extern int strncmp(const char *, const char *, size_t);
+__extern char *strncpy(char *, const char *, size_t);
+__extern size_t strlcpy(char *, const char *, size_t);
+__extern char *strpbrk(const char *, const char *);
+__extern char *strsep(char **, const char *);
+__extern size_t strspn(const char *, const char *);
+__extern char *strstr(const char *, const char *);
+__extern char *strtok(char *, const char *);
+__extern char *strtok_r(char *, const char *, char **);
+
+/* Some dummy functions to avoid errors with C++ cstring */
+inline static int strcoll(const char *s1, const char *s2)
+{
+	return strcmp(s1, s2);
+}
+
+inline static size_t strxfrm(char *dest, const char *src, size_t n)
+{
+	strncpy(dest, src, n);
+	return strlen(src);
+}
+
+#endif				/* _STRING_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/pkg.yml
----------------------------------------------------------------------
diff --git a/libc/baselibc/pkg.yml b/libc/baselibc/pkg.yml
new file mode 100644
index 0000000..8ce7945
--- /dev/null
+++ b/libc/baselibc/pkg.yml
@@ -0,0 +1,28 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+#
+
+pkg.name: libc/baselibc
+pkg.description: Simple libc for embedded systems.
+pkg.author: "Petteri Aimonen"
+pkg.homepage: "https://github.com/PetteriAimonen/Baselibc"
+pkg.keywords:
+    - libc
+
+pkg.req_apis:
+    - console

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/asprintf.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/asprintf.c b/libc/baselibc/src/asprintf.c
new file mode 100644
index 0000000..a3f5f00
--- /dev/null
+++ b/libc/baselibc/src/asprintf.c
@@ -0,0 +1,30 @@
+/*
+ * asprintf.c
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdarg.h>
+
+int asprintf(char **bufp, const char *format, ...)
+{
+	va_list ap, ap1;
+	int rv;
+	int bytes;
+	char *p;
+
+	va_start(ap, format);
+	va_copy(ap1, ap);
+
+	bytes = vsnprintf(NULL, 0, format, ap1) + 1;
+	va_end(ap1);
+
+	*bufp = p = malloc(bytes);
+	if (!p)
+		return -1;
+
+	rv = vsnprintf(p, bytes, format, ap);
+	va_end(ap);
+
+	return rv;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/atoi.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/atoi.c b/libc/baselibc/src/atoi.c
new file mode 100644
index 0000000..a26abee
--- /dev/null
+++ b/libc/baselibc/src/atoi.c
@@ -0,0 +1,3 @@
+#define TYPE int
+#define NAME atoi
+#include "templates/atox.c.template"

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/atol.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/atol.c b/libc/baselibc/src/atol.c
new file mode 100644
index 0000000..1139c52
--- /dev/null
+++ b/libc/baselibc/src/atol.c
@@ -0,0 +1,3 @@
+#define TYPE long
+#define NAME atol
+#include "templates/atox.c.template"

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/atoll.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/atoll.c b/libc/baselibc/src/atoll.c
new file mode 100644
index 0000000..bc8a9fc
--- /dev/null
+++ b/libc/baselibc/src/atoll.c
@@ -0,0 +1,3 @@
+#define TYPE long long
+#define NAME atoll
+#include "templates/atox.c.template"

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/baselibc_test/printf_tests.c.donotcompile
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/baselibc_test/printf_tests.c.donotcompile b/libc/baselibc/src/baselibc_test/printf_tests.c.donotcompile
new file mode 100644
index 0000000..f9f380f
--- /dev/null
+++ b/libc/baselibc/src/baselibc_test/printf_tests.c.donotcompile
@@ -0,0 +1,22 @@
+#include "unittests.h"
+
+int main()
+{
+    int status = 0;
+    
+    {
+        COMMENT("Testing basic snprintf functionality");
+        char buf[20];
+        
+        snprintf(buf, sizeof(buf), "%08d", 55);
+        TEST(strcmp(buf, "00000055") == 0);
+        
+        TEST(snprintf(buf, sizeof(buf), "01234567890123456789") == 20);
+        TEST(strcmp(buf, "0123456789012345678") == 0);
+    }
+        
+    if (status != 0)
+        fprintf(stdout, "\n\nSome tests FAILED!\n");
+
+    return status;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/baselibc_test/tests_glue.c.donotcompile
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/baselibc_test/tests_glue.c.donotcompile b/libc/baselibc/src/baselibc_test/tests_glue.c.donotcompile
new file mode 100644
index 0000000..b18a689
--- /dev/null
+++ b/libc/baselibc/src/baselibc_test/tests_glue.c.donotcompile
@@ -0,0 +1,33 @@
+#include <stdio.h>
+
+#if defined(linux)
+/* Connects the baselibc stdio to normal POSIX stdio */
+size_t write(int fd, const void *buf, size_t count);
+
+static size_t stdio_write(FILE *instance, const char *bp, size_t n)
+{
+    if (instance == stdout)
+        return write(1, bp, n);
+    else
+        return write(2, bp, n);
+}
+#else
+#error No suitable write() implementation.
+#endif
+
+
+static struct File_methods stdio_methods = {
+        &stdio_write, NULL
+};
+
+static struct File _stdout = {
+        &stdio_methods
+};
+
+static struct File _stderr = {
+        &stdio_methods
+};
+
+FILE* const stdout = &_stdout;
+FILE* const stderr = &_stderr;
+

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/baselibc_test/unittests.h
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/baselibc_test/unittests.h b/libc/baselibc/src/baselibc_test/unittests.h
new file mode 100644
index 0000000..572f595
--- /dev/null
+++ b/libc/baselibc/src/baselibc_test/unittests.h
@@ -0,0 +1,36 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 H_BASELIBC_UNITTESTS_
+#define H_BASELIBC_UNITTESTS_
+
+#include <stdio.h>
+
+#define COMMENT(x) printf("\n----" x "----\n");
+#define STR(x) #x
+#define STR2(x) STR(x)
+#define TEST(x) \
+    if (!(x)) { \
+        fprintf(stderr, "\033[31;1mFAILED:\033[22;39m " __FILE__ ":" STR2(__LINE__) " " #x "\n"); \
+        status = 1; \
+    } else { \
+        printf("\033[32;1mOK:\033[22;39m " #x "\n"); \
+    }
+
+#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/bsearch.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/bsearch.c b/libc/baselibc/src/bsearch.c
new file mode 100644
index 0000000..1c8b07f
--- /dev/null
+++ b/libc/baselibc/src/bsearch.c
@@ -0,0 +1,26 @@
+/*
+ * bsearch.c
+ */
+
+#include <stdlib.h>
+
+void *bsearch(const void *key, const void *base, size_t nmemb,
+	      size_t size, int (*cmp) (const void *, const void *))
+{
+	while (nmemb) {
+		size_t mididx = nmemb / 2;
+		const void *midobj = base + mididx * size;
+		int diff = cmp(key, midobj);
+
+		if (diff == 0)
+			return (void *)midobj;
+
+		if (diff > 0) {
+			base = midobj + size;
+			nmemb -= mididx + 1;
+		} else
+			nmemb = mididx;
+	}
+
+	return NULL;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/bzero.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/bzero.c b/libc/baselibc/src/bzero.c
new file mode 100644
index 0000000..aa1c1ff
--- /dev/null
+++ b/libc/baselibc/src/bzero.c
@@ -0,0 +1,6 @@
+#include <string.h>
+
+void bzero(void *dst, size_t n)
+{
+	memset(dst, 0, n);
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/calloc.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/calloc.c b/libc/baselibc/src/calloc.c
new file mode 100644
index 0000000..3db7664
--- /dev/null
+++ b/libc/baselibc/src/calloc.c
@@ -0,0 +1,20 @@
+/*
+ * calloc.c
+ */
+
+#include <stdlib.h>
+#include <string.h>
+
+/* FIXME: This should look for multiplication overflow */
+
+void *calloc(size_t nmemb, size_t size)
+{
+	void *ptr;
+
+	size *= nmemb;
+	ptr = malloc(size);
+	if (ptr)
+		memset(ptr, 0, size);
+
+	return ptr;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/fgets.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/fgets.c b/libc/baselibc/src/fgets.c
new file mode 100644
index 0000000..4e9cf68
--- /dev/null
+++ b/libc/baselibc/src/fgets.c
@@ -0,0 +1,31 @@
+/*
+ * fgets.c
+ *
+ * This will be very slow due to the implementation of getc(),
+ * but we don't have anywhere to put characters we don't need from
+ * the input.
+ */
+
+#include <stdio.h>
+
+char *fgets(char *s, int n, FILE *f)
+{
+	int ch;
+	char *p = s;
+
+	while (n > 1) {
+		ch = getc(f);
+		if (ch == EOF) {
+			*p = '\0';
+			return NULL;
+		}
+		*p++ = ch;
+		n--;
+		if (ch == '\n')
+			break;
+	}
+	if (n)
+		*p = '\0';
+
+	return s;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/inline.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/inline.c b/libc/baselibc/src/inline.c
new file mode 100644
index 0000000..2d8d013
--- /dev/null
+++ b/libc/baselibc/src/inline.c
@@ -0,0 +1,5 @@
+// Make an externally visible symbol out of inlined functions
+#define __extern_inline
+#include <stdlib.h>
+#include <stdio.h>
+#include <ctype.h>

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/jrand48.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/jrand48.c b/libc/baselibc/src/jrand48.c
new file mode 100644
index 0000000..8e2b3ac
--- /dev/null
+++ b/libc/baselibc/src/jrand48.c
@@ -0,0 +1,24 @@
+/*
+ * jrand48.c
+ */
+
+#include <stdlib.h>
+#include <stdint.h>
+
+long jrand48(unsigned short xsubi[3])
+{
+	uint64_t x;
+
+	/* The xsubi[] array is littleendian by spec */
+	x = (uint64_t) (uint16_t) xsubi[0] +
+	    ((uint64_t) (uint16_t) xsubi[1] << 16) +
+	    ((uint64_t) (uint16_t) xsubi[2] << 32);
+
+	x = (0x5deece66dULL * x) + 0xb;
+
+	xsubi[0] = (unsigned short)(uint16_t) x;
+	xsubi[1] = (unsigned short)(uint16_t) (x >> 16);
+	xsubi[2] = (unsigned short)(uint16_t) (x >> 32);
+
+	return (long)(int32_t) (x >> 16);
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/lrand48.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/lrand48.c b/libc/baselibc/src/lrand48.c
new file mode 100644
index 0000000..a2fc87a
--- /dev/null
+++ b/libc/baselibc/src/lrand48.c
@@ -0,0 +1,13 @@
+/*
+ * lrand48.c
+ */
+
+#include <stdlib.h>
+#include <stdint.h>
+
+extern unsigned short __rand48_seed[3];	/* Common with mrand48.c, srand48.c */
+
+long lrand48(void)
+{
+	return (uint32_t) jrand48(__rand48_seed) >> 1;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/malloc.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/malloc.c b/libc/baselibc/src/malloc.c
new file mode 100644
index 0000000..3ef5089
--- /dev/null
+++ b/libc/baselibc/src/malloc.c
@@ -0,0 +1,274 @@
+/*
+ * malloc.c
+ *
+ * Very simple linked-list based malloc()/free().
+ */
+
+#include <stdbool.h>
+#include <stdlib.h>
+#include <assert.h>
+#include "malloc.h"
+
+/* Both the arena list and the free memory list are double linked
+   list with head node.  This the head node. Note that the arena list
+   is sorted in order of address. */
+static struct free_arena_header __malloc_head = {
+	{
+		ARENA_TYPE_HEAD,
+		0,
+		&__malloc_head,
+		&__malloc_head,
+	},
+	&__malloc_head,
+	&__malloc_head
+};
+
+static bool malloc_lock_nop() {return true;}
+static void malloc_unlock_nop() {}
+
+static malloc_lock_t malloc_lock = &malloc_lock_nop;
+static malloc_unlock_t malloc_unlock = &malloc_unlock_nop;
+
+static inline void mark_block_dead(struct free_arena_header *ah)
+{
+#ifdef DEBUG_MALLOC
+	ah->a.type = ARENA_TYPE_DEAD;
+#endif
+}
+
+static inline void remove_from_main_chain(struct free_arena_header *ah)
+{
+	struct free_arena_header *ap, *an;
+
+	mark_block_dead(ah);
+
+	ap = ah->a.prev;
+	an = ah->a.next;
+	ap->a.next = an;
+	an->a.prev = ap;
+}
+
+static inline void remove_from_free_chain(struct free_arena_header *ah)
+{
+	struct free_arena_header *ap, *an;
+
+	ap = ah->prev_free;
+	an = ah->next_free;
+	ap->next_free = an;
+	an->prev_free = ap;
+}
+
+static inline void remove_from_chains(struct free_arena_header *ah)
+{
+	remove_from_free_chain(ah);
+	remove_from_main_chain(ah);
+}
+
+static void *__malloc_from_block(struct free_arena_header *fp, size_t size)
+{
+	size_t fsize;
+	struct free_arena_header *nfp, *na, *fpn, *fpp;
+
+	fsize = fp->a.size;
+
+	/* We need the 2* to account for the larger requirements of a
+	   free block */
+	if (fsize >= size + 2 * sizeof(struct arena_header)) {
+		/* Bigger block than required -- split block */
+		nfp = (struct free_arena_header *)((char *)fp + size);
+		na = fp->a.next;
+
+		nfp->a.type = ARENA_TYPE_FREE;
+		nfp->a.size = fsize - size;
+		fp->a.type = ARENA_TYPE_USED;
+		fp->a.size = size;
+
+		/* Insert into all-block chain */
+		nfp->a.prev = fp;
+		nfp->a.next = na;
+		na->a.prev = nfp;
+		fp->a.next = nfp;
+
+		/* Replace current block on free chain */
+		nfp->next_free = fpn = fp->next_free;
+		nfp->prev_free = fpp = fp->prev_free;
+		fpn->prev_free = nfp;
+		fpp->next_free = nfp;
+	} else {
+		fp->a.type = ARENA_TYPE_USED; /* Allocate the whole block */
+		remove_from_free_chain(fp);
+	}
+
+	return (void *)(&fp->a + 1);
+}
+
+static struct free_arena_header *__free_block(struct free_arena_header *ah)
+{
+	struct free_arena_header *pah, *nah;
+
+	pah = ah->a.prev;
+	nah = ah->a.next;
+	if (pah->a.type == ARENA_TYPE_FREE &&
+	    (char *)pah + pah->a.size == (char *)ah) {
+		/* Coalesce into the previous block */
+		pah->a.size += ah->a.size;
+		pah->a.next = nah;
+		nah->a.prev = pah;
+		mark_block_dead(ah);
+
+		ah = pah;
+		pah = ah->a.prev;
+	} else {
+		/* Need to add this block to the free chain */
+		ah->a.type = ARENA_TYPE_FREE;
+
+		ah->next_free = __malloc_head.next_free;
+		ah->prev_free = &__malloc_head;
+		__malloc_head.next_free = ah;
+		ah->next_free->prev_free = ah;
+	}
+
+	/* In either of the previous cases, we might be able to merge
+	   with the subsequent block... */
+	if (nah->a.type == ARENA_TYPE_FREE &&
+	    (char *)ah + ah->a.size == (char *)nah) {
+		ah->a.size += nah->a.size;
+
+		/* Remove the old block from the chains */
+		remove_from_chains(nah);
+	}
+
+	/* Return the block that contains the called block */
+	return ah;
+}
+
+void *malloc(size_t size)
+{
+	struct free_arena_header *fp;
+        void *more_mem;
+        extern void *_sbrk(int incr);
+
+	if (size == 0)
+		return NULL;
+
+	/* Add the obligatory arena header, and round up */
+	size = (size + 2 * sizeof(struct arena_header) - 1) & ARENA_SIZE_MASK;
+
+        if (!malloc_lock())
+                return NULL;
+
+        void *result = NULL;
+retry_alloc:
+	for (fp = __malloc_head.next_free; fp->a.type != ARENA_TYPE_HEAD;
+	     fp = fp->next_free) {
+		if (fp->a.size >= size) {
+			/* Found fit -- allocate out of this block */
+			result = __malloc_from_block(fp, size);
+                        break;
+		}
+	}
+        if (result == NULL) {
+            more_mem = _sbrk(size);
+            if (more_mem != (void *)-1) {
+                add_malloc_block(more_mem, size);
+                goto retry_alloc;
+            }
+        }
+        malloc_unlock();
+	return result;
+}
+
+/* Call this to give malloc some memory to allocate from */
+void add_malloc_block(void *buf, size_t size)
+{
+	struct free_arena_header *fp = buf;
+	struct free_arena_header *pah;
+
+	if (size < sizeof(struct free_arena_header))
+		return; // Too small.
+
+	/* Insert the block into the management chains.  We need to set
+	   up the size and the main block list pointer, the rest of
+	   the work is logically identical to free(). */
+	fp->a.type = ARENA_TYPE_FREE;
+	fp->a.size = size;
+
+        if (!malloc_lock())
+            return;
+
+	/* We need to insert this into the main block list in the proper
+	   place -- this list is required to be sorted.  Since we most likely
+	   get memory assignments in ascending order, search backwards for
+	   the proper place. */
+	for (pah = __malloc_head.a.prev; pah->a.type != ARENA_TYPE_HEAD;
+	     pah = pah->a.prev) {
+		if (pah < fp)
+			break;
+	}
+
+	/* Now pah points to the node that should be the predecessor of
+	   the new node */
+	fp->a.next = pah->a.next;
+	fp->a.prev = pah;
+	pah->a.next = fp;
+	fp->a.next->a.prev = fp;
+
+	/* Insert into the free chain and coalesce with adjacent blocks */
+	fp = __free_block(fp);
+
+        malloc_unlock();
+}
+
+void free(void *ptr)
+{
+	struct free_arena_header *ah;
+
+	if (!ptr)
+		return;
+
+	ah = (struct free_arena_header *)
+	    ((struct arena_header *)ptr - 1);
+
+#ifdef DEBUG_MALLOC
+	assert(ah->a.type == ARENA_TYPE_USED);
+#endif
+
+        if (!malloc_lock())
+            return;
+
+	/* Merge into adjacent free blocks */
+	ah = __free_block(ah);
+        malloc_unlock();
+}
+
+void get_malloc_memory_status(size_t *free_bytes, size_t *largest_block)
+{
+    struct free_arena_header *fp;
+    *free_bytes = 0;
+    *largest_block = 0;
+
+    if (!malloc_lock())
+            return;
+
+    for (fp = __malloc_head.next_free; fp->a.type != ARENA_TYPE_HEAD; fp = fp->next_free) {
+        *free_bytes += fp->a.size;
+        if (fp->a.size >= *largest_block) {
+            *largest_block = fp->a.size;
+        }
+    }
+
+    malloc_unlock();
+}
+
+void set_malloc_locking(malloc_lock_t lock, malloc_unlock_t unlock)
+{
+    if (lock)
+        malloc_lock = lock;
+    else
+        malloc_lock = &malloc_lock_nop;
+
+    if (unlock)
+        malloc_unlock = unlock;
+    else
+        malloc_unlock = &malloc_unlock_nop;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/malloc.h
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/malloc.h b/libc/baselibc/src/malloc.h
new file mode 100644
index 0000000..2bed2a6
--- /dev/null
+++ b/libc/baselibc/src/malloc.h
@@ -0,0 +1,43 @@
+/*
+ * malloc.h
+ *
+ * Internals for the memory allocator
+ */
+
+#include <stdint.h>
+#include <stddef.h>
+
+/*
+ * This structure should be a power of two.  This becomes the
+ * alignment unit.
+ */
+struct free_arena_header;
+
+struct arena_header {
+	size_t type;
+	size_t size;
+	struct free_arena_header *next, *prev;
+};
+
+#ifdef DEBUG_MALLOC
+#define ARENA_TYPE_USED 0x64e69c70
+#define ARENA_TYPE_FREE 0x012d610a
+#define ARENA_TYPE_HEAD 0x971676b5
+#define ARENA_TYPE_DEAD 0xeeeeeeee
+#else
+#define ARENA_TYPE_USED 0
+#define ARENA_TYPE_FREE 1
+#define ARENA_TYPE_HEAD 2
+#endif
+
+#define ARENA_SIZE_MASK (~(sizeof(struct arena_header)-1))
+
+/*
+ * This structure should be no more than twice the size of the
+ * previous structure.
+ */
+struct free_arena_header {
+	struct arena_header a;
+	struct free_arena_header *next_free, *prev_free;
+};
+

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/memccpy.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/memccpy.c b/libc/baselibc/src/memccpy.c
new file mode 100644
index 0000000..83d02c9
--- /dev/null
+++ b/libc/baselibc/src/memccpy.c
@@ -0,0 +1,23 @@
+/*
+ * memccpy.c
+ *
+ * memccpy()
+ */
+
+#include <stddef.h>
+#include <string.h>
+
+void *memccpy(void *dst, const void *src, int c, size_t n)
+{
+	char *q = dst;
+	const char *p = src;
+	char ch;
+
+	while (n--) {
+		*q++ = ch = *p++;
+		if (ch == (char)c)
+			return q;
+	}
+
+	return NULL;		/* No instance of "c" found */
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/memchr.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/memchr.c b/libc/baselibc/src/memchr.c
new file mode 100644
index 0000000..f1947fb
--- /dev/null
+++ b/libc/baselibc/src/memchr.c
@@ -0,0 +1,19 @@
+/*
+ * memchr.c
+ */
+
+#include <stddef.h>
+#include <string.h>
+
+void *memchr(const void *s, int c, size_t n)
+{
+	const unsigned char *sp = s;
+
+	while (n--) {
+		if (*sp == (unsigned char)c)
+			return (void *)sp;
+		sp++;
+	}
+
+	return NULL;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/memcmp.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/memcmp.c b/libc/baselibc/src/memcmp.c
new file mode 100644
index 0000000..3ce9941
--- /dev/null
+++ b/libc/baselibc/src/memcmp.c
@@ -0,0 +1,19 @@
+/*
+ * memcmp.c
+ */
+
+#include <string.h>
+
+int memcmp(const void *s1, const void *s2, size_t n)
+{
+	const unsigned char *c1 = s1, *c2 = s2;
+	int d = 0;
+
+	while (n--) {
+		d = (int)*c1++ - (int)*c2++;
+		if (d)
+			break;
+	}
+
+	return d;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/memcpy.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/memcpy.c b/libc/baselibc/src/memcpy.c
new file mode 100644
index 0000000..5ce206d
--- /dev/null
+++ b/libc/baselibc/src/memcpy.c
@@ -0,0 +1,29 @@
+/*
+ * memcpy.c
+ */
+
+#include <string.h>
+#include <stdint.h>
+
+void *memcpy(void *dst, const void *src, size_t n)
+{
+	const char *p = src;
+	char *q = dst;
+#if defined(__i386__)
+	size_t nl = n >> 2;
+	asm volatile ("cld ; rep ; movsl ; movl %3,%0 ; rep ; movsb":"+c" (nl),
+		      "+S"(p), "+D"(q)
+		      :"r"(n & 3));
+#elif defined(__x86_64__)
+	size_t nq = n >> 3;
+	asm volatile ("cld ; rep ; movsq ; movl %3,%%ecx ; rep ; movsb":"+c"
+		      (nq), "+S"(p), "+D"(q)
+		      :"r"((uint32_t) (n & 7)));
+#else
+	while (n--) {
+		*q++ = *p++;
+	}
+#endif
+
+	return dst;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/memfile.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/memfile.c b/libc/baselibc/src/memfile.c
new file mode 100644
index 0000000..c915004
--- /dev/null
+++ b/libc/baselibc/src/memfile.c
@@ -0,0 +1,33 @@
+#include <stdio.h>
+
+size_t memfile_write(FILE *instance, const char *bp, size_t n)
+{
+    struct MemFile *f = (struct MemFile*)instance;
+    size_t i = 0;
+    
+    while (n--)
+    {
+        f->bytes_written++;
+        if (f->bytes_written <= f->size)
+        {
+            *f->buffer++ = *bp++;
+            i++;
+        }
+    }
+    
+    return i;
+}
+
+const struct File_methods MemFile_methods = {
+    &memfile_write,
+    NULL
+};
+
+FILE *fmemopen_w(struct MemFile* storage, char *buffer, size_t size)
+{
+    storage->file.vmt = &MemFile_methods;
+    storage->buffer = buffer;
+    storage->bytes_written = 0;
+    storage->size = size;
+    return (FILE*)storage;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/memmem.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/memmem.c b/libc/baselibc/src/memmem.c
new file mode 100644
index 0000000..8b5faa0
--- /dev/null
+++ b/libc/baselibc/src/memmem.c
@@ -0,0 +1,52 @@
+/*
+ * memmem.c
+ *
+ * Find a byte string inside a longer byte string
+ *
+ * This uses the "Not So Naive" algorithm, a very simple but
+ * usually effective algorithm, see:
+ *
+ * http://www-igm.univ-mlv.fr/~lecroq/string/
+ */
+
+#include <string.h>
+
+void *memmem(const void *haystack, size_t n, const void *needle, size_t m)
+{
+	const unsigned char *y = (const unsigned char *)haystack;
+	const unsigned char *x = (const unsigned char *)needle;
+
+	size_t j, k, l;
+
+	if (m > n || !m || !n)
+		return NULL;
+
+	if (1 != m) {
+		if (x[0] == x[1]) {
+			k = 2;
+			l = 1;
+		} else {
+			k = 1;
+			l = 2;
+		}
+
+		j = 0;
+		while (j <= n - m) {
+			if (x[1] != y[j + 1]) {
+				j += k;
+			} else {
+				if (!memcmp(x + 2, y + j + 2, m - 2)
+				    && x[0] == y[j])
+					return (void *)&y[j];
+				j += l;
+			}
+		}
+	} else
+		do {
+			if (*y == *x)
+				return (void *)y;
+			y++;
+		} while (--n);
+
+	return NULL;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/memmove.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/memmove.c b/libc/baselibc/src/memmove.c
new file mode 100644
index 0000000..a398cd8
--- /dev/null
+++ b/libc/baselibc/src/memmove.c
@@ -0,0 +1,36 @@
+/*
+ * memmove.c
+ */
+
+#include <string.h>
+
+void *memmove(void *dst, const void *src, size_t n)
+{
+	const char *p = src;
+	char *q = dst;
+#if defined(__i386__) || defined(__x86_64__)
+	if (q < p) {
+		asm volatile("cld; rep; movsb"
+			     : "+c" (n), "+S"(p), "+D"(q));
+	} else {
+		p += (n - 1);
+		q += (n - 1);
+		asm volatile("std; rep; movsb; cld"
+			     : "+c" (n), "+S"(p), "+D"(q));
+	}
+#else
+	if (q < p) {
+		while (n--) {
+			*q++ = *p++;
+		}
+	} else {
+		p += n;
+		q += n;
+		while (n--) {
+			*--q = *--p;
+		}
+	}
+#endif
+
+	return dst;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/memrchr.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/memrchr.c b/libc/baselibc/src/memrchr.c
new file mode 100644
index 0000000..ff6d711
--- /dev/null
+++ b/libc/baselibc/src/memrchr.c
@@ -0,0 +1,19 @@
+/*
+ * memrchr.c
+ */
+
+#include <stddef.h>
+#include <string.h>
+
+void *memrchr(const void *s, int c, size_t n)
+{
+	const unsigned char *sp = (const unsigned char *)s + n - 1;
+
+	while (n--) {
+		if (*sp == (unsigned char)c)
+			return (void *)sp;
+		sp--;
+	}
+
+	return NULL;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/memset.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/memset.c b/libc/baselibc/src/memset.c
new file mode 100644
index 0000000..aa00b5b
--- /dev/null
+++ b/libc/baselibc/src/memset.c
@@ -0,0 +1,30 @@
+/*
+ * memset.c
+ */
+
+#include <string.h>
+#include <stdint.h>
+
+void *memset(void *dst, int c, size_t n)
+{
+	char *q = dst;
+
+#if defined(__i386__)
+	size_t nl = n >> 2;
+	asm volatile ("cld ; rep ; stosl ; movl %3,%0 ; rep ; stosb"
+		      : "+c" (nl), "+D" (q)
+		      : "a" ((unsigned char)c * 0x01010101U), "r" (n & 3));
+#elif defined(__x86_64__)
+	size_t nq = n >> 3;
+	asm volatile ("cld ; rep ; stosq ; movl %3,%%ecx ; rep ; stosb"
+		      :"+c" (nq), "+D" (q)
+		      : "a" ((unsigned char)c * 0x0101010101010101U),
+			"r" ((uint32_t) n & 7));
+#else
+	while (n--) {
+		*q++ = c;
+	}
+#endif
+
+	return dst;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/memswap.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/memswap.c b/libc/baselibc/src/memswap.c
new file mode 100644
index 0000000..b32315c
--- /dev/null
+++ b/libc/baselibc/src/memswap.c
@@ -0,0 +1,24 @@
+/*
+ * memswap()
+ *
+ * Swaps the contents of two nonoverlapping memory areas.
+ * This really could be done faster...
+ */
+
+#include <string.h>
+
+void memswap(void *m1, void *m2, size_t n)
+{
+	char *p = m1;
+	char *q = m2;
+	char tmp;
+
+	while (n--) {
+		tmp = *p;
+		*p = *q;
+		*q = tmp;
+
+		p++;
+		q++;
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/mrand48.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/mrand48.c b/libc/baselibc/src/mrand48.c
new file mode 100644
index 0000000..1a2383b
--- /dev/null
+++ b/libc/baselibc/src/mrand48.c
@@ -0,0 +1,13 @@
+/*
+ * mrand48.c
+ */
+
+#include <stdlib.h>
+#include <stdint.h>
+
+extern unsigned short __rand48_seed[3];	/* Common with lrand48.c, srand48.c */
+
+long mrand48(void)
+{
+	return jrand48(__rand48_seed);
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/mynewt.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/mynewt.c b/libc/baselibc/src/mynewt.c
new file mode 100644
index 0000000..e35b39e
--- /dev/null
+++ b/libc/baselibc/src/mynewt.c
@@ -0,0 +1,47 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include <stdio.h>
+#include <console/console.h>
+
+static size_t
+stdin_read(FILE *fp, char *bp, size_t n)
+{
+    return 0;
+}
+
+static size_t
+stdout_write(FILE *fp, const char *bp, size_t n)
+{
+    console_write(bp, n);
+    return n;
+}
+
+static struct File_methods _stdin_methods = {
+    .write = stdout_write,
+    .read = stdin_read
+};
+
+static struct File _stdin = {
+    .vmt = &_stdin_methods
+};
+
+struct File *const stdin = &_stdin;
+struct File *const stdout = &_stdin;
+struct File *const stderr = &_stdin;

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/nrand48.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/nrand48.c b/libc/baselibc/src/nrand48.c
new file mode 100644
index 0000000..cb3532b
--- /dev/null
+++ b/libc/baselibc/src/nrand48.c
@@ -0,0 +1,11 @@
+/*
+ * nrand48.c
+ */
+
+#include <stdlib.h>
+#include <stdint.h>
+
+long nrand48(unsigned short xsubi[3])
+{
+	return (long)((uint32_t) jrand48(xsubi) >> 1);
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/qsort.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/qsort.c b/libc/baselibc/src/qsort.c
new file mode 100644
index 0000000..4c189fc
--- /dev/null
+++ b/libc/baselibc/src/qsort.c
@@ -0,0 +1,46 @@
+/*
+ * qsort.c
+ *
+ * This is actually combsort.  It's an O(n log n) algorithm with
+ * simplicity/small code size being its main virtue.
+ */
+
+#include <stddef.h>
+#include <stdlib.h>
+#include <string.h>
+
+static inline size_t newgap(size_t gap)
+{
+	gap = (gap * 10) / 13;
+	if (gap == 9 || gap == 10)
+		gap = 11;
+
+	if (gap < 1)
+		gap = 1;
+	return gap;
+}
+
+void qsort(void *base, size_t nmemb, size_t size,
+	   int (*compar) (const void *, const void *))
+{
+	size_t gap = nmemb;
+	size_t i, j;
+	char *p1, *p2;
+	int swapped;
+
+	if (!nmemb)
+		return;
+
+	do {
+		gap = newgap(gap);
+		swapped = 0;
+
+		for (i = 0, p1 = base; i < nmemb - gap; i++, p1 += size) {
+			j = i + gap;
+			if (compar(p1, p2 = (char *)base + j * size) > 0) {
+				memswap(p1, p2, size);
+				swapped = 1;
+			}
+		}
+	} while (gap > 1 || swapped);
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/realloc.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/realloc.c b/libc/baselibc/src/realloc.c
new file mode 100644
index 0000000..77e8acb
--- /dev/null
+++ b/libc/baselibc/src/realloc.c
@@ -0,0 +1,50 @@
+/*
+ * realloc.c
+ */
+
+#include <stdlib.h>
+#include <string.h>
+
+#include "malloc.h"
+
+/* FIXME: This is cheesy, it should be fixed later */
+
+void *realloc(void *ptr, size_t size)
+{
+	struct free_arena_header *ah;
+	void *newptr;
+	size_t oldsize;
+
+	if (!ptr)
+		return malloc(size);
+
+	if (size == 0) {
+		free(ptr);
+		return NULL;
+	}
+
+	/* Add the obligatory arena header, and round up */
+	size = (size + 2 * sizeof(struct arena_header) - 1) & ARENA_SIZE_MASK;
+
+	ah = (struct free_arena_header *)
+	    ((struct arena_header *)ptr - 1);
+
+	if (ah->a.size >= size && size >= (ah->a.size >> 2)) {
+		/* This field is a good size already. */
+		return ptr;
+	} else {
+		/* Make me a new block.  This is kind of bogus; we should
+		   be checking the following block to see if we can do an
+		   in-place adjustment... fix that later. */
+
+		oldsize = ah->a.size - sizeof(struct arena_header);
+
+		newptr = malloc(size);
+                if(newptr) {
+                    memcpy(newptr, ptr, (size < oldsize) ? size : oldsize);
+                }
+		free(ptr);
+
+		return newptr;
+	}
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/sprintf.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/sprintf.c b/libc/baselibc/src/sprintf.c
new file mode 100644
index 0000000..c6d8758
--- /dev/null
+++ b/libc/baselibc/src/sprintf.c
@@ -0,0 +1,18 @@
+/*
+ * sprintf.c
+ */
+
+#include <stdio.h>
+#include <unistd.h>
+
+int sprintf(char *buffer, const char *format, ...)
+{
+	va_list ap;
+	int rv;
+
+	va_start(ap, format);
+	rv = vsnprintf(buffer, ~(size_t) 0, format, ap);
+	va_end(ap);
+
+	return rv;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/srand48.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/srand48.c b/libc/baselibc/src/srand48.c
new file mode 100644
index 0000000..e1c9567
--- /dev/null
+++ b/libc/baselibc/src/srand48.c
@@ -0,0 +1,15 @@
+/*
+ * srand48.c
+ */
+
+#include <stdlib.h>
+#include <stdint.h>
+
+unsigned short __rand48_seed[3];	/* Common with mrand48.c, lrand48.c */
+
+void srand48(long seedval)
+{
+	__rand48_seed[0] = 0x330e;
+	__rand48_seed[1] = (unsigned short)seedval;
+	__rand48_seed[2] = (unsigned short)((uint32_t) seedval >> 16);
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/sscanf.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/sscanf.c b/libc/baselibc/src/sscanf.c
new file mode 100644
index 0000000..f53b276
--- /dev/null
+++ b/libc/baselibc/src/sscanf.c
@@ -0,0 +1,17 @@
+/*
+ * sscanf()
+ */
+
+#include <stdio.h>
+
+int sscanf(const char *str, const char *format, ...)
+{
+	va_list ap;
+	int rv;
+
+	va_start(ap, format);
+	rv = vsscanf(str, format, ap);
+	va_end(ap);
+
+	return rv;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/strcasecmp.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/strcasecmp.c b/libc/baselibc/src/strcasecmp.c
new file mode 100644
index 0000000..ee1f28b
--- /dev/null
+++ b/libc/baselibc/src/strcasecmp.c
@@ -0,0 +1,24 @@
+/*
+ * strcasecmp.c
+ */
+
+#include <string.h>
+#include <ctype.h>
+
+int strcasecmp(const char *s1, const char *s2)
+{
+	const unsigned char *c1 = (const unsigned char *)s1;
+	const unsigned char *c2 = (const unsigned char *)s2;
+	unsigned char ch;
+	int d = 0;
+
+	while (1) {
+		/* toupper() expects an unsigned char (implicitly cast to int)
+		   as input, and returns an int, which is exactly what we want. */
+		d = toupper(ch = *c1++) - toupper(*c2++);
+		if (d || !ch)
+			break;
+	}
+
+	return d;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/strcat.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/strcat.c b/libc/baselibc/src/strcat.c
new file mode 100644
index 0000000..6c5b673
--- /dev/null
+++ b/libc/baselibc/src/strcat.c
@@ -0,0 +1,11 @@
+/*
+ * strcat.c
+ */
+
+#include <string.h>
+
+char *strcat(char *dst, const char *src)
+{
+	strcpy(strchr(dst, '\0'), src);
+	return dst;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/strchr.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/strchr.c b/libc/baselibc/src/strchr.c
new file mode 100644
index 0000000..6a57313
--- /dev/null
+++ b/libc/baselibc/src/strchr.c
@@ -0,0 +1,17 @@
+/*
+ * strchr.c
+ */
+
+#include <string.h>
+
+char *strchr(const char *s, int c)
+{
+	while (*s != (char)c) {
+		if (!*s)
+			return NULL;
+		s++;
+	}
+
+	return (char *)s;
+}
+

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/strcmp.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/strcmp.c b/libc/baselibc/src/strcmp.c
new file mode 100644
index 0000000..3ab9f5a
--- /dev/null
+++ b/libc/baselibc/src/strcmp.c
@@ -0,0 +1,21 @@
+/*
+ * strcmp.c
+ */
+
+#include <string.h>
+
+int strcmp(const char *s1, const char *s2)
+{
+	const unsigned char *c1 = (const unsigned char *)s1;
+	const unsigned char *c2 = (const unsigned char *)s2;
+	unsigned char ch;
+	int d = 0;
+
+	while (1) {
+		d = (int)(ch = *c1++) - (int)*c2++;
+		if (d || !ch)
+			break;
+	}
+
+	return d;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/strcpy.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/strcpy.c b/libc/baselibc/src/strcpy.c
new file mode 100644
index 0000000..aa656cf
--- /dev/null
+++ b/libc/baselibc/src/strcpy.c
@@ -0,0 +1,20 @@
+/*
+ * strcpy.c
+ *
+ * strcpy()
+ */
+
+#include <string.h>
+
+char *strcpy(char *dst, const char *src)
+{
+	char *q = dst;
+	const char *p = src;
+	char ch;
+
+	do {
+		*q++ = ch = *p++;
+	} while (ch);
+
+	return dst;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/strcspn.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/strcspn.c b/libc/baselibc/src/strcspn.c
new file mode 100644
index 0000000..ba9e3be
--- /dev/null
+++ b/libc/baselibc/src/strcspn.c
@@ -0,0 +1,51 @@
+/*
+FUNCTION
+	<<strcspn>>---count characters not in string
+
+INDEX
+	strcspn
+
+ANSI_SYNOPSIS
+	size_t strcspn(const char *<[s1]>, const char *<[s2]>);
+
+TRAD_SYNOPSIS
+	size_t strcspn(<[s1]>, <[s2]>)
+	char *<[s1]>;
+	char *<[s2]>;
+
+DESCRIPTION
+	This function computes the length of the initial part of
+	the string pointed to by <[s1]> which consists entirely of
+	characters <[NOT]> from the string pointed to by <[s2]>
+	(excluding the terminating null character).
+
+RETURNS
+	<<strcspn>> returns the length of the substring found.
+
+PORTABILITY
+<<strcspn>> is ANSI C.
+
+<<strcspn>> requires no supporting OS subroutines.
+ */
+
+#include <string.h>
+
+size_t strcspn(const char *s1, const char *s2)
+{
+  const char *s = s1;
+  const char *c;
+
+  while (*s1)
+    {
+      for (c = s2; *c; c++)
+	{
+	  if (*s1 == *c)
+	    break;
+	}
+      if (*c)
+	break;
+      s1++;
+    }
+
+  return s1 - s;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/strdup.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/strdup.c b/libc/baselibc/src/strdup.c
new file mode 100644
index 0000000..905b51d
--- /dev/null
+++ b/libc/baselibc/src/strdup.c
@@ -0,0 +1,17 @@
+/*
+ * strdup.c
+ */
+
+#include <string.h>
+#include <stdlib.h>
+
+char *strdup(const char *s)
+{
+	int l = strlen(s) + 1;
+	char *d = malloc(l);
+
+	if (d)
+		memcpy(d, s, l);
+
+	return d;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/strlcat.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/strlcat.c b/libc/baselibc/src/strlcat.c
new file mode 100644
index 0000000..6d95087
--- /dev/null
+++ b/libc/baselibc/src/strlcat.c
@@ -0,0 +1,30 @@
+/*
+ * strlcat.c
+ */
+
+#include <string.h>
+
+size_t strlcat(char *dst, const char *src, size_t size)
+{
+	size_t bytes = 0;
+	char *q = dst;
+	const char *p = src;
+	char ch;
+
+	while (bytes < size && *q) {
+		q++;
+		bytes++;
+	}
+	if (bytes == size)
+		return (bytes + strlen(src));
+
+	while ((ch = *p++)) {
+		if (bytes + 1 < size)
+			*q++ = ch;
+
+		bytes++;
+	}
+
+	*q = '\0';
+	return bytes;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/strlcpy.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/strlcpy.c b/libc/baselibc/src/strlcpy.c
new file mode 100644
index 0000000..3ec8fd2
--- /dev/null
+++ b/libc/baselibc/src/strlcpy.c
@@ -0,0 +1,26 @@
+/*
+ * strlcpy.c
+ */
+
+#include <string.h>
+
+size_t strlcpy(char *dst, const char *src, size_t size)
+{
+	size_t bytes = 0;
+	char *q = dst;
+	const char *p = src;
+	char ch;
+
+	while ((ch = *p++)) {
+		if (bytes + 1 < size)
+			*q++ = ch;
+
+		bytes++;
+	}
+
+	/* If size == 0 there is no space for a final null... */
+	if (size)
+		*q = '\0';
+
+	return bytes;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/strlen.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/strlen.c b/libc/baselibc/src/strlen.c
new file mode 100644
index 0000000..86526a5
--- /dev/null
+++ b/libc/baselibc/src/strlen.c
@@ -0,0 +1,13 @@
+/*
+ * strlen()
+ */
+
+#include <string.h>
+
+size_t strlen(const char *s)
+{
+	const char *ss = s;
+	while (*ss)
+		ss++;
+	return ss - s;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/strncasecmp.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/strncasecmp.c b/libc/baselibc/src/strncasecmp.c
new file mode 100644
index 0000000..0551935
--- /dev/null
+++ b/libc/baselibc/src/strncasecmp.c
@@ -0,0 +1,24 @@
+/*
+ * strncasecmp.c
+ */
+
+#include <string.h>
+#include <ctype.h>
+
+int strncasecmp(const char *s1, const char *s2, size_t n)
+{
+	const unsigned char *c1 = (const unsigned char *)s1;
+	const unsigned char *c2 = (const unsigned char *)s2;
+	unsigned char ch;
+	int d = 0;
+
+	while (n--) {
+		/* toupper() expects an unsigned char (implicitly cast to int)
+		   as input, and returns an int, which is exactly what we want. */
+		d = toupper(ch = *c1++) - toupper(*c2++);
+		if (d || !ch)
+			break;
+	}
+
+	return d;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/strncat.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/strncat.c b/libc/baselibc/src/strncat.c
new file mode 100644
index 0000000..5b86216
--- /dev/null
+++ b/libc/baselibc/src/strncat.c
@@ -0,0 +1,21 @@
+/*
+ * strncat.c
+ */
+
+#include <string.h>
+
+char *strncat(char *dst, const char *src, size_t n)
+{
+	char *q = strchr(dst, '\0');
+	const char *p = src;
+	char ch;
+
+	while (n--) {
+		*q++ = ch = *p++;
+		if (!ch)
+			return dst;
+	}
+	*q = '\0';
+
+	return dst;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/strncmp.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/strncmp.c b/libc/baselibc/src/strncmp.c
new file mode 100644
index 0000000..5235545
--- /dev/null
+++ b/libc/baselibc/src/strncmp.c
@@ -0,0 +1,21 @@
+/*
+ * strncmp.c
+ */
+
+#include <string.h>
+
+int strncmp(const char *s1, const char *s2, size_t n)
+{
+	const unsigned char *c1 = (const unsigned char *)s1;
+	const unsigned char *c2 = (const unsigned char *)s2;
+	unsigned char ch;
+	int d = 0;
+
+	while (n--) {
+		d = (int)(ch = *c1++) - (int)*c2++;
+		if (d || !ch)
+			break;
+	}
+
+	return d;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/strncpy.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/strncpy.c b/libc/baselibc/src/strncpy.c
new file mode 100644
index 0000000..fffc118
--- /dev/null
+++ b/libc/baselibc/src/strncpy.c
@@ -0,0 +1,24 @@
+/*
+ * strncpy.c
+ */
+
+#include <string.h>
+
+char *strncpy(char *dst, const char *src, size_t n)
+{
+	char *q = dst;
+	const char *p = src;
+	char ch;
+
+	while (n) {
+		n--;
+		*q++ = ch = *p++;
+		if (!ch)
+			break;
+	}
+
+	/* The specs say strncpy() fills the entire buffer with NUL.  Sigh. */
+	memset(q, 0, n);
+
+	return dst;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/strndup.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/strndup.c b/libc/baselibc/src/strndup.c
new file mode 100644
index 0000000..427162f
--- /dev/null
+++ b/libc/baselibc/src/strndup.c
@@ -0,0 +1,19 @@
+/*
+ * strndup.c
+ */
+
+#include <string.h>
+#include <stdlib.h>
+
+char *strndup(const char *s, size_t n)
+{
+	int l = n > strlen(s) ? strlen(s) + 1 : n + 1;
+	char *d = malloc(l);
+
+	if (!d)
+		return NULL;
+	
+	memcpy(d, s, l);
+	d[n] = '\0';
+	return d;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/strnlen.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/strnlen.c b/libc/baselibc/src/strnlen.c
new file mode 100644
index 0000000..1678f4b
--- /dev/null
+++ b/libc/baselibc/src/strnlen.c
@@ -0,0 +1,18 @@
+/*
+ * strnlen()
+ */
+
+#include <string.h>
+
+size_t strnlen(const char *s, size_t maxlen)
+{
+	const char *ss = s;
+
+	/* Important: the maxlen test must precede the reference through ss;
+	   since the byte beyond the maximum may segfault */
+	while ((maxlen > 0) && *ss) {
+		ss++;
+		maxlen--;
+	}
+	return ss - s;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/strntoimax.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/strntoimax.c b/libc/baselibc/src/strntoimax.c
new file mode 100644
index 0000000..179d9e5
--- /dev/null
+++ b/libc/baselibc/src/strntoimax.c
@@ -0,0 +1,13 @@
+/*
+ * strntoimax.c
+ *
+ * strntoimax()
+ */
+
+#include <stddef.h>
+#include <inttypes.h>
+
+intmax_t strntoimax(const char *nptr, char **endptr, int base, size_t n)
+{
+	return (intmax_t) strntoumax(nptr, endptr, base, n);
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libc/baselibc/src/strntoumax.c
----------------------------------------------------------------------
diff --git a/libc/baselibc/src/strntoumax.c b/libc/baselibc/src/strntoumax.c
new file mode 100644
index 0000000..56dddad
--- /dev/null
+++ b/libc/baselibc/src/strntoumax.c
@@ -0,0 +1,77 @@
+/*
+ * strntoumax.c
+ *
+ * The strntoumax() function and associated
+ */
+
+#include <stddef.h>
+#include <stdint.h>
+#include <ctype.h>
+#include <inttypes.h>
+
+static inline int digitval(int ch)
+{
+	if (ch >= '0' && ch <= '9') {
+		return ch - '0';
+	} else if (ch >= 'A' && ch <= 'Z') {
+		return ch - 'A' + 10;
+	} else if (ch >= 'a' && ch <= 'z') {
+		return ch - 'a' + 10;
+	} else {
+		return -1;
+	}
+}
+
+uintmax_t strntoumax(const char *nptr, char **endptr, int base, size_t n)
+{
+	int minus = 0;
+	uintmax_t v = 0;
+	int d;
+
+	while (n && isspace((unsigned char)*nptr)) {
+		nptr++;
+		n--;
+	}
+
+	/* Single optional + or - */
+	if (n) {
+		char c = *nptr;
+		if (c == '-' || c == '+') {
+			minus = (c == '-');
+			nptr++;
+			n--;
+		}
+	}
+
+	if (base == 0) {
+		if (n >= 2 && nptr[0] == '0' &&
+		    (nptr[1] == 'x' || nptr[1] == 'X')) {
+			n -= 2;
+			nptr += 2;
+			base = 16;
+		} else if (n >= 1 && nptr[0] == '0') {
+			n--;
+			nptr++;
+			base = 8;
+		} else {
+			base = 10;
+		}
+	} else if (base == 16) {
+		if (n >= 2 && nptr[0] == '0' &&
+		    (nptr[1] == 'x' || nptr[1] == 'X')) {
+			n -= 2;
+			nptr += 2;
+		}
+	}
+
+	while (n && (d = digitval(*nptr)) >= 0 && d < base) {
+		v = v * base + d;
+		n--;
+		nptr++;
+	}
+
+	if (endptr)
+		*endptr = (char *)nptr;
+
+	return minus ? -v : v;
+}



[46/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/encoding/base64/test/src/encoding_test_priv.h
----------------------------------------------------------------------
diff --git a/encoding/base64/test/src/encoding_test_priv.h b/encoding/base64/test/src/encoding_test_priv.h
new file mode 100644
index 0000000..fc2fcac
--- /dev/null
+++ b/encoding/base64/test/src/encoding_test_priv.h
@@ -0,0 +1,25 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 __ENCODING_TEST_PRIV_
+#define __ENCODING_TEST_PRIV_
+
+int hex_fmt_test_suite(void);
+
+#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/encoding/base64/test/src/hex_test.c
----------------------------------------------------------------------
diff --git a/encoding/base64/test/src/hex_test.c b/encoding/base64/test/src/hex_test.c
new file mode 100644
index 0000000..8183425
--- /dev/null
+++ b/encoding/base64/test/src/hex_test.c
@@ -0,0 +1,125 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+#include <stdio.h>
+#include <string.h>
+
+#include "testutil/testutil.h"
+#include "util/hex.h"
+
+TEST_CASE(hex2str)
+{
+    int i;
+    char *ret;
+    char cmp_data[8];
+
+    struct {
+        char *in;
+        int inlen;
+        char *out;
+        int outlen;
+    } test_data[] = {
+        [0] = {
+            .in = "\x01",
+            .inlen = 1,
+            .out = "01",
+            .outlen = 2,
+        },
+        [1] = {
+            .in = "\xaf\xf2",
+            .inlen = 2,
+            .out = "aff2",
+            .outlen = 4,
+        }
+    };
+
+    for (i = 0; i < sizeof(test_data) / sizeof(test_data[0]); i++) {
+        ret = hex_format(test_data[i].in, test_data[i].inlen,
+          cmp_data, sizeof(cmp_data));
+        TEST_ASSERT(ret == cmp_data);
+        TEST_ASSERT(strlen(cmp_data) == test_data[i].outlen);
+        TEST_ASSERT(!strcmp(test_data[i].out, cmp_data));
+    }
+
+    /*
+     * Test not enough space. Must have space for '\0' at the end.
+     */
+    ret = hex_format("\x01\x02", 2, cmp_data, 1);
+    TEST_ASSERT(ret == NULL);
+
+    ret = hex_format("\x01\x02", 2, cmp_data, 2);
+    TEST_ASSERT(ret == NULL);
+}
+
+TEST_CASE(str2hex)
+{
+    int i;
+    char cmp_data[8];
+    int rc;
+
+    struct {
+        char *in;
+        int inlen;
+        char *out;
+        int outlen;
+    } test_data[] = {
+        [0] = {
+            .in = "01",
+            .inlen = 2,
+            .out = "\x01",
+            .outlen = 1,
+        },
+        [1] = {
+            .in = "AfF2",
+            .inlen = 4,
+            .out = "\xaf\xf2",
+            .outlen = 2,
+        }
+    };
+
+    for (i = 0; i < sizeof(test_data) / sizeof(test_data[0]); i++) {
+        rc = hex_parse(test_data[i].in, test_data[i].inlen,
+          cmp_data, sizeof(cmp_data));
+        TEST_ASSERT(rc == test_data[i].outlen);
+        TEST_ASSERT(!memcmp(test_data[i].out, cmp_data, rc));
+    }
+
+    /*
+     * Test invalid input
+     */
+    rc = hex_parse("HJ", 2, cmp_data, sizeof(cmp_data));
+    TEST_ASSERT(rc < 0);
+
+    rc = hex_parse("a", 1, cmp_data, sizeof(cmp_data));
+    TEST_ASSERT(rc < 0);
+
+    rc = hex_parse("0102", 4, cmp_data, 1);
+    TEST_ASSERT(rc < 0);
+
+    /*
+     * This should be valid.
+     */
+    rc = hex_parse("0102", 4, cmp_data, 2);
+    TEST_ASSERT(rc == 2);
+}
+
+TEST_SUITE(hex_fmt_test_suite)
+{
+    hex2str();
+    str2hex();
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/encoding/crc/include/crc/base64.h
----------------------------------------------------------------------
diff --git a/encoding/crc/include/crc/base64.h b/encoding/crc/include/crc/base64.h
new file mode 100644
index 0000000..8e0c045
--- /dev/null
+++ b/encoding/crc/include/crc/base64.h
@@ -0,0 +1,32 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 __UTIL_BASE64_H
+#define __UTIL_BASE64_H
+
+#include <stdint.h>
+#include <string.h>
+
+int base64_encode(const void *, int, char *, uint8_t);
+int base64_decode(const char *, void *buf);
+int base64_pad(char *, int);
+int base64_decode_len(const char *str);
+
+#define BASE64_ENCODE_SIZE(__size) ((((__size) * 4) / 3) + 4)
+
+#endif /* __UTIL_BASE64_H__ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/encoding/crc/include/crc/crc16.h
----------------------------------------------------------------------
diff --git a/encoding/crc/include/crc/crc16.h b/encoding/crc/include/crc/crc16.h
new file mode 100644
index 0000000..b9b965f
--- /dev/null
+++ b/encoding/crc/include/crc/crc16.h
@@ -0,0 +1,36 @@
+/*	
+ * Copyright 2001-2010 Georges Menie (www.menie.org)
+ * 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 the University of California, Berkeley 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 REGENTS 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 REGENTS AND 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.
+ */
+
+#ifndef _CRC16_H_
+#define _CRC16_H_
+
+#include <inttypes.h>
+
+#define CRC16_INITIAL_CRC       0       /* what to seed crc16 with */
+unsigned short crc16_ccitt(uint16_t initial_crc, const void *buf, int len);
+
+#endif /* _CRC16_H_ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/encoding/crc/include/crc/crc8.h
----------------------------------------------------------------------
diff --git a/encoding/crc/include/crc/crc8.h b/encoding/crc/include/crc/crc8.h
new file mode 100644
index 0000000..336acca
--- /dev/null
+++ b/encoding/crc/include/crc/crc8.h
@@ -0,0 +1,32 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.
+ */
+
+/*
+ * CRC8-CCITT, with normal polynomial; 0x07.
+ */
+
+#ifndef _UTIL_CRC8_H_
+#define _UTIL_CRC8_H_
+
+#include <inttypes.h>
+
+uint8_t crc8_init(void);
+uint8_t crc8_calc(uint8_t val, void *buf, int cnt);
+
+#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/encoding/crc/include/crc/hex.h
----------------------------------------------------------------------
diff --git a/encoding/crc/include/crc/hex.h b/encoding/crc/include/crc/hex.h
new file mode 100644
index 0000000..1e9d8c8
--- /dev/null
+++ b/encoding/crc/include/crc/hex.h
@@ -0,0 +1,25 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 _UTIL_HEX_H_
+#define _UTIL_HEX_H_
+
+char *hex_format(void *src_v, int src_len, char *dst, int dst_len);
+int hex_parse(char *src, int src_len, void *dst_v, int dst_len);
+
+#endif /* _UTIL_HEX_H_ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/encoding/crc/pkg.yml
----------------------------------------------------------------------
diff --git a/encoding/crc/pkg.yml b/encoding/crc/pkg.yml
new file mode 100644
index 0000000..49e531e
--- /dev/null
+++ b/encoding/crc/pkg.yml
@@ -0,0 +1,28 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+#
+
+pkg.name: encoding/crc
+pkg.description: Library containing encoding functions
+pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
+pkg.homepage: "http://mynewt.apache.org/"
+pkg.keywords:
+    - crc16 
+    - crc32
+    - crc8
+    - crc

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/encoding/crc/src/crc16.c
----------------------------------------------------------------------
diff --git a/encoding/crc/src/crc16.c b/encoding/crc/src/crc16.c
new file mode 100644
index 0000000..6ece419
--- /dev/null
+++ b/encoding/crc/src/crc16.c
@@ -0,0 +1,83 @@
+/*
+ * Copyright 2001-2010 Georges Menie (www.menie.org)
+ * 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 the University of California, Berkeley 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 REGENTS 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 REGENTS AND 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 <inttypes.h>
+#include "crc/crc16.h"
+
+/* CRC16 implementation acording to CCITT standards */
+
+static const uint16_t crc16tab[256]= {
+    0x0000,0x1021,0x2042,0x3063,0x4084,0x50a5,0x60c6,0x70e7,
+    0x8108,0x9129,0xa14a,0xb16b,0xc18c,0xd1ad,0xe1ce,0xf1ef,
+    0x1231,0x0210,0x3273,0x2252,0x52b5,0x4294,0x72f7,0x62d6,
+    0x9339,0x8318,0xb37b,0xa35a,0xd3bd,0xc39c,0xf3ff,0xe3de,
+    0x2462,0x3443,0x0420,0x1401,0x64e6,0x74c7,0x44a4,0x5485,
+    0xa56a,0xb54b,0x8528,0x9509,0xe5ee,0xf5cf,0xc5ac,0xd58d,
+    0x3653,0x2672,0x1611,0x0630,0x76d7,0x66f6,0x5695,0x46b4,
+    0xb75b,0xa77a,0x9719,0x8738,0xf7df,0xe7fe,0xd79d,0xc7bc,
+    0x48c4,0x58e5,0x6886,0x78a7,0x0840,0x1861,0x2802,0x3823,
+    0xc9cc,0xd9ed,0xe98e,0xf9af,0x8948,0x9969,0xa90a,0xb92b,
+    0x5af5,0x4ad4,0x7ab7,0x6a96,0x1a71,0x0a50,0x3a33,0x2a12,
+    0xdbfd,0xcbdc,0xfbbf,0xeb9e,0x9b79,0x8b58,0xbb3b,0xab1a,
+    0x6ca6,0x7c87,0x4ce4,0x5cc5,0x2c22,0x3c03,0x0c60,0x1c41,
+    0xedae,0xfd8f,0xcdec,0xddcd,0xad2a,0xbd0b,0x8d68,0x9d49,
+    0x7e97,0x6eb6,0x5ed5,0x4ef4,0x3e13,0x2e32,0x1e51,0x0e70,
+    0xff9f,0xefbe,0xdfdd,0xcffc,0xbf1b,0xaf3a,0x9f59,0x8f78,
+    0x9188,0x81a9,0xb1ca,0xa1eb,0xd10c,0xc12d,0xf14e,0xe16f,
+    0x1080,0x00a1,0x30c2,0x20e3,0x5004,0x4025,0x7046,0x6067,
+    0x83b9,0x9398,0xa3fb,0xb3da,0xc33d,0xd31c,0xe37f,0xf35e,
+    0x02b1,0x1290,0x22f3,0x32d2,0x4235,0x5214,0x6277,0x7256,
+    0xb5ea,0xa5cb,0x95a8,0x8589,0xf56e,0xe54f,0xd52c,0xc50d,
+    0x34e2,0x24c3,0x14a0,0x0481,0x7466,0x6447,0x5424,0x4405,
+    0xa7db,0xb7fa,0x8799,0x97b8,0xe75f,0xf77e,0xc71d,0xd73c,
+    0x26d3,0x36f2,0x0691,0x16b0,0x6657,0x7676,0x4615,0x5634,
+    0xd94c,0xc96d,0xf90e,0xe92f,0x99c8,0x89e9,0xb98a,0xa9ab,
+    0x5844,0x4865,0x7806,0x6827,0x18c0,0x08e1,0x3882,0x28a3,
+    0xcb7d,0xdb5c,0xeb3f,0xfb1e,0x8bf9,0x9bd8,0xabbb,0xbb9a,
+    0x4a75,0x5a54,0x6a37,0x7a16,0x0af1,0x1ad0,0x2ab3,0x3a92,
+    0xfd2e,0xed0f,0xdd6c,0xcd4d,0xbdaa,0xad8b,0x9de8,0x8dc9,
+    0x7c26,0x6c07,0x5c64,0x4c45,0x3ca2,0x2c83,0x1ce0,0x0cc1,
+    0xef1f,0xff3e,0xcf5d,0xdf7c,0xaf9b,0xbfba,0x8fd9,0x9ff8,
+    0x6e17,0x7e36,0x4e55,0x5e74,0x2e93,0x3eb2,0x0ed1,0x1ef0
+};
+
+uint16_t
+crc16_ccitt(uint16_t initial_crc, const void *buf, int len)
+{
+    const uint8_t *ptr;
+    uint16_t crc;
+    int counter;
+
+    crc = initial_crc;
+    ptr = buf;
+
+    for (counter = 0; counter < len; counter++) {
+        crc = (crc<<8) ^ crc16tab[((crc>>8) ^ *ptr++)&0x00FF];
+    }
+
+    return crc;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/encoding/crc/src/crc8.c
----------------------------------------------------------------------
diff --git a/encoding/crc/src/crc8.c b/encoding/crc/src/crc8.c
new file mode 100644
index 0000000..384acb2
--- /dev/null
+++ b/encoding/crc/src/crc8.c
@@ -0,0 +1,74 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.
+ */
+
+/*
+ * Table computation:
+ *
+ * void
+ * gen_small_table(uint8_t poly)
+ * {
+ *      int i;
+ *	int j;
+ *	uint8_t curr;
+ *
+ *	for (i = 0; i < 16; i++) {
+ *		curr = i;
+ *
+ *		for (j = 0; j < 8; j++)  {
+ *			if ((curr & 0x80) != 0) {
+ *				curr = (curr << 1) ^ poly;
+ *			} else {
+ *				curr <<= 1;
+ *			}
+ *		}
+ *
+ *		small_table[i] = curr;
+ *
+ *		printf("0x%x, ", small_table[i]);
+ *	}
+ *	printf("\n");
+ *}
+ */
+
+#include "crc/crc8.h"
+
+static uint8_t crc8_small_table[16] = {
+    0x00, 0x07, 0x0e, 0x09, 0x1c, 0x1b, 0x12, 0x15,
+    0x38, 0x3f, 0x36, 0x31, 0x24, 0x23, 0x2a, 0x2d
+};
+
+uint8_t
+crc8_init(void)
+{
+    return 0xff;
+}
+
+uint8_t
+crc8_calc(uint8_t val, void *buf, int cnt)
+{
+	int i;
+	uint8_t *p = buf;
+
+	for (i = 0; i < cnt; i++) {
+		val ^= p[i];
+		val = (val << 4) ^ crc8_small_table[val >> 4];
+		val = (val << 4) ^ crc8_small_table[val >> 4];
+	}
+	return val;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/encoding/crc/test/pkg.yml
----------------------------------------------------------------------
diff --git a/encoding/crc/test/pkg.yml b/encoding/crc/test/pkg.yml
new file mode 100644
index 0000000..dac3cb1
--- /dev/null
+++ b/encoding/crc/test/pkg.yml
@@ -0,0 +1,30 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+#
+pkg.name: crypto/encoding/test
+pkg.type: unittest
+pkg.description: "Crypto encoding unit tests."
+pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
+pkg.homepage: "http://mynewt.apache.org/"
+pkg.keywords:
+
+pkg.deps: 
+    - libs/testutil
+    - libs/util
+
+pkg.deps.SELFTEST:
+    - libs/console/stub

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/encoding/crc/test/src/encoding_test.c
----------------------------------------------------------------------
diff --git a/encoding/crc/test/src/encoding_test.c b/encoding/crc/test/src/encoding_test.c
new file mode 100644
index 0000000..b21fee8
--- /dev/null
+++ b/encoding/crc/test/src/encoding_test.c
@@ -0,0 +1,46 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include <assert.h>
+#include <stddef.h>
+#include "syscfg/syscfg.h"
+#include "testutil/testutil.h"
+#include "encoding_test_priv.h"
+
+
+int
+hex_fmt_test_all(void)
+{
+    hex_fmt_test_suite();
+    return tu_case_failed;
+}
+
+#if MYNEWT_VAL(SELFTEST)
+
+int
+main(int argc, char **argv)
+{
+    tu_config.tc_print_results = 1;
+    tu_init();
+
+    hex_fmt_test_all();
+    return tu_any_failed;
+}
+
+#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/encoding/crc/test/src/encoding_test_priv.h
----------------------------------------------------------------------
diff --git a/encoding/crc/test/src/encoding_test_priv.h b/encoding/crc/test/src/encoding_test_priv.h
new file mode 100644
index 0000000..fc2fcac
--- /dev/null
+++ b/encoding/crc/test/src/encoding_test_priv.h
@@ -0,0 +1,25 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 __ENCODING_TEST_PRIV_
+#define __ENCODING_TEST_PRIV_
+
+int hex_fmt_test_suite(void);
+
+#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/encoding/crc/test/src/hex_test.c
----------------------------------------------------------------------
diff --git a/encoding/crc/test/src/hex_test.c b/encoding/crc/test/src/hex_test.c
new file mode 100644
index 0000000..8183425
--- /dev/null
+++ b/encoding/crc/test/src/hex_test.c
@@ -0,0 +1,125 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+#include <stdio.h>
+#include <string.h>
+
+#include "testutil/testutil.h"
+#include "util/hex.h"
+
+TEST_CASE(hex2str)
+{
+    int i;
+    char *ret;
+    char cmp_data[8];
+
+    struct {
+        char *in;
+        int inlen;
+        char *out;
+        int outlen;
+    } test_data[] = {
+        [0] = {
+            .in = "\x01",
+            .inlen = 1,
+            .out = "01",
+            .outlen = 2,
+        },
+        [1] = {
+            .in = "\xaf\xf2",
+            .inlen = 2,
+            .out = "aff2",
+            .outlen = 4,
+        }
+    };
+
+    for (i = 0; i < sizeof(test_data) / sizeof(test_data[0]); i++) {
+        ret = hex_format(test_data[i].in, test_data[i].inlen,
+          cmp_data, sizeof(cmp_data));
+        TEST_ASSERT(ret == cmp_data);
+        TEST_ASSERT(strlen(cmp_data) == test_data[i].outlen);
+        TEST_ASSERT(!strcmp(test_data[i].out, cmp_data));
+    }
+
+    /*
+     * Test not enough space. Must have space for '\0' at the end.
+     */
+    ret = hex_format("\x01\x02", 2, cmp_data, 1);
+    TEST_ASSERT(ret == NULL);
+
+    ret = hex_format("\x01\x02", 2, cmp_data, 2);
+    TEST_ASSERT(ret == NULL);
+}
+
+TEST_CASE(str2hex)
+{
+    int i;
+    char cmp_data[8];
+    int rc;
+
+    struct {
+        char *in;
+        int inlen;
+        char *out;
+        int outlen;
+    } test_data[] = {
+        [0] = {
+            .in = "01",
+            .inlen = 2,
+            .out = "\x01",
+            .outlen = 1,
+        },
+        [1] = {
+            .in = "AfF2",
+            .inlen = 4,
+            .out = "\xaf\xf2",
+            .outlen = 2,
+        }
+    };
+
+    for (i = 0; i < sizeof(test_data) / sizeof(test_data[0]); i++) {
+        rc = hex_parse(test_data[i].in, test_data[i].inlen,
+          cmp_data, sizeof(cmp_data));
+        TEST_ASSERT(rc == test_data[i].outlen);
+        TEST_ASSERT(!memcmp(test_data[i].out, cmp_data, rc));
+    }
+
+    /*
+     * Test invalid input
+     */
+    rc = hex_parse("HJ", 2, cmp_data, sizeof(cmp_data));
+    TEST_ASSERT(rc < 0);
+
+    rc = hex_parse("a", 1, cmp_data, sizeof(cmp_data));
+    TEST_ASSERT(rc < 0);
+
+    rc = hex_parse("0102", 4, cmp_data, 1);
+    TEST_ASSERT(rc < 0);
+
+    /*
+     * This should be valid.
+     */
+    rc = hex_parse("0102", 4, cmp_data, 2);
+    TEST_ASSERT(rc == 2);
+}
+
+TEST_SUITE(hex_fmt_test_suite)
+{
+    hex2str();
+    str2hex();
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/encoding/json/MSJSON_COPYING
----------------------------------------------------------------------
diff --git a/encoding/json/MSJSON_COPYING b/encoding/json/MSJSON_COPYING
new file mode 100644
index 0000000..2267ff2
--- /dev/null
+++ b/encoding/json/MSJSON_COPYING
@@ -0,0 +1,28 @@
+			BSD LICENSE
+
+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 name of the GPSD project 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 REGENTS 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.

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/encoding/json/include/json/json.h
----------------------------------------------------------------------
diff --git a/encoding/json/include/json/json.h b/encoding/json/include/json/json.h
new file mode 100644
index 0000000..ecf098a
--- /dev/null
+++ b/encoding/json/include/json/json.h
@@ -0,0 +1,245 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 _JSON_H_
+#define _JSON_H_
+
+#include <stdbool.h>
+#include <stdint.h>
+#include <ctype.h>
+#include <stdio.h>
+#include <sys/types.h>
+
+
+#define JSON_VALUE_TYPE_BOOL   (0)
+#define JSON_VALUE_TYPE_UINT64 (1)
+#define JSON_VALUE_TYPE_INT64  (2)
+#define JSON_VALUE_TYPE_STRING (3)
+#define JSON_VALUE_TYPE_ARRAY  (4)
+#define JSON_VALUE_TYPE_OBJECT (5)
+
+/**
+ * For encode.  The contents of a JSON value to encode.
+ */
+struct json_value {
+    uint8_t jv_pad1;
+    uint8_t jv_type;
+    uint16_t jv_len;
+
+    union {
+        uint64_t u;
+        float fl;
+        char *str;
+        struct {
+            char **keys;
+            struct json_value **values;
+        } composite;
+    } jv_val;
+};
+
+#define JSON_VALUE_STRING(__jv, __str)        \
+    (__jv)->jv_type = JSON_VALUE_TYPE_STRING; \
+    (__jv)->jv_len = strlen(__str);           \
+    (__jv)->jv_val.str = (__str);
+
+#define JSON_VALUE_STRINGN(__jv, __str, __len) \
+    (__jv)->jv_type = JSON_VALUE_TYPE_STRING;  \
+    (__jv)->jv_len = (uint16_t) (__len);                    \
+    (__jv)->jv_val.str = (__str);
+
+#define JSON_VALUE_BOOL(__jv, __v)            \
+    (__jv)->jv_type = JSON_VALUE_TYPE_BOOL;   \
+    (__jv)->jv_val.u = (__v);
+
+#define JSON_VALUE_INT(__jv, __v)             \
+    (__jv)->jv_type = JSON_VALUE_TYPE_INT64;  \
+    (__jv)->jv_val.u = (uint64_t) __v;
+
+#define JSON_VALUE_UINT(__jv, __v)            \
+    (__jv)->jv_type = JSON_VALUE_TYPE_UINT64; \
+    (__jv)->jv_val.u = (uint64_t) __v;
+
+/* Encoding functions */
+typedef int (*json_write_func_t)(void *buf, char *data,
+        int len);
+
+struct json_encoder {
+    json_write_func_t je_write;
+    void *je_arg;
+    int je_wr_commas:1;
+    char je_encode_buf[64];
+};
+
+
+#define JSON_NITEMS(x) (int)(sizeof(x)/sizeof(x[0]))
+
+int json_encode_object_start(struct json_encoder *);
+int json_encode_object_key(struct json_encoder *encoder, char *key);
+int json_encode_object_entry(struct json_encoder *, char *,
+        struct json_value *);
+int json_encode_object_finish(struct json_encoder *);
+
+int json_encode_array_name(struct json_encoder *encoder, char *name);
+int json_encode_array_start(struct json_encoder *encoder);
+int json_encode_array_value(struct json_encoder *encoder, struct json_value *val);
+int json_encode_array_finish(struct json_encoder *encoder);
+
+/* Json parser definitions */
+typedef enum {
+    t_integer,
+    t_uinteger,
+    t_real,
+    t_string,
+    t_boolean,
+    t_character,
+    t_object,
+    t_structobject,
+    t_array,
+    t_check,
+    t_ignore
+} json_type;
+
+struct json_enum_t {
+    char *name;
+    long long int value;
+};
+
+struct json_array_t {
+    json_type element_type;
+    union {
+        struct {
+            const struct json_attr_t *subtype;
+            char *base;
+            size_t stride;
+        } objects;
+        struct {
+            char **ptrs;
+            char *store;
+            int storelen;
+        } strings;
+        struct {
+            long long int *store;
+        } integers;
+        struct {
+            long long unsigned int *store;
+        } uintegers;
+        struct {
+            double *store;
+        } reals;
+        struct {
+            bool *store;
+        } booleans;
+    } arr;
+    int *count;
+    int maxlen;
+};
+
+struct json_attr_t {
+    char *attribute;
+    json_type type;
+    union {
+        long long int *integer;
+        long long unsigned int *uinteger;
+        double *real;
+        char *string;
+        bool *boolean;
+        char *character;
+        struct json_array_t array;
+        size_t offset;
+    } addr;
+    union {
+        long long int integer;
+        long long unsigned int uinteger;
+        double real;
+        bool boolean;
+        char character;
+        char *check;
+    } dflt;
+    size_t len;
+    const struct json_enum_t *map;
+    bool nodefault;
+};
+
+struct json_buffer;
+
+/* when you implement a json buffer, you must implement these functions */
+
+/* returns the next character in the buffer or '\0'*/
+typedef char (*json_buffer_read_next_byte_t)(struct json_buffer *);
+/* returns the previous character in the buffer or '\0' */
+typedef char (*json_buffer_read_prev_byte_t)(struct json_buffer *);
+/* returns the number of characters read or zero */
+typedef int (*json_buffer_readn_t)(struct json_buffer *, char *buf, int n);
+
+struct json_buffer {
+    json_buffer_readn_t jb_readn;
+    json_buffer_read_next_byte_t jb_read_next;
+    json_buffer_read_prev_byte_t jb_read_prev;
+};
+
+#define JSON_ATTR_MAX        31        /* max chars in JSON attribute name */
+#define JSON_VAL_MAX        512        /* max chars in JSON value part */
+
+int json_read_object(struct json_buffer *, const struct json_attr_t *);
+int json_read_array(struct json_buffer *, const struct json_array_t *);
+
+#define JSON_ERR_OBSTART     1   /* non-WS when expecting object start */
+#define JSON_ERR_ATTRSTART   2   /* non-WS when expecting attrib start */
+#define JSON_ERR_BADATTR     3   /* unknown attribute name */
+#define JSON_ERR_ATTRLEN     4   /* attribute name too long */
+#define JSON_ERR_NOARRAY     5   /* saw [ when not expecting array */
+#define JSON_ERR_NOBRAK      6   /* array element specified, but no [ */
+#define JSON_ERR_STRLONG     7   /* string value too long */
+#define JSON_ERR_TOKLONG     8   /* token value too long */
+#define JSON_ERR_BADTRAIL    9   /* garbage while expecting comma or } or ] */
+#define JSON_ERR_ARRAYSTART  10  /* didn't find expected array start */
+#define JSON_ERR_OBJARR      11  /* error while parsing object array */
+#define JSON_ERR_SUBTOOLONG  12  /* too many array elements */
+#define JSON_ERR_BADSUBTRAIL 13  /* garbage while expecting array comma */
+#define JSON_ERR_SUBTYPE     14  /* unsupported array element type */
+#define JSON_ERR_BADSTRING   15  /* error while string parsing */
+#define JSON_ERR_CHECKFAIL   16  /* check attribute not matched */
+#define JSON_ERR_NOPARSTR    17  /* can't support strings in parallel arrays */
+#define JSON_ERR_BADENUM     18  /* invalid enumerated value */
+#define JSON_ERR_QNONSTRING  19  /* saw quoted value when expecting nonstring */
+#define JSON_ERR_NONQSTRING  19  /* didn't see quoted value when expecting string */
+#define JSON_ERR_MISC        20  /* other data conversion error */
+#define JSON_ERR_BADNUM      21  /* error while parsing a numerical argument */
+#define JSON_ERR_NULLPTR     22  /* unexpected null value or attribute pointer */
+
+/*
+ * Use the following macros to declare template initializers for structobject
+ * arrays.  Writing the equivalents out by hand is error-prone.
+ *
+ * JSON_STRUCT_OBJECT takes a structure name s, and a fieldname f in s.
+ *
+ * JSON_STRUCT_ARRAY takes the name of a structure array, a pointer to a an
+ * initializer defining the subobject type, and the address of an integer to
+ * store the length in.
+ */
+#define JSON_STRUCT_OBJECT(s, f)        .addr.offset = offsetof(s, f)
+#define JSON_STRUCT_ARRAY(a, e, n) \
+        .addr.array.element_type = t_structobject, \
+        .addr.array.arr.objects.subtype = e, \
+        .addr.array.arr.objects.base = (char*)a, \
+        .addr.array.arr.objects.stride = sizeof(a[0]), \
+        .addr.array.count = n, \
+        .addr.array.maxlen = (int)(sizeof(a)/sizeof(a[0]))
+
+#endif /* _JSON_H_ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/encoding/json/pkg.yml
----------------------------------------------------------------------
diff --git a/encoding/json/pkg.yml b/encoding/json/pkg.yml
new file mode 100644
index 0000000..dcf6129
--- /dev/null
+++ b/encoding/json/pkg.yml
@@ -0,0 +1,26 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+#
+
+pkg.name: encoding/json 
+pkg.description: JSON encoding / decoding library.
+pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
+pkg.homepage: "http://mynewt.apache.org/"
+pkg.keywords:
+
+pkg.cflags.float_user: -DFLOAT_SUPPORT

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/encoding/json/src/json_decode.c
----------------------------------------------------------------------
diff --git a/encoding/json/src/json_decode.c b/encoding/json/src/json_decode.c
new file mode 100644
index 0000000..b78bbfd
--- /dev/null
+++ b/encoding/json/src/json_decode.c
@@ -0,0 +1,670 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <assert.h>
+
+#include "json/json.h"
+
+/**
+ * This file is based upon microjson, from Eric S Raymond.
+ *
+ * License information for MicroJSON is in the package file MSJSON_COPYING,
+ * it is BSD licensed source code.
+ */
+
+
+/****************************************************************************
+
+NAME
+   mjson.c - parse JSON into fixed-extent data structures
+
+DESCRIPTION
+   This module parses a large subset of JSON (JavaScript Object
+Notation).  Unlike more general JSON parsers, it doesn't use malloc(3)
+and doesn't support polymorphism; you need to give it a set of
+template structures describing the expected shape of the incoming
+JSON, and it will error out if that shape is not matched.  When the
+parse succeeds, attribute values will be extracted into static
+locations specified in the template structures.
+
+   The "shape" of a JSON object in the type signature of its
+attributes (and attribute values, and so on recursively down through
+all nestings of objects and arrays).  This parser is indifferent to
+the order of attributes at any level, but you have to tell it in
+advance what the type of each attribute value will be and where the
+parsed value will be stored. The template structures may supply
+default values to be used when an expected attribute is omitted.
+
+   The preceding paragraph told one fib.  A single attribute may
+actually have a span of multiple specifications with different
+syntactically distinguishable types (e.g. string vs. real vs. integer
+vs. boolean, but not signed integer vs. unsigned integer).  The parser
+will match the right spec against the actual data.
+
+   The dialect this parses has some limitations.  First, it cannot
+recognize the JSON "null" value. Second, all elements of an array must
+be of the same type. Third, characters may not be array elements (this
+restriction could be lifted)
+
+   There are separate entry points for beginning a parse of either
+JSON object or a JSON array. JSON "float" quantities are actually
+stored as doubles.
+
+   This parser processes object arrays in one of two different ways,
+defending on whether the array subtype is declared as object or
+structobject.
+
+   Object arrays take one base address per object subfield, and are
+mapped into parallel C arrays (one per subfield).  Strings are not
+supported in this kind of array, as they don't have a "natural" size
+to use as an offset multiplier.
+
+   Structobjects arrays are a way to parse a list of objects to a set
+of modifications to a corresponding array of C structs.  The trick is
+that the array object initialization has to specify both the C struct
+array's base address and the stride length (the size of the C struct).
+If you initialize the offset fields with the correct offsetof calls,
+everything will work. Strings are supported but all string storage
+has to be inline in the struct.
+
+PERMISSIONS
+   This file is Copyright (c) 2014 by Eric S. Raymond
+   BSD terms apply: see the file COPYING in the distribution root for details.
+
+***************************************************************************/
+
+#include <string.h>
+#include <stdlib.h>
+#include <stdbool.h>
+#include <stdarg.h>
+#include <ctype.h>
+#include <math.h>        /* for HUGE_VAL */
+
+static void
+json_skip_ws(struct json_buffer *jb)
+{
+    char c;
+
+    do {
+        c = jb->jb_read_next(jb);
+    } while (isspace(c));
+
+    jb->jb_read_prev(jb);
+}
+
+static char
+json_peek(struct json_buffer *jb)
+{
+    char c;
+
+    jb->jb_read_next(jb);
+    c = jb->jb_read_prev(jb);
+
+    return c;
+}
+
+static char *
+json_target_address(const struct json_attr_t *cursor,
+        const struct json_array_t *parent, int offset)
+{
+    char *targetaddr = NULL;
+    if (parent == NULL || parent->element_type != t_structobject) {
+        /* ordinary case - use the address in the cursor structure */
+        switch (cursor->type) {
+        case t_ignore:
+            targetaddr = NULL;
+            break;
+        case t_integer:
+            targetaddr = (char *)&cursor->addr.integer[offset];
+            break;
+        case t_uinteger:
+            targetaddr = (char *)&cursor->addr.uinteger[offset];
+            break;
+        case t_real:
+            targetaddr = (char *)&cursor->addr.real[offset];
+            break;
+        case t_string:
+            targetaddr = cursor->addr.string;
+            break;
+        case t_boolean:
+            targetaddr = (char *)&cursor->addr.boolean[offset];
+            break;
+        case t_character:
+            targetaddr = (char *)&cursor->addr.character[offset];
+            break;
+        default:
+            targetaddr = NULL;
+            break;
+        }
+    } else {
+        /* tricky case - hacking a member in an array of structures */
+        targetaddr =
+            parent->arr.objects.base + (offset * parent->arr.objects.stride) +
+            cursor->addr.offset;
+    }
+    return targetaddr;
+}
+
+static int
+json_internal_read_object(struct json_buffer *jb,
+                          const struct json_attr_t *attrs,
+                          const struct json_array_t *parent,
+                          int offset)
+{
+    char c;
+    enum {
+        init, await_attr, in_attr, await_value, in_val_string,
+        in_escape, in_val_token, post_val, post_array
+    } state = 0;
+    char attrbuf[JSON_ATTR_MAX + 1], *pattr = NULL;
+    char valbuf[JSON_VAL_MAX + 1], *pval = NULL;
+    bool value_quoted = false;
+    char uescape[5];    /* enough space for 4 hex digits and '\0' */
+    const struct json_attr_t *cursor;
+    int substatus, n, maxlen = 0;
+    unsigned int u;
+    const struct json_enum_t *mp;
+    char *lptr;
+
+#ifdef S_SPLINT_S
+    /* prevents gripes about buffers not being completely defined */
+    memset(valbuf, '\0', sizeof(valbuf));
+    memset(attrbuf, '\0', sizeof(attrbuf));
+#endif /* S_SPLINT_S */
+
+    /* stuff fields with defaults in case they're omitted in the JSON input */
+    for (cursor = attrs; cursor->attribute != NULL; cursor++) {
+        if (!cursor->nodefault) {
+            lptr = json_target_address(cursor, parent, offset);
+            if (lptr != NULL) {
+                switch (cursor->type) {
+                case t_integer:
+                    memcpy(lptr, &cursor->dflt.integer, sizeof(long long int));
+                    break;
+                case t_uinteger:
+                    memcpy(lptr, &cursor->dflt.uinteger,
+                           sizeof(long long unsigned int));
+                    break;
+                case t_real:
+                    memcpy(lptr, &cursor->dflt.real, sizeof(double));
+                    break;
+                case t_string:
+                    if (parent != NULL
+                        && parent->element_type != t_structobject
+                        && offset > 0) {
+                        return JSON_ERR_NOPARSTR;
+                    }
+                    lptr[0] = '\0';
+                    break;
+                case t_boolean:
+                    memcpy(lptr, &cursor->dflt.boolean, sizeof(bool));
+                    break;
+                case t_character:
+                    lptr[0] = cursor->dflt.character;
+                    break;
+                case t_object:        /* silences a compiler warning */
+                case t_structobject:
+                case t_array:
+                case t_check:
+                case t_ignore:
+                    break;
+                }
+            }
+        }
+    }
+
+    /* parse input JSON */
+    for (c = jb->jb_read_next(jb); c != '\0'; c = jb->jb_read_next(jb)) {
+        switch (state) {
+        case init:
+            if (isspace((unsigned char) c)) {
+                continue;
+            } else if (c == '{') {
+                state = await_attr;
+            } else {
+                return JSON_ERR_OBSTART;
+            }
+            break;
+        case await_attr:
+            if (isspace((unsigned char) c)) {
+                continue;
+            } else if (c == '"') {
+                state = in_attr;
+                pattr = attrbuf;
+            } else if (c == '}') {
+                break;
+            } else {
+                return JSON_ERR_ATTRSTART;
+            }
+            break;
+        case in_attr:
+            if (pattr == NULL) {
+                /* don't update end here, leave at attribute start */
+                return JSON_ERR_NULLPTR;
+            }
+            if (c == '"') {
+                *pattr++ = '\0';
+                for (cursor = attrs; cursor->attribute != NULL; cursor++) {
+                    if (strcmp(cursor->attribute, attrbuf) == 0) {
+                        break;
+                    }
+                }
+                if (cursor->attribute == NULL) {
+                    /* don't update end here, leave at attribute start */
+                    return JSON_ERR_BADATTR;
+                }
+                state = await_value;
+                if (cursor->type == t_string) {
+                    maxlen = (int)cursor->len - 1;
+                } else if (cursor->type == t_check) {
+                    maxlen = (int)strlen(cursor->dflt.check);
+                } else if (cursor->type == t_ignore) {
+                    maxlen = JSON_VAL_MAX;
+                } else if (cursor->map != NULL) {
+                    maxlen = (int)sizeof(valbuf) - 1;
+                } else if (cursor->type == t_boolean) {
+                    maxlen = 5; /* false */
+                }
+                pval = valbuf;
+            } else if (pattr >= attrbuf + JSON_ATTR_MAX - 1) {
+                /* don't update end here, leave at attribute start */
+                return JSON_ERR_ATTRLEN;
+            } else {
+                *pattr++ = c;
+            }
+            break;
+        case await_value:
+            if (isspace((unsigned char) c) || c == ':') {
+                continue;
+            } else if (c == '[') {
+                if (cursor->type != t_array) {
+                    return JSON_ERR_NOARRAY;
+                }
+                c = jb->jb_read_prev(jb);
+                substatus = json_read_array(jb, &cursor->addr.array);
+                if (substatus != 0) {
+                    return substatus;
+                }
+                state = post_array;
+            } else if (cursor->type == t_array) {
+                return JSON_ERR_NOBRAK;
+            } else if (c == '"') {
+                value_quoted = true;
+                state = in_val_string;
+                pval = valbuf;
+            } else {
+                value_quoted = false;
+                state = in_val_token;
+                pval = valbuf;
+                *pval++ = c;
+            }
+            break;
+        case in_val_string:
+            if (pval == NULL) {
+                /* don't update end here, leave at value start */
+                return JSON_ERR_NULLPTR;
+            }
+            if (c == '\\') {
+                state = in_escape;
+            } else if (c == '"') {
+                *pval++ = '\0';
+                state = post_val;
+            } else if (pval > valbuf + JSON_VAL_MAX - 1
+                       || pval > valbuf + maxlen) {
+                /* don't update end here, leave at value start */
+                return JSON_ERR_STRLONG;        /*  */
+            } else {
+                *pval++ = c;
+            }
+            break;
+        case in_escape:
+            if (pval == NULL) {
+                /* don't update end here, leave at value start */
+                return JSON_ERR_NULLPTR;
+            }
+            switch (c) {
+            case 'b':
+                *pval++ = '\b';
+                break;
+            case 'f':
+                *pval++ = '\f';
+                break;
+            case 'n':
+                *pval++ = '\n';
+                break;
+            case 'r':
+                *pval++ = '\r';
+                break;
+            case 't':
+                *pval++ = '\t';
+                break;
+            case 'u':
+                for (n = 0; n < 4 && c != '\0'; n++) {
+                    uescape[n] = c;
+                    c = jb->jb_read_next(jb);
+                }
+                // Scroll back one
+                c = jb->jb_read_prev(jb);
+                (void)sscanf(uescape, "%04x", &u);
+                *pval++ = (char)u;        /* will truncate values above 0xff */
+                break;
+            default:                /* handles double quote and solidus */
+                *pval++ = c;
+                break;
+            }
+            state = in_val_string;
+            break;
+        case in_val_token:
+            if (pval == NULL) {
+                /* don't update end here, leave at value start */
+                return JSON_ERR_NULLPTR;
+            }
+            if (isspace((unsigned char) c) || c == ',' || c == '}') {
+                *pval = '\0';
+                state = post_val;
+                if (c == '}' || c == ',') {
+                    c = jb->jb_read_prev(jb);
+                }
+            } else if (pval > valbuf + JSON_VAL_MAX - 1) {
+                /* don't update end here, leave at value start */
+                return JSON_ERR_TOKLONG;
+            } else {
+                *pval++ = c;
+            }
+            break;
+        case post_val:
+            /*
+             * We know that cursor points at the first spec matching
+             * the current attribute.  We don't know that it's *the*
+             * correct spec; our dialect allows there to be any number
+             * of adjacent ones with the same attrname but different
+             * types.  Here's where we try to seek forward for a
+             * matching type/attr pair if we're not looking at one.
+             */
+            for (;;) {
+                int seeking = cursor->type;
+                if (value_quoted && (cursor->type == t_string)) {
+                    break;
+                }
+                if ((strcmp(valbuf, "true")==0 || strcmp(valbuf, "false")==0)
+                        && seeking == t_boolean) {
+                    break;
+                }
+                if (isdigit((unsigned char) valbuf[0])) {
+                    bool decimal = strchr(valbuf, '.') != NULL;
+                    if (decimal && seeking == t_real) {
+                        break;
+                    }
+                    if (!decimal && (seeking == t_integer ||
+                                     seeking == t_uinteger)) {
+                        break;
+                    }
+                }
+                if (cursor[1].attribute==NULL) {       /* out of possiblities */
+                    break;
+                }
+                if (strcmp(cursor[1].attribute, attrbuf)!=0) {
+                    break;
+                }
+                ++cursor;
+            }
+            if (value_quoted
+                && (cursor->type != t_string && cursor->type != t_character
+                    && cursor->type != t_check && cursor->type != t_ignore
+                    && cursor->map == 0)) {
+                return JSON_ERR_QNONSTRING;
+            }
+            if (!value_quoted
+                && (cursor->type == t_string || cursor->type == t_check
+                    || cursor->map != 0)) {
+                return JSON_ERR_NONQSTRING;
+            }
+            if (cursor->map != 0) {
+                for (mp = cursor->map; mp->name != NULL; mp++) {
+                    if (strcmp(mp->name, valbuf) == 0) {
+                        goto foundit;
+                    }
+                }
+                return JSON_ERR_BADENUM;
+              foundit:
+                (void)snprintf(valbuf, sizeof(valbuf), "%lld", mp->value);
+            }
+            lptr = json_target_address(cursor, parent, offset);
+            if (lptr != NULL) {
+                switch (cursor->type) {
+                case t_integer: {
+                        long long int tmp =
+                            (long long int)strtoll(valbuf, NULL, 10);
+                        memcpy(lptr, &tmp, sizeof(long long int));
+                    }
+                    break;
+                case t_uinteger: {
+                        long long unsigned int tmp =
+                            (long long unsigned int)strtoull(valbuf, NULL, 10);
+                        memcpy(lptr, &tmp, sizeof(long long unsigned int));
+                    }
+                    break;
+                case t_real: {
+#ifdef FLOAT_SUPPORT
+                        double tmp = atof(valbuf);
+                        memcpy(lptr, &tmp, sizeof(double));
+#else
+                        return JSON_ERR_MISC;
+#endif
+                    }
+                    break;
+                case t_string:
+                    if (parent != NULL
+                        && parent->element_type != t_structobject
+                        && offset > 0) {
+                        return JSON_ERR_NOPARSTR;
+                    }
+                    (void)strncpy(lptr, valbuf, cursor->len);
+                    valbuf[sizeof(valbuf)-1] = '\0';
+                    break;
+                case t_boolean: {
+                        bool tmp = (strcmp(valbuf, "true") == 0);
+                        memcpy(lptr, &tmp, sizeof(bool));
+                    }
+                    break;
+                case t_character:
+                    if (strlen(valbuf) > 1) {
+                        /* don't update end here, leave at value start */
+                        return JSON_ERR_STRLONG;
+                    } else {
+                        lptr[0] = valbuf[0];
+                    }
+                    break;
+                case t_ignore:        /* silences a compiler warning */
+                case t_object:        /* silences a compiler warning */
+                case t_structobject:
+                case t_array:
+                    break;
+                case t_check:
+                    if (strcmp(cursor->dflt.check, valbuf) != 0) {
+                        /* don't update end here, leave at start of attribute */
+                        return JSON_ERR_CHECKFAIL;
+                    }
+                    break;
+                }
+            }
+            /*@fallthrough@*/
+        case post_array:
+            if (isspace((unsigned char) c)) {
+                continue;
+            } else if (c == ',') {
+                state = await_attr;
+            } else if (c == '}') {
+                c = jb->jb_read_next(jb);
+                goto good_parse;
+            } else {
+                return JSON_ERR_BADTRAIL;
+            }
+            break;
+        }
+    }
+
+  good_parse:
+    /* in case there's another object following, consume trailing WS */
+    while (isspace((unsigned char) jb->jb_read_next(jb))) {
+    }
+    return 0;
+}
+
+int
+json_read_array(struct json_buffer *jb, const struct json_array_t *arr)
+{
+    char valbuf[64];
+    char c;
+    int substatus, offset, arrcount;
+    char *tp;
+    int n, count;
+
+    json_skip_ws(jb);
+
+    if (jb->jb_read_next(jb) != '[') {
+        return JSON_ERR_ARRAYSTART;
+    }
+
+    tp = arr->arr.strings.store;
+    arrcount = 0;
+
+    json_skip_ws(jb);
+
+    if (json_peek(jb) == ']') {
+        goto breakout;
+    }
+
+    for (offset = 0; offset < arr->maxlen; offset++) {
+        json_skip_ws(jb);
+
+        char *ep = NULL;
+        switch (arr->element_type) {
+        case t_string:
+            if (jb->jb_read_next(jb) != '"') {
+                return JSON_ERR_BADSTRING;
+            }
+            arr->arr.strings.ptrs[offset] = tp;
+            for (; tp - arr->arr.strings.store < arr->arr.strings.storelen;
+                 tp++) {
+                c = jb->jb_read_next(jb);
+                if (c == '"') {
+                    c = jb->jb_read_next(jb);
+                    *tp++ = '\0';
+                    goto stringend;
+                } else if (c == '\0') {
+                    return JSON_ERR_BADSTRING;
+                } else {
+                    *tp = c;
+                    c = jb->jb_read_next(jb);
+                }
+            }
+            return JSON_ERR_BADSTRING;
+          stringend:
+            break;
+        case t_object:
+        case t_structobject:
+            substatus =
+                json_internal_read_object(jb, arr->arr.objects.subtype, arr,
+                                          offset);
+            if (substatus != 0) {
+                return substatus;
+            }
+            break;
+        case t_integer:
+            n = jb->jb_readn(jb, valbuf, sizeof(valbuf)-1);
+            valbuf[n] = '\0';
+
+            arr->arr.integers.store[offset] = strtoll(valbuf, &ep, 0);
+            if (ep == valbuf) {
+                return JSON_ERR_BADNUM;
+            } else {
+                count = n - (ep - valbuf);
+                while (count-- > 0) {
+                    jb->jb_read_prev(jb);
+                }
+            }
+            break;
+        case t_uinteger:
+            n = jb->jb_readn(jb, valbuf, sizeof(valbuf)-1);
+            valbuf[n] = '\0';
+
+            arr->arr.uintegers.store[offset] = strtoull(valbuf, &ep, 0);
+            if (ep == valbuf) {
+                return JSON_ERR_BADNUM;
+            } else {
+                count = n - (ep - valbuf);
+                while (count-- > 0) {
+                    jb->jb_read_prev(jb);
+                }
+            }
+            break;
+        case t_real:
+#ifdef FLOAT_SUPPORT
+            n = jb->jb_readn(jb, valbuf, sizeof(valbuf)-1);
+            valbuf[n] = '\0';
+
+            arr->arr.reals.store[offset] = strtod(valbuf, &ep);
+            if (ep == valbuf) {
+                return JSON_ERR_BADNUM;
+            } else {
+                count = ep - valbuf;
+                while (count-- > 0) {
+                    c = jb->jb_read_next(jb);
+                }
+            }
+#else
+            return JSON_ERR_MISC;
+#endif
+            break;
+        case t_boolean:
+            n = jb->jb_readn(jb, valbuf, 5);
+            valbuf[n] = '\0';
+
+            if (strncmp(valbuf, "true", 4) == 0) {
+                arr->arr.booleans.store[offset] = true;
+                count = n - 4;
+            } else if (strncmp(valbuf, "false", 5) == 0) {
+                arr->arr.booleans.store[offset] = false;
+                count = n - 5;
+            } else {
+                return JSON_ERR_MISC;
+            }
+
+            assert(count >= 0);
+            while (count-- > 0) {
+                jb->jb_read_prev(jb);
+            }
+            break;
+        case t_character:
+        case t_array:
+        case t_check:
+        case t_ignore:
+            return JSON_ERR_SUBTYPE;
+        }
+        arrcount++;
+        json_skip_ws(jb);
+
+        c = jb->jb_read_next(jb);
+        if (c == ']') {
+            goto breakout;
+        } else if (c != ',') {
+            return JSON_ERR_BADSUBTRAIL;
+        }
+    }
+    return JSON_ERR_SUBTOOLONG;
+  breakout:
+    if (arr->count != NULL) {
+        *(arr->count) = arrcount;
+    }
+    return 0;
+}
+
+int
+json_read_object(struct json_buffer *jb, const struct json_attr_t *attrs)
+{
+    int st;
+
+    st = json_internal_read_object(jb, attrs, NULL, 0);
+    return st;
+}
+

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/encoding/json/src/json_encode.c
----------------------------------------------------------------------
diff --git a/encoding/json/src/json_encode.c b/encoding/json/src/json_encode.c
new file mode 100644
index 0000000..8512a66
--- /dev/null
+++ b/encoding/json/src/json_encode.c
@@ -0,0 +1,248 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include <stdio.h>
+#include <string.h>
+
+#include <json/json.h>
+
+#define JSON_ENCODE_OBJECT_START(__e) \
+    (__e)->je_write((__e)->je_arg, "{", sizeof("{")-1);
+
+#define JSON_ENCODE_OBJECT_END(__e) \
+    (__e)->je_write((__e)->je_arg, "}", sizeof("}")-1);
+
+#define JSON_ENCODE_ARRAY_START(__e) \
+    (__e)->je_write((__e)->je_arg, "[", sizeof("[")-1);
+
+#define JSON_ENCODE_ARRAY_END(__e) \
+    (__e)->je_write((__e)->je_arg, "]", sizeof("]")-1);
+
+
+int
+json_encode_object_start(struct json_encoder *encoder)
+{
+    if (encoder->je_wr_commas) {
+        encoder->je_write(encoder->je_arg, ",", sizeof(",")-1);
+        encoder->je_wr_commas = 0;
+    }
+    JSON_ENCODE_OBJECT_START(encoder);
+    encoder->je_wr_commas = 0;
+
+    return (0);
+}
+
+static int
+json_encode_value(struct json_encoder *encoder, struct json_value *jv)
+{
+    int rc;
+    int i;
+    int len;
+
+    switch (jv->jv_type) {
+        case JSON_VALUE_TYPE_BOOL:
+            len = sprintf(encoder->je_encode_buf, "%s",
+                    jv->jv_val.u > 0 ? "true" : "false");
+            encoder->je_write(encoder->je_arg, encoder->je_encode_buf, len);
+            break;
+        case JSON_VALUE_TYPE_UINT64:
+            len = sprintf(encoder->je_encode_buf, "%llu",
+                    jv->jv_val.u);
+            encoder->je_write(encoder->je_arg, encoder->je_encode_buf, len);
+            break;
+        case JSON_VALUE_TYPE_INT64:
+            len = sprintf(encoder->je_encode_buf, "%lld",
+                    jv->jv_val.u);
+            encoder->je_write(encoder->je_arg, encoder->je_encode_buf, len);
+            break;
+        case JSON_VALUE_TYPE_STRING:
+            encoder->je_write(encoder->je_arg, "\"", sizeof("\"")-1);
+            for (i = 0; i < jv->jv_len; i++) {
+                switch (jv->jv_val.str[i]) {
+                    case '"':
+                    case '/':
+                    case '\\':
+                        encoder->je_write(encoder->je_arg, "\\",
+                                sizeof("\\")-1);
+                        encoder->je_write(encoder->je_arg,
+                                (char *) &jv->jv_val.str[i], 1);
+
+                        break;
+                    case '\t':
+                        encoder->je_write(encoder->je_arg, "\\t",
+                                sizeof("\\t")-1);
+                        break;
+                    case '\r':
+                        encoder->je_write(encoder->je_arg, "\\r",
+                                sizeof("\\r")-1);
+                        break;
+                    case '\n':
+                        encoder->je_write(encoder->je_arg, "\\n",
+                                sizeof("\\n")-1);
+                        break;
+                    case '\f':
+                        encoder->je_write(encoder->je_arg, "\\f",
+                                sizeof("\\f")-1);
+                        break;
+                    case '\b':
+                        encoder->je_write(encoder->je_arg, "\\b",
+                                sizeof("\\b")-1);
+                        break;
+                   default:
+                        encoder->je_write(encoder->je_arg,
+                                (char *) &jv->jv_val.str[i], 1);
+                        break;
+                }
+
+            }
+            encoder->je_write(encoder->je_arg, "\"", sizeof("\"")-1);
+            break;
+        case JSON_VALUE_TYPE_ARRAY:
+            JSON_ENCODE_ARRAY_START(encoder);
+            for (i = 0; i < jv->jv_len; i++) {
+                rc = json_encode_value(encoder, jv->jv_val.composite.values[i]);
+                if (rc != 0) {
+                    goto err;
+                }
+                if (i != jv->jv_len - 1) {
+                    encoder->je_write(encoder->je_arg, ",", sizeof(",")-1);
+                }
+            }
+            JSON_ENCODE_ARRAY_END(encoder);
+            break;
+        case JSON_VALUE_TYPE_OBJECT:
+            JSON_ENCODE_OBJECT_START(encoder);
+            for (i = 0; i < jv->jv_len; i++) {
+                rc = json_encode_object_entry(encoder,
+                        jv->jv_val.composite.keys[i],
+                        jv->jv_val.composite.values[i]);
+                if (rc != 0) {
+                    goto err;
+                }
+            }
+            JSON_ENCODE_OBJECT_END(encoder);
+            break;
+        default:
+            rc = -1;
+            goto err;
+    }
+
+
+    return (0);
+err:
+    return (rc);
+}
+
+int
+json_encode_object_key(struct json_encoder *encoder, char *key)
+{
+    if (encoder->je_wr_commas) {
+        encoder->je_write(encoder->je_arg, ",", sizeof(",")-1);
+        encoder->je_wr_commas = 0;
+    }
+
+    /* Write the key entry */
+    encoder->je_write(encoder->je_arg, "\"", sizeof("\"")-1);
+    encoder->je_write(encoder->je_arg, key, strlen(key));
+    encoder->je_write(encoder->je_arg, "\": ", sizeof("\": ")-1);
+
+    return (0);
+}
+
+int
+json_encode_object_entry(struct json_encoder *encoder, char *key,
+        struct json_value *val)
+{
+    int rc;
+
+    if (encoder->je_wr_commas) {
+        encoder->je_write(encoder->je_arg, ",", sizeof(",")-1);
+        encoder->je_wr_commas = 0;
+    }
+    /* Write the key entry */
+    encoder->je_write(encoder->je_arg, "\"", sizeof("\"")-1);
+    encoder->je_write(encoder->je_arg, key, strlen(key));
+    encoder->je_write(encoder->je_arg, "\": ", sizeof("\": ")-1);
+
+    rc = json_encode_value(encoder, val);
+    if (rc != 0) {
+        goto err;
+    }
+    encoder->je_wr_commas = 1;
+
+    return (0);
+err:
+    return (rc);
+}
+
+int
+json_encode_object_finish(struct json_encoder *encoder)
+{
+    JSON_ENCODE_OBJECT_END(encoder);
+    /* Useful in case of nested objects. */
+    encoder->je_wr_commas = 1;
+
+    return (0);
+}
+
+int
+json_encode_array_name(struct json_encoder *encoder, char *name)
+{
+    return json_encode_object_key(encoder, name);
+}
+
+int
+json_encode_array_start(struct json_encoder *encoder)
+{
+    JSON_ENCODE_ARRAY_START(encoder);
+    encoder->je_wr_commas = 0;
+
+    return (0);
+}
+
+int
+json_encode_array_value(struct json_encoder *encoder, struct json_value *jv)
+{
+    int rc;
+
+    if (encoder->je_wr_commas) {
+        encoder->je_write(encoder->je_arg, ",", sizeof(",")-1);
+        encoder->je_wr_commas = 0;
+    }
+
+    rc = json_encode_value(encoder, jv);
+    if (rc != 0) {
+        goto err;
+    }
+    encoder->je_wr_commas = 1;
+
+    return (0);
+err:
+    return (rc);
+}
+
+
+int
+json_encode_array_finish(struct json_encoder *encoder)
+{
+    encoder->je_wr_commas = 1;
+    JSON_ENCODE_ARRAY_END(encoder);
+
+    return (0);
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/encoding/json/test/pkg.yml
----------------------------------------------------------------------
diff --git a/encoding/json/test/pkg.yml b/encoding/json/test/pkg.yml
new file mode 100644
index 0000000..1d57016
--- /dev/null
+++ b/encoding/json/test/pkg.yml
@@ -0,0 +1,30 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+#
+pkg.name: encoding/json/test
+pkg.type: unittest
+pkg.description: "JSON unit tests."
+pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
+pkg.homepage: "http://mynewt.apache.org/"
+pkg.keywords:
+
+pkg.deps: 
+    - encoding/json
+    - test/testutil
+
+pkg.deps.SELFTEST:
+    - sys/console/stub

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/encoding/json/test/src/test_json.c
----------------------------------------------------------------------
diff --git a/encoding/json/test/src/test_json.c b/encoding/json/test/src/test_json.c
new file mode 100644
index 0000000..dab3f06
--- /dev/null
+++ b/encoding/json/test/src/test_json.c
@@ -0,0 +1,43 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include "syscfg/syscfg.h"
+#include "testutil/testutil.h"
+#include "test_json.h"
+
+
+TEST_SUITE(test_json_suite) {
+    test_json_simple_encode();
+    test_json_simple_decode();
+}
+
+#if MYNEWT_VAL(SELFTEST)
+
+int
+main(int argc, char **argv)
+{
+    tu_config.tc_print_results = 1;
+    tu_init();
+
+    test_json_suite();
+
+    return tu_any_failed;
+}
+
+#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/encoding/json/test/src/test_json.h
----------------------------------------------------------------------
diff --git a/encoding/json/test/src/test_json.h b/encoding/json/test/src/test_json.h
new file mode 100644
index 0000000..ea5efcf
--- /dev/null
+++ b/encoding/json/test/src/test_json.h
@@ -0,0 +1,27 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 TEST_JSON_H
+#define TEST_JSON_H
+
+TEST_CASE_DECL(test_json_simple_encode);
+TEST_CASE_DECL(test_json_simple_decode);
+
+#endif /* TEST_JSON_H */
+

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/encoding/json/test/src/test_json_simple.c
----------------------------------------------------------------------
diff --git a/encoding/json/test/src/test_json_simple.c b/encoding/json/test/src/test_json_simple.c
new file mode 100644
index 0000000..0f9e10e
--- /dev/null
+++ b/encoding/json/test/src/test_json_simple.c
@@ -0,0 +1,360 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include <assert.h>
+#include <string.h>
+#include "testutil/testutil.h"
+#include "test_json.h"
+#include "json/json.h"
+
+static char *output = "{\"KeyBool\": true,\"KeyInt\": -1234,\"KeyUint\": 1353214,\"KeyString\": \"foobar\",\"KeyStringN\": \"foobarlong\",\"KeyIntArr\": [153,2532,-322]}";
+
+static char *output1 ="{\"KeyBoolArr\": [true, false], \"KeyUintArr\": [0, 65535, 4294967295, 8589934590, 3451257]}";
+static char *outputboolspace = "{\"KeyBoolArr\": [    true    ,    false,true         ]}";
+static char *outputboolempty = "{\"KeyBoolArr\": , \"KeyBoolArr\": [  ]}";
+
+static char bigbuf[512];
+static int buf_index;
+
+static int test_write(void *buf, char* data, int len) {
+    int i;
+    for(i = 0; i < len; i++) {
+        bigbuf[buf_index++] = data[i];
+    }
+    return len;
+}
+
+TEST_CASE(test_json_simple_encode){
+    struct json_encoder encoder;
+    struct json_value value;
+    int rc;
+
+    /* reset the state of the internal test */
+    buf_index = 0;
+    memset(&encoder, 0, sizeof(encoder));
+
+    encoder.je_write = test_write;
+    encoder.je_arg= NULL;
+
+    rc = json_encode_object_start(&encoder);
+    TEST_ASSERT(rc == 0);
+
+    JSON_VALUE_BOOL(&value, 1);
+    rc = json_encode_object_entry(&encoder, "KeyBool", &value);
+    TEST_ASSERT(rc == 0);
+
+    JSON_VALUE_INT(&value, -1234);
+    rc = json_encode_object_entry(&encoder, "KeyInt", &value);
+    TEST_ASSERT(rc == 0);
+
+    JSON_VALUE_UINT(&value, 1353214);
+    rc = json_encode_object_entry(&encoder, "KeyUint", &value);
+    TEST_ASSERT(rc == 0);
+
+    JSON_VALUE_STRING(&value, "foobar");
+    rc = json_encode_object_entry(&encoder, "KeyString", &value);
+    TEST_ASSERT(rc == 0);
+
+    /* we'll decode later differently */
+    JSON_VALUE_STRINGN(&value, "foobarlongstring", 10);
+    rc = json_encode_object_entry(&encoder, "KeyStringN", &value);
+    TEST_ASSERT(rc == 0);
+
+    rc = json_encode_array_name(&encoder, "KeyIntArr");
+    TEST_ASSERT(rc == 0);
+
+    rc = json_encode_array_start(&encoder);
+    TEST_ASSERT(rc == 0);
+
+    JSON_VALUE_INT(&value, 153);
+    rc = json_encode_array_value(&encoder, &value);
+    TEST_ASSERT(rc == 0);
+
+    JSON_VALUE_INT(&value, 2532);
+    rc = json_encode_array_value(&encoder, &value);
+    TEST_ASSERT(rc == 0);
+
+    JSON_VALUE_INT(&value, -322);
+    rc = json_encode_array_value(&encoder, &value);
+    TEST_ASSERT(rc == 0);
+
+    rc = json_encode_array_finish(&encoder);
+    TEST_ASSERT(rc == 0);
+
+    rc = json_encode_object_finish(&encoder);
+    TEST_ASSERT(rc == 0);
+
+    /* does it match what we expect it to */
+    rc = strcmp(bigbuf, output);
+    TEST_ASSERT(rc == 0);
+}
+
+
+/* a test structure to hold the json flat buffer and pass bytes
+ * to the decoder */
+struct test_jbuf {
+    /* json_buffer must be first element in the structure */
+    struct json_buffer json_buf;
+    char * start_buf;
+    char * end_buf;
+    int current_position;
+};
+
+
+static char
+test_jbuf_read_next(struct json_buffer *jb) {
+    char c;
+    struct test_jbuf  *ptjb = (struct test_jbuf*) jb;
+
+    if((ptjb->start_buf + ptjb->current_position) <= ptjb->end_buf) {
+        c = *(ptjb->start_buf + ptjb->current_position);
+        ptjb->current_position++;
+        return c;
+    }
+    return '\0';
+}
+
+/* this goes backward in the buffer one character */
+static char
+test_jbuf_read_prev(struct json_buffer *jb) {
+    char c;
+    struct test_jbuf  *ptjb = (struct test_jbuf*) jb;
+    if(ptjb->current_position) {
+       ptjb->current_position--;
+       c = *(ptjb->start_buf + ptjb->current_position);
+       return c;
+    }
+
+    /* can't rewind */
+    return '\0';
+
+}
+
+static int
+test_jbuf_readn(struct json_buffer *jb, char *buf, int size) {
+    struct test_jbuf  *ptjb = (struct test_jbuf*) jb;
+
+    int remlen;
+
+    remlen = ptjb->end_buf - (ptjb->start_buf + ptjb->current_position);
+    if (size > remlen) {
+        size = remlen;
+    }
+
+    memcpy(buf, ptjb->start_buf + ptjb->current_position, size);
+    ptjb->current_position += size;
+    return size;
+}
+
+static void
+test_buf_init(struct test_jbuf *ptjb, char *string) {
+    /* initialize the decode */
+    ptjb->json_buf.jb_read_next = test_jbuf_read_next;
+    ptjb->json_buf.jb_read_prev = test_jbuf_read_prev;
+    ptjb->json_buf.jb_readn = test_jbuf_readn;
+    ptjb->start_buf = string;
+    ptjb->end_buf = string + strlen(string);
+    /* end buf points to the NULL */
+    ptjb->current_position = 0;
+}
+
+/* now test the decode on a string */
+TEST_CASE(test_json_simple_decode){
+    struct test_jbuf tjb;
+    struct test_jbuf tjb1;
+    struct test_jbuf tjbboolspacearr;
+    struct test_jbuf tjbboolemptyarr;
+    long long unsigned int uint_val;
+    long long int int_val;
+    bool bool_val;
+    char string1[16];
+    char string2[16];
+    long long int intarr[8];
+    int rc;
+    int rc1;
+    int rcbsa;
+    int array_count;
+    int array_countemp;
+    bool boolarr[2];
+    unsigned long long uintarr[5];
+    int array_count1;
+    int array_count1u;
+    bool boolspacearr[3];
+    bool boolemptyarr[2];
+    
+    struct json_attr_t test_attr[7] = {
+        [0] = {
+            .attribute = "KeyBool",
+            .type = t_boolean,
+            .addr.boolean = &bool_val,
+            .nodefault = true
+        },
+        [1] = {
+            .attribute = "KeyInt",
+            .type = t_integer,
+            .addr.integer = &int_val,
+            .nodefault = true
+            },
+        [2] = {
+            .attribute = "KeyUint",
+            .type = t_uinteger,
+            .addr.uinteger = &uint_val,
+            .nodefault = true
+            },
+        [3] = {
+            .attribute = "KeyString",
+            .type = t_string,
+            .addr.string = string1,
+            .nodefault = true,
+            .len = sizeof(string1)
+            },
+        [4] = {
+            .attribute = "KeyStringN",
+            .type = t_string,
+            .addr.string = string2,
+            .nodefault = true,
+            .len = sizeof(string2)
+        },
+        [5] = {
+            .attribute = "KeyIntArr",
+            .type = t_array,
+            .addr.array = {
+                .element_type = t_integer,
+                .arr.integers.store = intarr,
+                .maxlen = sizeof intarr / sizeof intarr[0],
+                .count = &array_count,
+            },
+            .nodefault = true,
+            .len = sizeof(intarr)
+        },
+        [6] = {
+            .attribute = NULL
+        }
+    };
+    
+    test_buf_init(&tjb, output);
+
+    rc = json_read_object(&tjb.json_buf, test_attr);
+    TEST_ASSERT(rc==0);
+    TEST_ASSERT(bool_val == 1);
+    TEST_ASSERT(int_val ==  -1234);
+    TEST_ASSERT(uint_val == 1353214);
+
+    rc = memcmp(string1, "foobar", strlen("foobar"));
+    TEST_ASSERT(rc==0);
+
+    rc = memcmp(string2, "foobarlongstring", 10);
+    TEST_ASSERT(rc==0);
+
+    TEST_ASSERT(array_count == 3);
+    TEST_ASSERT(intarr[0] == 153);
+    TEST_ASSERT(intarr[1] == 2532);
+    TEST_ASSERT(intarr[2] == -322);
+
+   /*testing for the boolean*/
+   struct json_attr_t test_attr1[2] = {
+       [0] = {
+           .attribute = "KeyBoolArr",
+           .type = t_array,
+           .addr.array = {
+               .element_type = t_boolean,
+               .arr.booleans.store = boolarr,
+               .maxlen = sizeof boolarr / sizeof boolarr[0],
+               .count =&array_count1,
+           },
+           .nodefault = true,
+           .len = sizeof( boolarr),
+       },
+
+       [1] = {
+           .attribute = "KeyUintArr",
+           .type = t_array,
+           .addr.array = {
+               .element_type = t_uinteger,
+               .arr.uintegers.store = uintarr,
+               .maxlen = sizeof uintarr / sizeof uintarr[0],
+               .count =&array_count1u,
+           },
+           .nodefault = true,
+           .len = sizeof( uintarr),
+       }
+   };
+   
+   test_buf_init(&tjb1, output1);
+
+   rc1 = json_read_object(&tjb1.json_buf, test_attr1);
+   TEST_ASSERT(rc1==0);
+
+   TEST_ASSERT(boolarr[0] == true);
+   TEST_ASSERT(boolarr[1] == false);
+
+   TEST_ASSERT(uintarr[0] == 0);
+   TEST_ASSERT(uintarr[1] == 65535);
+   TEST_ASSERT(uintarr[2] == 4294967295ULL);
+   TEST_ASSERT(uintarr[3] == 8589934590ULL);
+   TEST_ASSERT(uintarr[4] == 3451257ULL);
+
+    /*testing arrays with empty spaces within the elements*/
+    struct json_attr_t test_boolspacearr[2] = {
+       [0] = {    
+           .attribute = "KeyBoolArr",
+           .type = t_array,
+           .addr.array = {
+               .element_type = t_boolean,
+               .arr.booleans.store = boolspacearr,
+               .maxlen = sizeof boolspacearr / sizeof boolspacearr[0],
+               .count =&array_count1,
+           },
+           .nodefault = true,
+           .len = sizeof( boolspacearr),
+       }
+           
+    };
+    
+    test_buf_init(&tjbboolspacearr, outputboolspace);
+
+    rcbsa = json_read_object(&tjbboolspacearr.json_buf, test_boolspacearr);
+    TEST_ASSERT(rcbsa == 0);
+
+    TEST_ASSERT(boolspacearr[0] == true);
+    TEST_ASSERT(boolspacearr[1] == false);
+    TEST_ASSERT(boolspacearr[2] == true);
+
+    /*testing array with empty value*/
+    struct json_attr_t test_boolemptyarr[2] = {
+        [0] = {
+            .attribute = "KeyBoolArr",
+           .type = t_array,
+           .addr.array = {
+               .element_type = t_boolean,
+               .arr.booleans.store = boolemptyarr,
+               .maxlen = sizeof boolemptyarr / sizeof boolemptyarr[0],
+               .count =&array_countemp,
+           },
+           .nodefault = true,
+           .len = sizeof( boolemptyarr),
+        }
+    };
+   
+   test_buf_init(&tjbboolemptyarr, outputboolempty);
+
+    rcbsa = json_read_object(&tjbboolemptyarr.json_buf, test_boolemptyarr);
+    TEST_ASSERT(rcbsa == 6); 
+    
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/encoding/tinycbor/include/tinycbor/assert_p.h
----------------------------------------------------------------------
diff --git a/encoding/tinycbor/include/tinycbor/assert_p.h b/encoding/tinycbor/include/tinycbor/assert_p.h
new file mode 100644
index 0000000..994be06
--- /dev/null
+++ b/encoding/tinycbor/include/tinycbor/assert_p.h
@@ -0,0 +1,29 @@
+/****************************************************************************
+**
+** Copyright (C) 2015 Intel Corporation
+**
+** Permission is hereby granted, free of charge, to any person obtaining a copy
+** of this software and associated documentation files (the "Software"), to deal
+** in the Software without restriction, including without limitation the rights
+** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+** copies of the Software, and to permit persons to whom the Software is
+** furnished to do so, subject to the following conditions:
+**
+** The above copyright notice and this permission notice shall be included in
+** all copies or substantial portions of the Software.
+**
+** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+** THE SOFTWARE.
+**
+****************************************************************************/
+
+#include <assert.h>
+#ifdef NDEBUG
+#  undef assert
+#  define assert(cond)      do { if (!(cond)) unreachable(); } while (0)
+#endif



[07/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/net/ip/mn_socket/src/arch/sim/native_sock.c
----------------------------------------------------------------------
diff --git a/net/ip/mn_socket/src/arch/sim/native_sock.c b/net/ip/mn_socket/src/arch/sim/native_sock.c
new file mode 100644
index 0000000..819120c
--- /dev/null
+++ b/net/ip/mn_socket/src/arch/sim/native_sock.c
@@ -0,0 +1,753 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+#include <sys/socket.h>
+#include <unistd.h>
+#include <errno.h>
+#include <netinet/in.h>
+#include <string.h>
+#include <poll.h>
+#include <assert.h>
+#include <fcntl.h>
+#include <sys/ioctl.h>
+#include <stdio.h>
+
+#include <os/os.h>
+#include <os/os_mbuf.h>
+#include "mn_socket/mn_socket.h"
+#include "mn_socket/mn_socket_ops.h"
+
+#include "mn_socket/arch/sim/native_sock.h"
+#include "native_sock_priv.h"
+
+#define NATIVE_SOCK_MAX 8
+#define NATIVE_SOCK_MAX_UDP 2048
+#define NATIVE_SOCK_POLL_ITVL (OS_TICKS_PER_SEC / 5)
+#define SOCK_STACK_SZ   4096
+#define SOCK_PRIO       2
+
+static int native_sock_create(struct mn_socket **sp, uint8_t domain,
+  uint8_t type, uint8_t proto);
+static int native_sock_close(struct mn_socket *);
+static int native_sock_connect(struct mn_socket *, struct mn_sockaddr *);
+static int native_sock_bind(struct mn_socket *, struct mn_sockaddr *);
+static int native_sock_listen(struct mn_socket *, uint8_t qlen);
+static int native_sock_sendto(struct mn_socket *, struct os_mbuf *,
+  struct mn_sockaddr *);
+static int native_sock_recvfrom(struct mn_socket *, struct os_mbuf **,
+  struct mn_sockaddr *);
+static int native_sock_getsockopt(struct mn_socket *, uint8_t level,
+  uint8_t name, void *val);
+static int native_sock_setsockopt(struct mn_socket *, uint8_t level,
+  uint8_t name, void *val);
+
+static int native_sock_getsockname(struct mn_socket *, struct mn_sockaddr *);
+static int native_sock_getpeername(struct mn_socket *, struct mn_sockaddr *);
+
+static struct native_sock {
+    struct mn_socket ns_sock;
+    int ns_fd;
+    unsigned int ns_poll:1;
+    unsigned int ns_listen:1;
+    uint8_t ns_type;
+    uint8_t ns_pf;
+    struct os_sem ns_sem;
+    STAILQ_HEAD(, os_mbuf_pkthdr) ns_rx;
+    struct os_mbuf *ns_tx;
+} native_socks[NATIVE_SOCK_MAX];
+
+static struct native_sock_state {
+    struct pollfd poll_fds[NATIVE_SOCK_MAX];
+    int poll_fd_cnt;
+    struct os_mutex mtx;
+    struct os_task task;
+} native_sock_state;
+
+static const struct mn_socket_ops native_sock_ops = {
+    .mso_create = native_sock_create,
+    .mso_close = native_sock_close,
+
+    .mso_bind = native_sock_bind,
+    .mso_connect = native_sock_connect,
+    .mso_listen = native_sock_listen,
+
+    .mso_sendto = native_sock_sendto,
+    .mso_recvfrom = native_sock_recvfrom,
+
+    .mso_getsockopt = native_sock_getsockopt,
+    .mso_setsockopt = native_sock_setsockopt,
+
+    .mso_getsockname = native_sock_getsockname,
+    .mso_getpeername = native_sock_getpeername,
+
+    .mso_itf_getnext = native_sock_itf_getnext,
+    .mso_itf_addr_getnext = native_sock_itf_addr_getnext
+};
+
+static struct native_sock *
+native_get_sock(void)
+{
+    int i;
+    struct native_sock *ns;
+
+    for (i = 0; i < NATIVE_SOCK_MAX; i++) {
+        if (native_socks[i].ns_fd < 0) {
+            ns = &native_socks[i];
+            ns->ns_poll = 0;
+            ns->ns_listen = 0;
+            return ns;
+        }
+    }
+    return NULL;
+}
+
+static struct native_sock *
+native_find_sock(int fd)
+{
+    int i;
+
+    for (i = 0; i < NATIVE_SOCK_MAX; i++) {
+        if (native_socks[i].ns_fd == fd) {
+            return &native_socks[i];
+        }
+    }
+    return NULL;
+}
+
+static void
+native_sock_poll_rebuild(struct native_sock_state *nss)
+{
+    struct native_sock *ns;
+    int i;
+    int j;
+
+    os_mutex_pend(&nss->mtx, OS_WAIT_FOREVER);
+    for (i = 0, j = 0; i < NATIVE_SOCK_MAX; i++) {
+        ns = &native_socks[i];
+        if (ns->ns_fd < 0) {
+            continue;
+        }
+        if (!ns->ns_poll) {
+            continue;
+        }
+        nss->poll_fds[j].fd = ns->ns_fd;
+        nss->poll_fds[j].events = POLLIN;
+        nss->poll_fds[j].revents = 0;
+        j++;
+    }
+    nss->poll_fd_cnt = j;
+    os_mutex_release(&nss->mtx);
+}
+
+int
+native_sock_err_to_mn_err(int err)
+{
+    switch (err) {
+    case 0:
+        return 0;
+    case EAGAIN:
+    case EINPROGRESS:
+        return MN_EAGAIN;
+    case ENOTCONN:
+        return MN_ENOTCONN;
+    case ETIMEDOUT:
+        return MN_ETIMEDOUT;
+    case ENOMEM:
+        return MN_ENOBUFS;
+    case EADDRINUSE:
+        return MN_EADDRINUSE;
+    case EADDRNOTAVAIL:
+        return MN_EADDRNOTAVAIL;
+    default:
+        return MN_EINVAL;
+    }
+}
+
+static int
+native_sock_mn_addr_to_addr(struct mn_sockaddr *ms, struct sockaddr *sa,
+  int *sa_len)
+{
+    struct sockaddr_in *sin = (struct sockaddr_in *)sa;
+    struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa;
+    struct mn_sockaddr_in *msin = (struct mn_sockaddr_in *)ms;
+    struct mn_sockaddr_in6 *msin6 = (struct mn_sockaddr_in6 *)ms;
+
+    switch (ms->msa_family) {
+    case MN_AF_INET:
+        sin->sin_family = AF_INET;
+#ifndef MN_LINUX
+        sin->sin_len = sizeof(*sin);
+#endif
+        sin->sin_addr.s_addr = msin->msin_addr.s_addr;
+        sin->sin_port = msin->msin_port;
+        *sa_len = sizeof(*sin);
+        break;
+    case MN_AF_INET6:
+        sin6->sin6_family = AF_INET6;
+#ifndef MN_LINUX
+        sin6->sin6_len = sizeof(*sin6);
+#endif
+        sin6->sin6_port = msin6->msin6_port;
+        sin6->sin6_flowinfo = msin6->msin6_flowinfo;
+        memcpy(&sin6->sin6_addr, &msin6->msin6_addr, sizeof(msin6->msin6_addr));
+        sin6->sin6_scope_id = msin6->msin6_scope_id;
+        *sa_len = sizeof(*sin6);
+        break;
+    default:
+        return MN_EPROTONOSUPPORT;
+    }
+    return 0;
+}
+
+static int
+native_sock_addr_to_mn_addr(struct sockaddr *sa, struct mn_sockaddr *ms)
+{
+    struct mn_sockaddr_in *msin = (struct mn_sockaddr_in *)ms;
+    struct mn_sockaddr_in6 *msin6 = (struct mn_sockaddr_in6 *)ms;
+    struct sockaddr_in *sin = (struct sockaddr_in *)sa;
+    struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)sa;
+
+    switch (sa->sa_family) {
+    case AF_INET:
+        msin->msin_family = MN_AF_INET;
+        msin->msin_len = sizeof(*msin);
+        msin->msin_addr.s_addr = sin->sin_addr.s_addr;
+        msin->msin_port = sin->sin_port;
+        break;
+    case AF_INET6:
+        msin6->msin6_family = MN_AF_INET6;
+        msin6->msin6_len = sizeof(*msin6);
+        msin6->msin6_port = sin6->sin6_port;
+        msin6->msin6_flowinfo = sin6->sin6_flowinfo;
+        memcpy(&msin6->msin6_addr, &sin6->sin6_addr, sizeof(msin6->msin6_addr));
+        msin6->msin6_scope_id = sin6->sin6_scope_id;
+        break;
+    default:
+        return MN_EPROTONOSUPPORT;
+    }
+    return 0;
+}
+
+static int
+native_sock_create(struct mn_socket **sp, uint8_t domain,
+  uint8_t type, uint8_t proto)
+{
+    struct native_sock_state *nss = &native_sock_state;
+    struct native_sock *ns;
+    int idx;
+
+    switch (domain) {
+    case MN_PF_INET:
+        domain = PF_INET;
+        break;
+    case MN_PF_INET6:
+        domain = PF_INET6;
+        break;
+    default:
+        return MN_EPROTONOSUPPORT;
+    }
+
+    switch (type) {
+    case MN_SOCK_DGRAM:
+        type = SOCK_DGRAM;
+        break;
+    case MN_SOCK_STREAM:
+        type = SOCK_STREAM;
+        break;
+    case 0:
+        break;
+    default:
+        return MN_EPROTONOSUPPORT;
+    }
+
+    os_mutex_pend(&nss->mtx, OS_WAIT_FOREVER);
+    ns = native_get_sock();
+    if (!ns) {
+        os_mutex_release(&nss->mtx);
+        return MN_ENOBUFS;
+    }
+    os_sem_init(&ns->ns_sem, 0);
+    idx = socket(domain, type, proto);
+    ns->ns_fd = idx;
+    ns->ns_pf = domain;
+    ns->ns_type = type;
+    os_mutex_release(&nss->mtx);
+    if (idx < 0) {
+        return MN_ENOBUFS;
+    }
+    *sp = &ns->ns_sock;
+    return 0;
+}
+
+static int
+native_sock_close(struct mn_socket *s)
+{
+    struct native_sock_state *nss = &native_sock_state;
+    struct native_sock *ns = (struct native_sock *)s;
+    struct os_mbuf_pkthdr *m;
+
+    os_mutex_pend(&nss->mtx, OS_WAIT_FOREVER);
+    close(ns->ns_fd);
+    ns->ns_fd = -1;
+
+    /*
+     * When socket is closed, we must free all mbufs which might be
+     * queued in it.
+     */
+    while ((m = STAILQ_FIRST(&ns->ns_rx))) {
+        STAILQ_REMOVE_HEAD(&ns->ns_rx, omp_next);
+        os_mbuf_free_chain(OS_MBUF_PKTHDR_TO_MBUF(m));
+    }
+    native_sock_poll_rebuild(nss);
+    os_mutex_release(&nss->mtx);
+    return 0;
+}
+
+static int
+native_sock_connect(struct mn_socket *s, struct mn_sockaddr *addr)
+{
+    struct native_sock_state *nss = &native_sock_state;
+    struct native_sock *ns = (struct native_sock *)s;
+    struct sockaddr_storage ss;
+    struct sockaddr *sa = (struct sockaddr *)&ss;
+    int rc;
+    int sa_len;
+
+    rc = native_sock_mn_addr_to_addr(addr, sa, &sa_len);
+    if (rc) {
+        return rc;
+    }
+    os_mutex_pend(&nss->mtx, OS_WAIT_FOREVER);
+    if (connect(ns->ns_fd, sa, sa_len)) {
+        rc = errno;
+        os_mutex_release(&nss->mtx);
+        return native_sock_err_to_mn_err(rc);
+    }
+    ns->ns_poll = 1;
+    native_sock_poll_rebuild(nss);
+    os_mutex_release(&nss->mtx);
+    mn_socket_writable(s, 0);
+    return 0;
+}
+
+static int
+native_sock_bind(struct mn_socket *s, struct mn_sockaddr *addr)
+{
+    struct native_sock_state *nss = &native_sock_state;
+    struct native_sock *ns = (struct native_sock *)s;
+    struct sockaddr_storage ss;
+    struct sockaddr *sa = (struct sockaddr *)&ss;
+    int rc;
+    int sa_len;
+    int val = 1;
+
+    rc = native_sock_mn_addr_to_addr(addr, sa, &sa_len);
+    if (rc) {
+        return rc;
+    }
+
+    os_mutex_pend(&nss->mtx, OS_WAIT_FOREVER);
+    if (ns->ns_type == SOCK_STREAM) {
+        rc = setsockopt(ns->ns_fd, SOL_SOCKET, SO_REUSEADDR, &val,
+          sizeof(val));
+        if (rc) {
+            goto err;
+        }
+    }
+    rc = ioctl(ns->ns_fd, FIONBIO, (char *)&val);
+    if (rc) {
+        goto err;
+    }
+    if (bind(ns->ns_fd, sa, sa_len)) {
+        goto err;
+    }
+    if (ns->ns_type == SOCK_DGRAM) {
+        ns->ns_poll = 1;
+        native_sock_poll_rebuild(nss);
+    }
+    os_mutex_release(&nss->mtx);
+    return 0;
+err:
+    rc = errno;
+    os_mutex_release(&nss->mtx);
+    return native_sock_err_to_mn_err(rc);
+}
+
+static int
+native_sock_listen(struct mn_socket *s, uint8_t qlen)
+{
+    struct native_sock_state *nss = &native_sock_state;
+    struct native_sock *ns = (struct native_sock *)s;
+    int rc;
+
+    os_mutex_pend(&nss->mtx, OS_WAIT_FOREVER);
+    if (listen(ns->ns_fd, qlen)) {
+        rc = errno;
+        os_mutex_release(&nss->mtx);
+        return native_sock_err_to_mn_err(rc);
+    }
+    ns->ns_poll = 1;
+    ns->ns_listen = 1;
+    native_sock_poll_rebuild(nss);
+    os_mutex_release(&nss->mtx);
+    return 0;
+}
+
+/*
+ * TX routine for stream sockets (TCP). The data to send is pointed
+ * by ns_tx.
+ * Keep sending mbufs until socket says that it can't take anymore.
+ * then wait for send event notification before continuing.
+ */
+static int
+native_sock_stream_tx(struct native_sock *ns, int notify)
+{
+    struct native_sock_state *nss = &native_sock_state;
+    struct os_mbuf *m;
+    struct os_mbuf *n;
+    int rc;
+
+    rc = 0;
+
+    os_mutex_pend(&nss->mtx, OS_TIMEOUT_NEVER);
+    while (ns->ns_tx && rc == 0) {
+        m = ns->ns_tx;
+        n = SLIST_NEXT(m, om_next);
+        rc = write(ns->ns_fd, m->om_data, m->om_len);
+        if (rc == m->om_len) {
+            ns->ns_tx = n;
+            os_mbuf_free(m);
+            rc = 0;
+        } else {
+            rc = errno;
+        }
+    }
+    os_mutex_release(&nss->mtx);
+    if (rc) {
+        if (rc == EAGAIN) {
+            rc = 0;
+        } else {
+            rc = native_sock_err_to_mn_err(rc);
+        }
+    }
+    if (notify) {
+        if (ns->ns_tx == NULL) {
+            mn_socket_writable(&ns->ns_sock, 0);
+        } else {
+            mn_socket_writable(&ns->ns_sock, rc);
+        }
+    }
+    return rc;
+}
+
+static int
+native_sock_sendto(struct mn_socket *s, struct os_mbuf *m,
+  struct mn_sockaddr *addr)
+{
+    struct native_sock *ns = (struct native_sock *)s;
+    struct sockaddr_storage ss;
+    struct sockaddr *sa = (struct sockaddr *)&ss;
+    uint8_t tmpbuf[NATIVE_SOCK_MAX_UDP];
+    struct os_mbuf *o;
+    int sa_len;
+    int off;
+    int rc;
+
+    if (ns->ns_type == SOCK_DGRAM) {
+        rc = native_sock_mn_addr_to_addr(addr, sa, &sa_len);
+        if (rc) {
+            return rc;
+        }
+        off = 0;
+        for (o = m; o; o = SLIST_NEXT(o, om_next)) {
+            if (off + o->om_len > sizeof(tmpbuf)) {
+                return MN_ENOBUFS;
+            }
+            os_mbuf_copydata(o, 0, o->om_len, &tmpbuf[off]);
+            off += o->om_len;
+        }
+        rc = sendto(ns->ns_fd, tmpbuf, off, 0, sa, sa_len);
+        if (rc != off) {
+            return native_sock_err_to_mn_err(errno);
+        }
+        os_mbuf_free_chain(m);
+        return 0;
+    } else {
+        if (ns->ns_tx) {
+            return MN_EAGAIN;
+        }
+        ns->ns_tx = m;
+
+        rc = native_sock_stream_tx(ns, 0);
+        return rc;
+    }
+}
+
+static int
+native_sock_recvfrom(struct mn_socket *s, struct os_mbuf **mp,
+  struct mn_sockaddr *addr)
+{
+    struct native_sock *ns = (struct native_sock *)s;
+    struct sockaddr_storage ss;
+    struct sockaddr *sa = (struct sockaddr *)&ss;
+    uint8_t tmpbuf[NATIVE_SOCK_MAX_UDP];
+    struct os_mbuf *m;
+    socklen_t slen;
+    int rc;
+
+    slen = sizeof(ss);
+    if (ns->ns_type == SOCK_DGRAM) {
+        rc = recvfrom(ns->ns_fd, tmpbuf, sizeof(tmpbuf), 0, sa, &slen);
+    } else {
+        rc = getpeername(ns->ns_fd, sa, &slen);
+        if (rc == 0) {
+            rc = read(ns->ns_fd, tmpbuf, sizeof(tmpbuf));
+        }
+    }
+    if (rc < 0) {
+        return native_sock_err_to_mn_err(errno);
+    }
+    if (ns->ns_type == SOCK_STREAM && rc == 0) {
+        mn_socket_readable(&ns->ns_sock, MN_ECONNABORTED);
+        ns->ns_poll = 0;
+        native_sock_poll_rebuild(&native_sock_state);
+        return MN_ECONNABORTED;
+    }
+
+    m = os_msys_get_pkthdr(rc, 0);
+    if (!m) {
+        return MN_ENOBUFS;
+    }
+    os_mbuf_copyinto(m, 0, tmpbuf, rc);
+    *mp = m;
+    if (addr) {
+        native_sock_addr_to_mn_addr(sa, addr);
+    }
+    return 0;
+}
+
+static int
+native_sock_getsockopt(struct mn_socket *s, uint8_t level, uint8_t name,
+  void *val)
+{
+    return MN_EPROTONOSUPPORT;
+}
+
+static int
+native_sock_setsockopt(struct mn_socket *s, uint8_t level, uint8_t name,
+  void *val)
+{
+    struct native_sock *ns = (struct native_sock *)s;
+    int rc;
+    uint32_t val32;
+    struct group_req greq;
+    struct sockaddr_in *sin;
+    struct sockaddr_in6 *sin6;
+    struct mn_mreq *mreq;
+
+    if (level == MN_SO_LEVEL) {
+        switch (name) {
+        case MN_MCAST_JOIN_GROUP:
+        case MN_MCAST_LEAVE_GROUP:
+            mreq = val;
+            memset(&greq, 0, sizeof(greq));
+            greq.gr_interface = mreq->mm_idx;
+            if (mreq->mm_family == MN_AF_INET) {
+                sin = (struct sockaddr_in *)&greq.gr_group;
+#ifndef MN_LINUX
+                sin->sin_len = sizeof(*sin);
+#endif
+                sin->sin_family = AF_INET;
+                memcpy(&sin->sin_addr, &mreq->mm_addr, sizeof(struct in_addr));
+                level = IPPROTO_IP;
+            } else {
+                sin6 = (struct sockaddr_in6 *)&greq.gr_group;
+#ifndef MN_LINUX
+                sin6->sin6_len = sizeof(*sin6);
+#endif
+                sin6->sin6_family = AF_INET6;
+                memcpy(&sin6->sin6_addr, &mreq->mm_addr,
+                  sizeof(struct in6_addr));
+                level = IPPROTO_IPV6;
+            }
+
+            if (name == MN_MCAST_JOIN_GROUP) {
+                name = MCAST_JOIN_GROUP;
+            } else {
+                name = MCAST_LEAVE_GROUP;
+            }
+            rc = setsockopt(ns->ns_fd, level, name, &greq, sizeof(greq));
+            if (rc) {
+                return native_sock_err_to_mn_err(errno);
+            }
+            return 0;
+        case MN_MCAST_IF:
+            if (ns->ns_pf == AF_INET) {
+                level = IPPROTO_IP;
+                name = IP_MULTICAST_IF;
+                rc = native_sock_itf_addr(*(int *)val, &val32);
+                if (rc) {
+                    return rc;
+                }
+            } else {
+                level = IPPROTO_IPV6;
+                name = IPV6_MULTICAST_IF;
+                val32 = *(uint32_t *)val;
+            }
+            rc = setsockopt(ns->ns_fd, level, name, &val32, sizeof(val32));
+            if (rc) {
+                return native_sock_err_to_mn_err(errno);
+            }
+            return 0;
+        }
+    }
+    return MN_EPROTONOSUPPORT;
+}
+
+static int
+native_sock_getsockname(struct mn_socket *s, struct mn_sockaddr *addr)
+{
+    struct native_sock *ns = (struct native_sock *)s;
+    struct sockaddr_storage ss;
+    struct sockaddr *sa = (struct sockaddr *)&ss;
+    socklen_t len;
+    int rc;
+
+    len = sizeof(struct sockaddr_storage);
+    rc = getsockname(ns->ns_fd, sa, &len);
+    if (rc) {
+        return native_sock_err_to_mn_err(errno);
+    }
+    rc = native_sock_addr_to_mn_addr(sa, addr);
+    if (rc) {
+        return rc;
+    }
+    return 0;
+}
+
+static int
+native_sock_getpeername(struct mn_socket *s, struct mn_sockaddr *addr)
+{
+    struct native_sock *ns = (struct native_sock *)s;
+    struct sockaddr_storage ss;
+    struct sockaddr *sa = (struct sockaddr *)&ss;
+    socklen_t len;
+    int rc;
+
+    len = sizeof(struct sockaddr_storage);
+    rc = getpeername(ns->ns_fd, sa, &len);
+    if (rc) {
+        return native_sock_err_to_mn_err(errno);
+    }
+    rc = native_sock_addr_to_mn_addr(sa, addr);
+    if (rc) {
+        return rc;
+    }
+    return 0;
+}
+
+/*
+ * XXX should do this task with SIGIO as well.
+ */
+static void
+socket_task(void *arg)
+{
+    struct native_sock_state *nss = arg;
+    struct native_sock *ns, *new_ns;
+    struct sockaddr_storage ss;
+    struct sockaddr *sa = (struct sockaddr *)&ss;
+    int i;
+    socklen_t slen;
+    int rc;
+
+    os_mutex_pend(&nss->mtx, OS_WAIT_FOREVER);
+    while (1) {
+        os_mutex_release(&nss->mtx);
+        os_time_delay(NATIVE_SOCK_POLL_ITVL);
+        os_mutex_pend(&nss->mtx, OS_WAIT_FOREVER);
+        if (nss->poll_fd_cnt) {
+            rc = poll(nss->poll_fds, nss->poll_fd_cnt, 0);
+        } else {
+            rc = 0;
+        }
+        if (rc == 0) {
+            continue;
+        }
+        for (i = 0; i < nss->poll_fd_cnt; i++) {
+            if (!nss->poll_fds[i].revents) {
+                continue;
+            }
+            nss->poll_fds[i].revents = 0;
+            ns = native_find_sock(nss->poll_fds[i].fd);
+            assert(ns);
+            if (ns->ns_listen) {
+                new_ns = native_get_sock();
+                if (!new_ns) {
+                    continue;
+                }
+                slen = sizeof(ss);
+                new_ns->ns_fd = accept(ns->ns_fd, sa, &slen);
+                if (new_ns->ns_fd < 0) {
+                    continue;
+                }
+                new_ns->ns_type = ns->ns_type;
+                new_ns->ns_sock.ms_ops = &native_sock_ops;
+                os_mutex_release(&nss->mtx);
+                if (mn_socket_newconn(&ns->ns_sock, &new_ns->ns_sock)) {
+                    /*
+                     * should close
+                     */
+                }
+                os_mutex_pend(&nss->mtx, OS_WAIT_FOREVER);
+                new_ns->ns_poll = 1;
+                native_sock_poll_rebuild(nss);
+            } else {
+                mn_socket_readable(&ns->ns_sock, 0);
+            }
+        }
+    }
+}
+
+int
+native_sock_init(void)
+{
+    struct native_sock_state *nss = &native_sock_state;
+    int i;
+    os_stack_t *sp;
+
+    for (i = 0; i < NATIVE_SOCK_MAX; i++) {
+        native_socks[i].ns_fd = -1;
+        STAILQ_INIT(&native_socks[i].ns_rx);
+    }
+    sp = malloc(sizeof(os_stack_t) * SOCK_STACK_SZ);
+    if (!sp) {
+        return -1;
+    }
+    os_mutex_init(&nss->mtx);
+    i = os_task_init(&nss->task, "socket", socket_task, &native_sock_state,
+      SOCK_PRIO, OS_WAIT_FOREVER, sp, SOCK_STACK_SZ);
+    if (i) {
+        return -1;
+    }
+    i = mn_socket_ops_reg(&native_sock_ops);
+    if (i) {
+        return -1;
+    }
+
+    return 0;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/net/ip/mn_socket/src/arch/sim/native_sock_priv.h
----------------------------------------------------------------------
diff --git a/net/ip/mn_socket/src/arch/sim/native_sock_priv.h b/net/ip/mn_socket/src/arch/sim/native_sock_priv.h
new file mode 100644
index 0000000..108cbeb
--- /dev/null
+++ b/net/ip/mn_socket/src/arch/sim/native_sock_priv.h
@@ -0,0 +1,32 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 __NATIVE_SOCK_PRIV_H_
+#define __NATIVE_SOCK_PRIV_H_
+
+struct mn_itf;
+struct mn_itf_addr;
+
+int native_sock_itf_getnext(struct mn_itf *);
+int native_sock_itf_addr_getnext(struct mn_itf *, struct mn_itf_addr *);
+int native_sock_itf_addr(int idx, uint32_t *addr);
+
+int native_sock_err_to_mn_err(int err);
+
+#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/net/ip/mn_socket/src/mn_socket.c
----------------------------------------------------------------------
diff --git a/net/ip/mn_socket/src/mn_socket.c b/net/ip/mn_socket/src/mn_socket.c
new file mode 100644
index 0000000..1bf2b4c
--- /dev/null
+++ b/net/ip/mn_socket/src/mn_socket.c
@@ -0,0 +1,138 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include <inttypes.h>
+#include <assert.h>
+
+#include <os/os.h>
+
+#include "mn_socket/mn_socket.h"
+#include "mn_socket/mn_socket_ops.h"
+
+/*
+ * Currently there can be just one provider of sockets.
+ */
+static const struct mn_socket_ops *mn_sock_tgt;
+
+/** All zeros. */
+const uint32_t nm_in6addr_any[4];
+
+int
+mn_socket_ops_reg(const struct mn_socket_ops *ops)
+{
+    if (mn_sock_tgt) {
+        /*
+         * XXXX for now.
+         */
+        return -1;
+    }
+    mn_sock_tgt = ops;
+    return 0;
+}
+
+int
+mn_socket(struct mn_socket **sp, uint8_t domain, uint8_t type, uint8_t proto)
+{
+    int rc;
+
+    *sp = NULL;
+    /*
+     * XXX Look up where socket should go.
+     */
+    if (!mn_sock_tgt) {
+        return MN_EINVAL;
+    }
+    rc = mn_sock_tgt->mso_create(sp, domain, type, proto);
+    if (*sp) {
+        (*sp)->ms_ops = mn_sock_tgt;
+    }
+    return rc;
+}
+
+int
+mn_bind(struct mn_socket *s, struct mn_sockaddr *addr)
+{
+    return s->ms_ops->mso_bind(s, addr);
+}
+
+int
+mn_connect(struct mn_socket *s, struct mn_sockaddr *addr)
+{
+    return s->ms_ops->mso_connect(s, addr);
+}
+
+int
+mn_listen(struct mn_socket *s, uint8_t qlen)
+{
+    return s->ms_ops->mso_listen(s, qlen);
+}
+
+int
+mn_recvfrom(struct mn_socket *s, struct os_mbuf **mp, struct mn_sockaddr *from)
+{
+    return s->ms_ops->mso_recvfrom(s, mp, from);
+}
+
+int
+mn_sendto(struct mn_socket *s, struct os_mbuf *m, struct mn_sockaddr *to)
+{
+    return s->ms_ops->mso_sendto(s, m, to);
+}
+
+int
+mn_getsockopt(struct mn_socket *s, uint8_t level, uint8_t name, void *val)
+{
+    return s->ms_ops->mso_getsockopt(s, level, name, val);
+}
+
+int
+mn_setsockopt(struct mn_socket *s, uint8_t level, uint8_t name, void *val)
+{
+    return s->ms_ops->mso_setsockopt(s, level, name, val);
+}
+
+int
+mn_getsockname(struct mn_socket *s, struct mn_sockaddr *addr)
+{
+    return s->ms_ops->mso_getsockname(s, addr);
+}
+
+int
+mn_getpeername(struct mn_socket *s, struct mn_sockaddr *addr)
+{
+    return s->ms_ops->mso_getpeername(s, addr);
+}
+
+int
+mn_close(struct mn_socket *s)
+{
+    return s->ms_ops->mso_close(s);
+}
+
+int
+mn_itf_getnext(struct mn_itf *mi)
+{
+    return mn_sock_tgt->mso_itf_getnext(mi);
+}
+
+int
+mn_itf_addr_getnext(struct mn_itf *mi, struct mn_itf_addr *mia)
+{
+    return mn_sock_tgt->mso_itf_addr_getnext(mi, mia);
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/net/ip/mn_socket/src/mn_socket_aconv.c
----------------------------------------------------------------------
diff --git a/net/ip/mn_socket/src/mn_socket_aconv.c b/net/ip/mn_socket/src/mn_socket_aconv.c
new file mode 100644
index 0000000..7e48d65
--- /dev/null
+++ b/net/ip/mn_socket/src/mn_socket_aconv.c
@@ -0,0 +1,98 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+#include <ctype.h>
+#include <stdio.h>
+#include <os/endian.h>
+#include "mn_socket/mn_socket.h"
+
+int
+mn_inet_pton(int af, const char *src, void *dst)
+{
+    const char *ch_src;
+    uint8_t *ch_tgt;
+    int val;
+    int cnt;
+
+    if (af == MN_PF_INET) {
+        cnt = 0;
+        ch_tgt = dst;
+        val = 0;
+        for (ch_src = src; *ch_src; ch_src++) {
+            if (cnt > 4) {
+                return 0;
+            }
+            if (isdigit(*ch_src)) {
+                val = val * 10 + *ch_src - '0';
+                if (val > 255) {
+                    return 0;
+                }
+                *ch_tgt = val;
+            } else if (*ch_src == '.') {
+                ++cnt;
+                val = 0;
+                ch_tgt++;
+            } else {
+                return 0;
+            }
+        }
+        return 1;
+    } else {
+        /*
+         * Add code here. XXX
+         */
+        return 0;
+    }
+}
+
+const char *
+mn_inet_ntop(int af, const void *src_v, void *dst, int len)
+{
+    const unsigned char *src = src_v;
+    const struct mn_in6_addr *a6;
+    int rc;
+    int i;
+
+    if (af == MN_PF_INET) {
+        rc = snprintf(dst, len, "%u.%u.%u.%u",
+          src[0], src[1], src[2], src[3]);
+        if (rc >= len) {
+            return NULL;
+        } else {
+            return dst;
+        }
+    } else {
+        a6 = src_v;
+        rc = 0;
+
+        for (i = 0; i < sizeof(*a6); i += 2) {
+            rc += snprintf(dst + rc, len - rc, "%x",
+              htons(*(uint16_t *)&a6->s_addr[i]));
+            if (rc >= len) {
+                return NULL;
+            }
+            if (i < sizeof(*a6) - 2) {
+                rc += snprintf(dst + rc, len - rc, ":");
+                if (rc >= len) {
+                    return NULL;
+                }
+            }
+        }
+        return dst;
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/net/ip/mn_socket/test/pkg.yml
----------------------------------------------------------------------
diff --git a/net/ip/mn_socket/test/pkg.yml b/net/ip/mn_socket/test/pkg.yml
new file mode 100644
index 0000000..b46d24c
--- /dev/null
+++ b/net/ip/mn_socket/test/pkg.yml
@@ -0,0 +1,30 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+#
+pkg.name: sys/mn_socket/test
+pkg.type: unittest
+pkg.description: "Mynewt socket unit tests."
+pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
+pkg.homepage: "http://mynewt.apache.org/"
+pkg.keywords:
+
+pkg.deps: 
+    - libs/testutil
+    - sys/mn_socket
+
+pkg.deps.SELFTEST:
+    - libs/console/stub

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/net/ip/mn_socket/test/src/mn_sock_test.c
----------------------------------------------------------------------
diff --git a/net/ip/mn_socket/test/src/mn_sock_test.c b/net/ip/mn_socket/test/src/mn_sock_test.c
new file mode 100644
index 0000000..39acd2b
--- /dev/null
+++ b/net/ip/mn_socket/test/src/mn_sock_test.c
@@ -0,0 +1,895 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include <stdio.h>
+#include <string.h>
+
+#include "syscfg/syscfg.h"
+#include "os/os.h"
+#include "testutil/testutil.h"
+
+#include "mn_socket/mn_socket.h"
+#include "mn_socket/arch/sim/native_sock.h"
+
+#define TEST_STACK_SIZE 4096
+#define TEST_PRIO 22
+static os_stack_t test_stack[OS_STACK_ALIGN(TEST_STACK_SIZE)];
+static struct os_task test_task;
+
+static struct os_sem test_sem;
+
+#define MB_CNT 10
+#define MB_SZ  512
+static uint8_t test_mbuf_area[MB_CNT * MB_SZ];
+static struct os_mempool test_mbuf_mpool;
+static struct os_mbuf_pool test_mbuf_pool;
+
+TEST_CASE(inet_pton_test)
+{
+    int rc;
+    uint8_t addr[8];
+    struct test_vec {
+        char *str;
+        uint8_t cmp[4];
+    };
+    struct test_vec ok_vec[] = {
+        { "1.1.1.1", { 1, 1, 1, 1 } },
+        { "1.2.3.4", { 1, 2, 3, 4 } },
+        { "010.001.255.255", { 10, 1, 255, 255 } },
+        { "001.002.005.006", { 1, 2, 5, 6 } }
+    };
+    struct test_vec invalid_vec[] = {
+        { "a.b.c.d" },
+        { "1a.b3.4.2" },
+        { "1.3.4.2a" },
+        { "1111.3.4.2" },
+        { "3.256.1.0" },
+    };
+    int i;
+
+    for (i = 0; i < sizeof(ok_vec) / sizeof(ok_vec[0]); i++) {
+        memset(addr, 0xa5, sizeof(addr));
+        rc = mn_inet_pton(MN_PF_INET, ok_vec[i].str, addr);
+        TEST_ASSERT(rc == 1);
+        TEST_ASSERT(!memcmp(ok_vec[i].cmp, addr, sizeof(uint32_t)));
+        TEST_ASSERT(addr[5] == 0xa5);
+    }
+    for (i = 0; i < sizeof(invalid_vec) / sizeof(invalid_vec[0]); i++) {
+        rc = mn_inet_pton(MN_PF_INET, invalid_vec[i].str, addr);
+        TEST_ASSERT(rc == 0);
+    }
+}
+
+TEST_CASE(inet_ntop_test)
+{
+    const char *rstr;
+    char addr[48];
+    struct test_vec {
+        char *str;
+        uint8_t cmp[4];
+    };
+    struct test_vec ok_vec[] = {
+        { "1.1.1.1", { 1, 1, 1, 1 } },
+        { "1.2.3.4", { 1, 2, 3, 4 } },
+        { "255.1.255.255", { 255, 1, 255, 255 } },
+        { "1.2.5.6", { 1, 2, 5, 6 } }
+    };
+    int i;
+
+    for (i = 0; i < sizeof(ok_vec) / sizeof(ok_vec[0]); i++) {
+        memset(addr, 0xa5, sizeof(addr));
+        rstr = mn_inet_ntop(MN_PF_INET, ok_vec[i].cmp, addr, sizeof(addr));
+        TEST_ASSERT(rstr);
+        TEST_ASSERT(!strcmp(ok_vec[i].str, addr));
+    }
+    rstr = mn_inet_ntop(MN_PF_INET, ok_vec[0].cmp, addr, 1);
+    TEST_ASSERT(rstr == NULL);
+
+    /* does not have space to null terminate */
+    rstr = mn_inet_ntop(MN_PF_INET, ok_vec[0].cmp, addr, 7);
+    TEST_ASSERT(rstr == NULL);
+}
+
+void
+sock_open_close(void)
+{
+    struct mn_socket *sock;
+    int rc;
+
+    rc = mn_socket(&sock, MN_PF_INET, MN_SOCK_DGRAM, 0);
+    TEST_ASSERT(sock);
+    TEST_ASSERT(rc == 0);
+    mn_close(sock);
+
+    rc = mn_socket(&sock, MN_PF_INET, MN_SOCK_STREAM, 0);
+    TEST_ASSERT(sock);
+    TEST_ASSERT(rc == 0);
+    mn_close(sock);
+
+    rc = mn_socket(&sock, MN_PF_INET6, MN_SOCK_DGRAM, 0);
+    TEST_ASSERT(sock);
+    TEST_ASSERT(rc == 0);
+    mn_close(sock);
+
+    rc = mn_socket(&sock, MN_PF_INET6, MN_SOCK_STREAM, 0);
+    TEST_ASSERT(sock);
+    TEST_ASSERT(rc == 0);
+    mn_close(sock);
+}
+
+void
+sock_listen(void)
+{
+    struct mn_socket *sock;
+    struct mn_sockaddr_in msin;
+    int rc;
+
+    rc = mn_socket(&sock, MN_PF_INET, MN_SOCK_STREAM, 0);
+    TEST_ASSERT(rc == 0);
+
+    msin.msin_family = MN_PF_INET;
+    msin.msin_len = sizeof(msin);
+    msin.msin_port = htons(12444);
+
+    mn_inet_pton(MN_PF_INET, "127.0.0.1", &msin.msin_addr);
+
+    rc = mn_bind(sock, (struct mn_sockaddr *)&msin);
+    TEST_ASSERT(rc == 0);
+
+    rc = mn_listen(sock, 2);
+    TEST_ASSERT(rc == 0);
+
+    mn_close(sock);
+}
+
+void
+stc_writable(void *cb_arg, int err)
+{
+    int *i;
+
+    TEST_ASSERT(err == 0);
+    i = (int *)cb_arg;
+    *i = *i + 1;
+}
+
+int
+stc_newconn(void *cb_arg, struct mn_socket *new)
+{
+    struct mn_socket **r_sock;
+
+    r_sock = cb_arg;
+    *r_sock = new;
+
+    os_sem_release(&test_sem);
+    return 0;
+}
+
+void
+sock_tcp_connect(void)
+{
+    struct mn_socket *listen_sock;
+    struct mn_socket *sock;
+    struct mn_sockaddr_in msin;
+    struct mn_sockaddr_in msin2;
+    int rc;
+    union mn_socket_cb listen_cbs = {
+        .listen.newconn = stc_newconn,
+    };
+    union mn_socket_cb sock_cbs = {
+        .socket.writable = stc_writable
+    };
+    int connected = 0;
+    struct mn_socket *new_sock = NULL;
+
+    rc = mn_socket(&listen_sock, MN_PF_INET, MN_SOCK_STREAM, 0);
+    TEST_ASSERT(rc == 0);
+
+    msin.msin_family = MN_PF_INET;
+    msin.msin_len = sizeof(msin);
+    msin.msin_port = htons(12445);
+
+    mn_inet_pton(MN_PF_INET, "127.0.0.1", &msin.msin_addr);
+
+    mn_socket_set_cbs(listen_sock, &new_sock, &listen_cbs);
+    rc = mn_bind(listen_sock, (struct mn_sockaddr *)&msin);
+    TEST_ASSERT(rc == 0);
+
+    rc = mn_listen(listen_sock, 2);
+    TEST_ASSERT(rc == 0);
+
+    rc = mn_socket(&sock, MN_PF_INET, MN_SOCK_STREAM, 0);
+    TEST_ASSERT(rc == 0);
+
+    mn_socket_set_cbs(sock, &connected, &sock_cbs);
+
+    rc = mn_connect(sock, (struct mn_sockaddr *)&msin);
+    TEST_ASSERT(rc == 0);
+
+    rc = os_sem_pend(&test_sem, OS_TICKS_PER_SEC);
+    TEST_ASSERT(rc == 0);
+    TEST_ASSERT(connected == 1);
+    TEST_ASSERT(new_sock != NULL);
+
+    /*
+     * Check endpoint data matches
+     */
+    rc = mn_getsockname(sock, (struct mn_sockaddr *)&msin);
+    TEST_ASSERT(rc == 0);
+    rc = mn_getpeername(new_sock, (struct mn_sockaddr *)&msin2);
+    TEST_ASSERT(rc == 0);
+    TEST_ASSERT(!memcmp(&msin, &msin2, sizeof(msin)));
+
+    rc = mn_getsockname(new_sock, (struct mn_sockaddr *)&msin);
+    TEST_ASSERT(rc == 0);
+    rc = mn_getpeername(sock, (struct mn_sockaddr *)&msin2);
+    TEST_ASSERT(rc == 0);
+    TEST_ASSERT(!memcmp(&msin, &msin2, sizeof(msin)));
+
+
+    if (new_sock) {
+        mn_close(new_sock);
+    }
+    mn_close(sock);
+    mn_close(listen_sock);
+}
+
+void
+sud_readable(void *cb_arg, int err)
+{
+    os_sem_release(&test_sem);
+}
+
+void
+sock_udp_data(void)
+{
+    struct mn_socket *sock1;
+    struct mn_socket *sock2;
+    struct mn_sockaddr_in msin;
+    struct mn_sockaddr_in msin2;
+    int rc;
+    union mn_socket_cb sock_cbs = {
+        .socket.readable = sud_readable
+    };
+    struct os_mbuf *m;
+    char data[] = "1234567890";
+
+    rc = mn_socket(&sock1, MN_PF_INET, MN_SOCK_DGRAM, 0);
+    TEST_ASSERT(rc == 0);
+    mn_socket_set_cbs(sock1, NULL, &sock_cbs);
+
+    rc = mn_socket(&sock2, MN_PF_INET, MN_SOCK_DGRAM, 0);
+    TEST_ASSERT(rc == 0);
+    mn_socket_set_cbs(sock2, NULL, &sock_cbs);
+
+    msin.msin_family = MN_PF_INET;
+    msin.msin_len = sizeof(msin);
+    msin.msin_port = htons(12445);
+
+    mn_inet_pton(MN_PF_INET, "127.0.0.1", &msin.msin_addr);
+
+    rc = mn_bind(sock1, (struct mn_sockaddr *)&msin);
+    TEST_ASSERT(rc == 0);
+
+    msin2.msin_family = MN_PF_INET;
+    msin2.msin_len = sizeof(msin2);
+    msin2.msin_port = 0;
+    msin2.msin_addr.s_addr = 0;
+    rc = mn_bind(sock2, (struct mn_sockaddr *)&msin2);
+    TEST_ASSERT(rc == 0);
+
+    m = os_msys_get(sizeof(data), 0);
+    TEST_ASSERT(m);
+    rc = os_mbuf_copyinto(m, 0, data, sizeof(data));
+    TEST_ASSERT(rc == 0);
+    rc = mn_sendto(sock2, (struct os_mbuf *)m, (struct mn_sockaddr *)&msin);
+    TEST_ASSERT(rc == 0);
+
+    /*
+     * Wait for the packet.
+     */
+    rc = os_sem_pend(&test_sem, OS_TICKS_PER_SEC);
+    TEST_ASSERT(rc == 0);
+
+    rc = mn_recvfrom(sock1, &m, (struct mn_sockaddr *)&msin2);
+    TEST_ASSERT(rc == 0);
+    TEST_ASSERT(m != NULL);
+    TEST_ASSERT(msin2.msin_family == MN_AF_INET);
+    TEST_ASSERT(msin2.msin_len == sizeof(msin2));
+    TEST_ASSERT(msin2.msin_port != 0);
+    TEST_ASSERT(msin2.msin_addr.s_addr != 0);
+
+    if (m) {
+        TEST_ASSERT(OS_MBUF_IS_PKTHDR(m));
+        TEST_ASSERT(OS_MBUF_PKTLEN(m) == sizeof(data));
+        TEST_ASSERT(m->om_len == sizeof(data));
+        TEST_ASSERT(!memcmp(m->om_data, data, sizeof(data)));
+    }
+
+    rc = mn_sendto(sock1, m, (struct mn_sockaddr *)&msin2);
+    TEST_ASSERT(rc == 0);
+
+    rc = os_sem_pend(&test_sem, OS_TICKS_PER_SEC);
+    TEST_ASSERT(rc == 0);
+
+    rc = mn_recvfrom(sock2, &m, (struct mn_sockaddr *)&msin2);
+    TEST_ASSERT(rc == 0);
+    TEST_ASSERT(m != NULL);
+    if (m) {
+        TEST_ASSERT(OS_MBUF_IS_PKTHDR(m));
+        TEST_ASSERT(OS_MBUF_PKTLEN(m) == sizeof(data));
+        TEST_ASSERT(m->om_len == sizeof(data));
+        TEST_ASSERT(!memcmp(m->om_data, data, sizeof(data)));
+        os_mbuf_free_chain(m);
+    }
+
+    mn_close(sock1);
+    mn_close(sock2);
+}
+
+void
+std_writable(void *cb_arg, int err)
+{
+    int *i;
+
+    TEST_ASSERT(err == 0);
+    i = (int *)cb_arg;
+    if (i) {
+        *i = *i + 1;
+    }
+}
+
+void
+std_readable(void *cb_arg, int err)
+{
+    os_sem_release(&test_sem);
+}
+
+static union mn_socket_cb sud_sock_cbs = {
+    .socket.writable = std_writable,
+    .socket.readable = std_readable
+};
+
+int
+std_newconn(void *cb_arg, struct mn_socket *new)
+{
+    struct mn_socket **r_sock;
+
+    r_sock = cb_arg;
+    *r_sock = new;
+
+    mn_socket_set_cbs(new, NULL, &sud_sock_cbs);
+
+    os_sem_release(&test_sem);
+    return 0;
+}
+
+void
+sock_tcp_data(void)
+{
+    struct mn_socket *listen_sock;
+    struct mn_socket *sock;
+    struct mn_sockaddr_in msin;
+    int rc;
+    union mn_socket_cb listen_cbs = {
+        .listen.newconn = std_newconn,
+    };
+    int connected = 0;
+    struct mn_socket *new_sock = NULL;
+    struct os_mbuf *m;
+    char data[] = "1234567890";
+
+    rc = mn_socket(&listen_sock, MN_PF_INET, MN_SOCK_STREAM, 0);
+    TEST_ASSERT(rc == 0);
+
+    msin.msin_family = MN_PF_INET;
+    msin.msin_len = sizeof(msin);
+    msin.msin_port = htons(12447);
+
+    mn_inet_pton(MN_PF_INET, "127.0.0.1", &msin.msin_addr);
+
+    mn_socket_set_cbs(listen_sock, &new_sock, &listen_cbs);
+    rc = mn_bind(listen_sock, (struct mn_sockaddr *)&msin);
+    TEST_ASSERT(rc == 0);
+
+    rc = mn_listen(listen_sock, 2);
+    TEST_ASSERT(rc == 0);
+
+    rc = mn_socket(&sock, MN_PF_INET, MN_SOCK_STREAM, 0);
+    TEST_ASSERT(rc == 0);
+
+    mn_socket_set_cbs(sock, &connected, &sud_sock_cbs);
+
+    rc = mn_connect(sock, (struct mn_sockaddr *)&msin);
+    TEST_ASSERT(rc == 0);
+
+    rc = os_sem_pend(&test_sem, OS_TICKS_PER_SEC);
+    TEST_ASSERT(rc == 0);
+    TEST_ASSERT(connected == 1);
+    TEST_ASSERT(new_sock != NULL);
+
+    m = os_msys_get(sizeof(data), 0);
+    TEST_ASSERT(m);
+    rc = os_mbuf_copyinto(m, 0, data, sizeof(data));
+    TEST_ASSERT(rc == 0);
+    rc = mn_sendto(new_sock, (struct os_mbuf *)m, (struct mn_sockaddr *)&msin);
+    TEST_ASSERT(rc == 0);
+
+    /*
+     * Wait for the packet.
+     */
+    rc = os_sem_pend(&test_sem, OS_TICKS_PER_SEC);
+    TEST_ASSERT(rc == 0);
+
+    memset(&msin, 0, sizeof(msin));
+    rc = mn_recvfrom(sock, &m, (struct mn_sockaddr *)&msin);
+    TEST_ASSERT(rc == 0);
+    TEST_ASSERT(m != NULL);
+    TEST_ASSERT(msin.msin_family == MN_AF_INET);
+    TEST_ASSERT(msin.msin_len == sizeof(msin));
+    TEST_ASSERT(msin.msin_port != 0);
+    TEST_ASSERT(msin.msin_addr.s_addr != 0);
+    os_mbuf_free_chain(m);
+
+    if (new_sock) {
+        mn_close(new_sock);
+    }
+    mn_close(sock);
+    mn_close(listen_sock);
+}
+
+void
+sock_itf_list(void)
+{
+    struct mn_itf itf;
+    struct mn_itf_addr itf_addr;
+    int if_cnt = 0;
+    int seen_127;
+    struct mn_in_addr addr127;
+    char addr_str[64];
+    int rc;
+
+    mn_inet_pton(MN_PF_INET, "127.0.0.1", &addr127);
+
+    memset(&itf, 0, sizeof(itf));
+
+    while (1) {
+        rc = mn_itf_getnext(&itf);
+        if (rc) {
+            break;
+        }
+        printf("%d: %x %s\n", itf.mif_idx, itf.mif_flags, itf.mif_name);
+        memset(&itf_addr, 0, sizeof(itf_addr));
+        while (1) {
+            rc = mn_itf_addr_getnext(&itf, &itf_addr);
+            if (rc) {
+                break;
+            }
+            if (itf_addr.mifa_family == MN_AF_INET &&
+              !memcmp(&itf_addr.mifa_addr, &addr127, sizeof(addr127))) {
+                seen_127 = 1;
+            }
+            addr_str[0] = '\0';
+            mn_inet_ntop(itf_addr.mifa_family, &itf_addr.mifa_addr,
+              addr_str, sizeof(addr_str));
+            printf(" %s/%d\n", addr_str, itf_addr.mifa_plen);
+        }
+        if_cnt++;
+    }
+    TEST_ASSERT(if_cnt > 0);
+    TEST_ASSERT(seen_127);
+}
+
+static int
+first_ll_addr(struct mn_sockaddr_in6 *ra)
+{
+    struct mn_itf itf;
+    struct mn_itf_addr itf_addr;
+    int rc;
+    struct mn_in6_addr *addr;
+
+    memset(&itf, 0, sizeof(itf));
+    addr = (struct mn_in6_addr *)&itf_addr.mifa_addr;
+    while (1) {
+        rc = mn_itf_getnext(&itf);
+        if (rc) {
+            break;
+        }
+        memset(&itf_addr, 0, sizeof(itf_addr));
+        while (1) {
+            rc = mn_itf_addr_getnext(&itf, &itf_addr);
+            if (rc) {
+                break;
+            }
+            if (itf_addr.mifa_family == MN_AF_INET6 &&
+              addr->s_addr[0] == 0xfe && addr->s_addr[1] == 0x80) {
+                memset(ra, 0, sizeof(*ra));
+                ra->msin6_family = MN_AF_INET6;
+                ra->msin6_len = sizeof(*ra);
+                ra->msin6_scope_id = itf.mif_idx;
+                memcpy(&ra->msin6_addr, addr, sizeof(*addr));
+                return 0;
+            }
+        }
+    }
+    return -1;
+}
+
+void
+sul_readable(void *cb_arg, int err)
+{
+    os_sem_release(&test_sem);
+}
+
+void
+sock_udp_ll(void)
+{
+    struct mn_socket *sock1;
+    struct mn_socket *sock2;
+    struct mn_sockaddr_in6 msin;
+    struct mn_sockaddr_in6 msin2;
+    int rc;
+    union mn_socket_cb sock_cbs = {
+        .socket.readable = sul_readable
+    };
+    struct os_mbuf *m;
+    char data[] = "1234567890";
+
+    rc = mn_socket(&sock1, MN_PF_INET6, MN_SOCK_DGRAM, 0);
+    TEST_ASSERT(rc == 0);
+    mn_socket_set_cbs(sock1, NULL, &sock_cbs);
+
+    rc = mn_socket(&sock2, MN_PF_INET6, MN_SOCK_DGRAM, 0);
+    TEST_ASSERT(rc == 0);
+    mn_socket_set_cbs(sock2, NULL, &sock_cbs);
+
+    rc = first_ll_addr(&msin);
+    if (rc != 0) {
+        printf("No ipv6 address present?\n");
+        return;
+    }
+    msin.msin6_port = htons(12445);
+
+    rc = mn_bind(sock1, (struct mn_sockaddr *)&msin);
+    TEST_ASSERT(rc == 0);
+
+    rc = mn_getsockname(sock1, (struct mn_sockaddr *)&msin2);
+    TEST_ASSERT(rc == 0);
+
+    m = os_msys_get(sizeof(data), 0);
+    TEST_ASSERT(m);
+    rc = os_mbuf_copyinto(m, 0, data, sizeof(data));
+    TEST_ASSERT(rc == 0);
+    rc = mn_sendto(sock2, (struct os_mbuf *)m, (struct mn_sockaddr *)&msin2);
+    TEST_ASSERT(rc == 0);
+
+    /*
+     * Wait for the packet.
+     */
+    rc = os_sem_pend(&test_sem, OS_TICKS_PER_SEC);
+    TEST_ASSERT(rc == 0);
+
+    rc = mn_recvfrom(sock1, &m, (struct mn_sockaddr *)&msin);
+    TEST_ASSERT(rc == 0);
+    TEST_ASSERT(m != NULL);
+
+    if (m) {
+        TEST_ASSERT(OS_MBUF_IS_PKTHDR(m));
+        TEST_ASSERT(OS_MBUF_PKTLEN(m) == sizeof(data));
+        TEST_ASSERT(m->om_len == sizeof(data));
+        TEST_ASSERT(!memcmp(m->om_data, data, sizeof(data)));
+        os_mbuf_free_chain(m);
+    }
+
+    mn_close(sock1);
+    mn_close(sock2);
+}
+
+static int
+sock_find_multicast_if(void)
+{
+    struct mn_itf itf;
+
+    memset(&itf, 0, sizeof(itf));
+
+    while (1) {
+        if (mn_itf_getnext(&itf)) {
+            break;
+        }
+        if ((itf.mif_flags & MN_ITF_F_UP) == 0) {
+            continue;
+        }
+        if (itf.mif_flags & MN_ITF_F_MULTICAST) {
+            return itf.mif_idx;
+        }
+    }
+    return -1;
+}
+
+void
+sum4_readable(void *cb_arg, int err)
+{
+    os_sem_release(&test_sem);
+}
+
+static void
+sock_udp_mcast_v4(void)
+{
+    int loop_if_idx;
+    struct mn_socket *rx_sock;
+    struct mn_socket *tx_sock;
+    struct mn_sockaddr_in msin;
+    union mn_socket_cb sock_cbs = {
+        .socket.readable = sum4_readable
+    };
+    struct os_mbuf *m;
+    char data[] = "1234567890";
+    int rc;
+    struct mn_mreq mreq;
+    loop_if_idx = sock_find_multicast_if();
+    TEST_ASSERT(loop_if_idx > 0);
+
+    msin.msin_family = MN_AF_INET;
+    msin.msin_len = sizeof(msin);
+    msin.msin_port = htons(44344);
+    memset(&msin.msin_addr, 0, sizeof(msin.msin_addr));
+
+    rc = mn_socket(&rx_sock, MN_PF_INET, MN_SOCK_DGRAM, 0);
+    TEST_ASSERT(rc == 0);
+    mn_socket_set_cbs(rx_sock, NULL, &sock_cbs);
+
+    rc = mn_bind(rx_sock, (struct mn_sockaddr *)&msin);
+    TEST_ASSERT(rc == 0);
+
+    rc = mn_socket(&tx_sock, MN_PF_INET, MN_SOCK_DGRAM, 0);
+    TEST_ASSERT(rc == 0);
+
+    rc = mn_setsockopt(tx_sock, MN_SO_LEVEL, MN_MCAST_IF, &loop_if_idx);
+    TEST_ASSERT(rc == 0);
+
+    m = os_msys_get(sizeof(data), 0);
+    rc = os_mbuf_copyinto(m, 0, data, sizeof(data));
+    TEST_ASSERT(rc == 0);
+
+    /*
+     * multicast tgt
+     */
+    mn_inet_pton(MN_PF_INET, "224.0.2.241", &msin.msin_addr);
+
+    rc = mn_sendto(tx_sock, (struct os_mbuf *)m, (struct mn_sockaddr *)&msin);
+    TEST_ASSERT(rc == 0);
+
+    /*
+     * RX socket has not joined group yet.
+     */
+    rc = os_sem_pend(&test_sem, OS_TICKS_PER_SEC / 2);
+    TEST_ASSERT(rc == OS_TIMEOUT);
+
+    mreq.mm_idx = loop_if_idx;
+    mreq.mm_family = MN_AF_INET;
+    mreq.mm_addr.v4.s_addr = msin.msin_addr.s_addr;
+
+    /*
+     * Now join it.
+     */
+    rc = mn_setsockopt(rx_sock, MN_SO_LEVEL, MN_MCAST_JOIN_GROUP, &mreq);
+    TEST_ASSERT(rc == 0);
+
+    m = os_msys_get(sizeof(data), 0);
+    rc = os_mbuf_copyinto(m, 0, data, sizeof(data));
+    TEST_ASSERT(rc == 0);
+
+    rc = mn_sendto(tx_sock, (struct os_mbuf *)m, (struct mn_sockaddr *)&msin);
+    TEST_ASSERT(rc == 0);
+
+    rc = os_sem_pend(&test_sem, OS_TICKS_PER_SEC);
+    TEST_ASSERT(rc == 0);
+
+    rc = mn_recvfrom(rx_sock, &m, NULL);
+    TEST_ASSERT(rc == 0);
+    TEST_ASSERT(m != NULL);
+    TEST_ASSERT(!memcmp(m->om_data, data, sizeof(data)));
+    os_mbuf_free_chain(m);
+
+    /*
+     * Then leave
+     */
+    rc = mn_setsockopt(rx_sock, MN_SO_LEVEL, MN_MCAST_LEAVE_GROUP, &mreq);
+    TEST_ASSERT(rc == 0);
+
+    m = os_msys_get(sizeof(data), 0);
+    TEST_ASSERT(m);
+    rc = os_mbuf_copyinto(m, 0, data, sizeof(data));
+    TEST_ASSERT(rc == 0);
+
+    rc = mn_sendto(tx_sock, (struct os_mbuf *)m, (struct mn_sockaddr *)&msin);
+    TEST_ASSERT(rc == 0);
+
+    rc = os_sem_pend(&test_sem, OS_TICKS_PER_SEC);
+    TEST_ASSERT(rc == OS_TIMEOUT);
+
+    mn_close(rx_sock);
+    mn_close(tx_sock);
+}
+
+static void
+sock_udp_mcast_v6(void)
+{
+    int loop_if_idx;
+    struct mn_socket *rx_sock;
+    struct mn_socket *tx_sock;
+    struct mn_sockaddr_in6 msin6;
+    union mn_socket_cb sock_cbs = {
+        .socket.readable = sum4_readable
+    };
+    struct os_mbuf *m;
+    char data[] = "1234567890";
+    int rc;
+    struct mn_mreq mreq;
+    uint8_t mcast_addr[16] = {
+        0xff, 2, 0, 0,
+        0, 0, 0, 0,
+        0, 0, 0, 0,
+        0, 0, 0, 2
+    };
+
+    loop_if_idx = sock_find_multicast_if();
+    TEST_ASSERT(loop_if_idx > 0);
+
+    msin6.msin6_family = MN_AF_INET6;
+    msin6.msin6_len = sizeof(msin6);
+    msin6.msin6_port = htons(44344);
+    memset(&msin6.msin6_addr, 0, sizeof(msin6.msin6_addr));
+
+    rc = mn_socket(&rx_sock, MN_PF_INET6, MN_SOCK_DGRAM, 0);
+    TEST_ASSERT(rc == 0);
+    mn_socket_set_cbs(rx_sock, NULL, &sock_cbs);
+
+    rc = mn_bind(rx_sock, (struct mn_sockaddr *)&msin6);
+    TEST_ASSERT(rc == 0);
+
+    rc = mn_socket(&tx_sock, MN_PF_INET6, MN_SOCK_DGRAM, 0);
+    TEST_ASSERT(rc == 0);
+
+    rc = mn_setsockopt(tx_sock, MN_SO_LEVEL, MN_MCAST_IF, &loop_if_idx);
+    TEST_ASSERT(rc == 0);
+
+    m = os_msys_get(sizeof(data), 0);
+    rc = os_mbuf_copyinto(m, 0, data, sizeof(data));
+    TEST_ASSERT(rc == 0);
+
+    /*
+     * multicast tgt
+     */
+    memcpy(&msin6.msin6_addr, mcast_addr, sizeof(mcast_addr));
+
+    rc = mn_sendto(tx_sock, (struct os_mbuf *)m, (struct mn_sockaddr *)&msin6);
+    TEST_ASSERT(rc == 0);
+
+    /*
+     * RX socket has not joined group yet.
+     */
+    rc = os_sem_pend(&test_sem, OS_TICKS_PER_SEC / 2);
+    TEST_ASSERT(rc == OS_TIMEOUT);
+
+    mreq.mm_idx = loop_if_idx;
+    mreq.mm_family = MN_AF_INET6;
+    memcpy(&mreq.mm_addr.v6.s_addr, msin6.msin6_addr.s_addr,
+      sizeof(msin6.msin6_addr.s_addr));
+
+    /*
+     * Now join it.
+     */
+    rc = mn_setsockopt(rx_sock, MN_SO_LEVEL, MN_MCAST_JOIN_GROUP, &mreq);
+    TEST_ASSERT(rc == 0);
+
+    m = os_msys_get(sizeof(data), 0);
+    rc = os_mbuf_copyinto(m, 0, data, sizeof(data));
+    TEST_ASSERT(rc == 0);
+
+    rc = mn_sendto(tx_sock, (struct os_mbuf *)m, (struct mn_sockaddr *)&msin6);
+    TEST_ASSERT(rc == 0);
+
+    rc = os_sem_pend(&test_sem, OS_TICKS_PER_SEC);
+    TEST_ASSERT(rc == 0);
+
+    rc = mn_recvfrom(rx_sock, &m, NULL);
+    TEST_ASSERT(rc == 0);
+    TEST_ASSERT(m != NULL);
+    TEST_ASSERT(!memcmp(m->om_data, data, sizeof(data)));
+    os_mbuf_free_chain(m);
+
+    /*
+     * Then leave
+     */
+    rc = mn_setsockopt(rx_sock, MN_SO_LEVEL, MN_MCAST_LEAVE_GROUP, &mreq);
+    TEST_ASSERT(rc == 0);
+
+    m = os_msys_get(sizeof(data), 0);
+    TEST_ASSERT(m);
+    rc = os_mbuf_copyinto(m, 0, data, sizeof(data));
+    TEST_ASSERT(rc == 0);
+
+    rc = mn_sendto(tx_sock, (struct os_mbuf *)m, (struct mn_sockaddr *)&msin6);
+    TEST_ASSERT(rc == 0);
+
+    rc = os_sem_pend(&test_sem, OS_TICKS_PER_SEC);
+    TEST_ASSERT(rc == OS_TIMEOUT);
+
+    mn_close(rx_sock);
+    mn_close(tx_sock);
+}
+
+void
+mn_socket_test_handler(void *arg)
+{
+    sock_open_close();
+    sock_listen();
+    sock_tcp_connect();
+    sock_udp_data();
+    sock_tcp_data();
+    sock_itf_list();
+    sock_udp_ll();
+    sock_udp_mcast_v4();
+    sock_udp_mcast_v6();
+    tu_restart();
+}
+
+TEST_CASE(socket_tests)
+{
+    os_init();
+    native_sock_init();
+
+    os_sem_init(&test_sem, 0);
+
+    os_task_init(&test_task, "mn_socket_test", mn_socket_test_handler, NULL,
+      TEST_PRIO, OS_WAIT_FOREVER, test_stack, TEST_STACK_SIZE);
+    os_start();
+}
+
+TEST_SUITE(mn_socket_test_all)
+{
+    int rc;
+
+    rc = os_mempool_init(&test_mbuf_mpool, MB_CNT, MB_SZ, test_mbuf_area, "mb");
+    TEST_ASSERT(rc == 0);
+    rc = os_mbuf_pool_init(&test_mbuf_pool, &test_mbuf_mpool, MB_CNT, MB_CNT);
+    TEST_ASSERT(rc == 0);
+    rc = os_msys_register(&test_mbuf_pool);
+    TEST_ASSERT(rc == 0);
+
+    inet_pton_test();
+    inet_ntop_test();
+
+    socket_tests();
+}
+
+#if MYNEWT_VAL(SELFTEST)
+
+int
+main(int argc, char **argv)
+{
+    tu_config.tc_print_results = 1;
+    tu_init();
+
+    mn_socket_test_all();
+
+    return tu_any_failed;
+}
+#endif
+

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/net/nimble/controller/pkg.yml
----------------------------------------------------------------------
diff --git a/net/nimble/controller/pkg.yml b/net/nimble/controller/pkg.yml
index 7b5a4eb..ee5be84 100644
--- a/net/nimble/controller/pkg.yml
+++ b/net/nimble/controller/pkg.yml
@@ -30,7 +30,7 @@ pkg.req_apis:
     - ble_transport
 
 pkg.deps:
-    - libs/os
+    - kernel/os
     - sys/stats
     - net/nimble
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/net/nimble/host/pkg.yml
----------------------------------------------------------------------
diff --git a/net/nimble/host/pkg.yml b/net/nimble/host/pkg.yml
index 923c13e..97b713a 100644
--- a/net/nimble/host/pkg.yml
+++ b/net/nimble/host/pkg.yml
@@ -28,7 +28,7 @@ pkg.keywords:
 pkg.deps:
     - sys/log
     - sys/stats
-    - libs/os
+    - kernel/os
     - libs/util
     - net/nimble
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/net/nimble/host/services/bleuart/include/bleuart/bleuart.h
----------------------------------------------------------------------
diff --git a/net/nimble/host/services/bleuart/include/bleuart/bleuart.h b/net/nimble/host/services/bleuart/include/bleuart/bleuart.h
new file mode 100644
index 0000000..6639747
--- /dev/null
+++ b/net/nimble/host/services/bleuart/include/bleuart/bleuart.h
@@ -0,0 +1,34 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 _BLEUART_H_
+#define _BLEUART_H_
+
+void
+bleuart_init(void);
+int
+bleuart_svc_register(void);
+int
+bleuart_gatt_svr_init(void);
+void
+bleuart_set_conn_handle(uint16_t conn_handle);
+
+extern const uint8_t gatt_svr_svc_uart[16];
+
+#endif /* _BLEUART_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/net/nimble/host/services/bleuart/pkg.yml
----------------------------------------------------------------------
diff --git a/net/nimble/host/services/bleuart/pkg.yml b/net/nimble/host/services/bleuart/pkg.yml
new file mode 100644
index 0000000..96d4c44
--- /dev/null
+++ b/net/nimble/host/services/bleuart/pkg.yml
@@ -0,0 +1,42 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+#
+
+pkg.name: libs/bleuart
+pkg.description: BLE uart service.
+pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
+pkg.homepage: "http://mynewt.apache.org/"
+pkg.keywords:
+    - ble
+    - bluetooth
+    - uart
+
+pkg.deps:
+    - kernel/os
+    - net/nimble/host
+
+pkg.req_apis:
+    - console
+
+pkg.init_function: bleuart_init
+pkg.init_stage: 5
+
+pkg.syscfg_defs:
+    BLEUART_MAX_INPUT:
+        description: 'TBD'
+        value: 120

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/net/nimble/host/services/bleuart/src/bleuart.c
----------------------------------------------------------------------
diff --git a/net/nimble/host/services/bleuart/src/bleuart.c b/net/nimble/host/services/bleuart/src/bleuart.c
new file mode 100644
index 0000000..b7b2591
--- /dev/null
+++ b/net/nimble/host/services/bleuart/src/bleuart.c
@@ -0,0 +1,201 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include <assert.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "sysinit/sysinit.h"
+#include "host/ble_hs.h"
+#include "bleuart/bleuart.h"
+#include "os/endian.h"
+#include "console/console.h"
+
+/* ble uart attr read handle */
+uint16_t g_bleuart_attr_read_handle;
+
+/* ble uart attr write handle */
+uint16_t g_bleuart_attr_write_handle;
+
+/* Pointer to a console buffer */
+char *console_buf;
+
+uint16_t g_console_conn_handle;
+/**
+ * The vendor specific "bleuart" service consists of one write no-rsp characteristic
+ * and one notification only read charateristic
+ *     o "write no-rsp": a single-byte characteristic that can be written only
+ *       over a non-encrypted connection
+ *     o "read": a single-byte characteristic that can always be read only via
+ *       notifications
+ */
+
+/* {6E400001-B5A3-F393-E0A9-E50E24DCCA9E} */
+const uint8_t gatt_svr_svc_uart[16] = {
+    0x9e, 0xca, 0xdc, 0x24, 0x0e, 0xe5, 0xa9, 0xe0,
+    0x93, 0xf3, 0xa3, 0xb5, 0x01, 0x00, 0x40, 0x6e
+};
+
+/* {6E400002-B5A3-F393-E0A9-E50E24DCCA9E} */
+const uint8_t gatt_svr_chr_uart_write[16] = {
+    0x9e, 0xca, 0xdc, 0x24, 0x0e, 0xe5, 0xa9, 0xe0,
+    0x93, 0xf3, 0xa3, 0xb5, 0x02, 0x00, 0x40, 0x6e
+};
+
+
+/* {6E400003-B5A3-F393-E0A9-E50E24DCCA9E} */
+const uint8_t gatt_svr_chr_uart_read[16] = {
+    0x9e, 0xca, 0xdc, 0x24, 0x0e, 0xe5, 0xa9, 0xe0,
+    0x93, 0xf3, 0xa3, 0xb5, 0x03, 0x00, 0x40, 0x6e
+};
+
+static int
+gatt_svr_chr_access_uart_write(uint16_t conn_handle, uint16_t attr_handle,
+                              struct ble_gatt_access_ctxt *ctxt, void *arg);
+
+static const struct ble_gatt_svc_def gatt_svr_svcs[] = {
+    {
+        /* Service: uart */
+        .type = BLE_GATT_SVC_TYPE_PRIMARY,
+        .uuid128 = (void *)gatt_svr_svc_uart,
+        .characteristics = (struct ble_gatt_chr_def[]) { {
+            .uuid128 = gatt_svr_chr_uart_read,
+            .val_handle = &g_bleuart_attr_read_handle,
+            .access_cb = gatt_svr_chr_access_uart_write,
+            .flags = BLE_GATT_CHR_F_NOTIFY,
+        }, {
+            /* Characteristic: Write */
+            .uuid128 = (void *)gatt_svr_chr_uart_write,
+            .access_cb = gatt_svr_chr_access_uart_write,
+            .flags = BLE_GATT_CHR_F_WRITE | BLE_GATT_CHR_F_WRITE_NO_RSP,
+            .val_handle = &g_bleuart_attr_write_handle,
+        }, {
+            0, /* No more characteristics in this service */
+        } },
+    },
+
+    {
+        0, /* No more services */
+    },
+};
+
+static int
+gatt_svr_chr_access_uart_write(uint16_t conn_handle, uint16_t attr_handle,
+                               struct ble_gatt_access_ctxt *ctxt, void *arg)
+{
+    struct os_mbuf *om = ctxt->om;
+    switch (ctxt->op) {
+        case BLE_GATT_ACCESS_OP_WRITE_CHR:
+              while(om) {
+                  console_write((char *)om->om_data, om->om_len);
+                  om = SLIST_NEXT(om, om_next);
+              }
+              console_write("\n", 1);
+              return 0;
+        default:
+            assert(0);
+            return BLE_ATT_ERR_UNLIKELY;
+    }
+}
+
+/**
+ * bleuart GATT server initialization
+ *
+ * @param eventq
+ * @return 0 on success; non-zero on failure
+ */
+int
+bleuart_gatt_svr_init(void)
+{
+    int rc;
+
+    rc = ble_gatts_count_cfg(gatt_svr_svcs);
+    if (rc != 0) {
+        goto err;
+    }
+
+    rc = ble_gatts_add_svcs(gatt_svr_svcs);
+    if (rc != 0) {
+        return rc;
+    }
+
+err:
+    return rc;
+}
+
+/**
+ * Reads console and sends data over BLE
+ */
+static void
+bleuart_uart_read(void)
+{
+    int rc;
+    int off;
+    int full_line;
+    struct os_mbuf *om;
+
+    off = 0;
+    while (1) {
+        rc = console_read(console_buf + off,
+                          MYNEWT_VAL(BLEUART_MAX_INPUT) - off, &full_line);
+        if (rc <= 0 && !full_line) {
+            continue;
+        }
+        off += rc;
+        if (!full_line) {
+            continue;
+        }
+
+        om = ble_hs_mbuf_from_flat(console_buf, off);
+        if (!om) {
+            return;
+        }
+        ble_gattc_notify_custom(g_console_conn_handle,
+                                g_bleuart_attr_read_handle, om);
+        off = 0;
+        break;
+    }
+}
+
+/**
+ * Sets the global connection handle
+ *
+ * @param connection handle
+ */
+void
+bleuart_set_conn_handle(uint16_t conn_handle) {
+    g_console_conn_handle = conn_handle;
+}
+
+/**
+ * BLEuart console initialization
+ *
+ * @param Maximum input
+ */
+void
+bleuart_init(void)
+{
+    int rc;
+
+    rc = console_init(bleuart_uart_read);
+    SYSINIT_PANIC_ASSERT(rc == 0);
+
+    console_buf = malloc(MYNEWT_VAL(BLEUART_MAX_INPUT));
+    SYSINIT_PANIC_ASSERT(console_buf != NULL);
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/net/nimble/host/src/ble_hs.c
----------------------------------------------------------------------
diff --git a/net/nimble/host/src/ble_hs.c b/net/nimble/host/src/ble_hs.c
index 3b33341..57c3e70 100644
--- a/net/nimble/host/src/ble_hs.c
+++ b/net/nimble/host/src/ble_hs.c
@@ -23,7 +23,6 @@
 #include "syscfg/syscfg.h"
 #include "bsp/bsp.h"
 #include "stats/stats.h"
-#include "util/tpq.h"
 #include "os/os.h"
 #include "nimble/ble_hci_trans.h"
 #include "ble_hs_priv.h"
@@ -61,11 +60,11 @@ static int ble_hs_reset_reason;
 #define BLE_HS_HEARTBEAT_OS_TICKS       \
     (MYNEWT_VAL(BLE_HS_HEARTBEAT_FREQ) * OS_TICKS_PER_SEC / 1000)
 
-#define BLE_HS_SYNC_RETRY_RATE          (OS_TICKS_PER_SEC / 10)    
+#define BLE_HS_SYNC_RETRY_RATE          (OS_TICKS_PER_SEC / 10)
 
 static struct os_task *ble_hs_parent_task;
 
-#define BLE_HS_SYNC_RETRY_RATE          (OS_TICKS_PER_SEC / 10)    
+#define BLE_HS_SYNC_RETRY_RATE          (OS_TICKS_PER_SEC / 10)
 
 /**
  * Handles unresponsive timeouts and periodic retries in case of resource

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/net/nimble/pkg.yml
----------------------------------------------------------------------
diff --git a/net/nimble/pkg.yml b/net/nimble/pkg.yml
index 10d2004..bf39866 100644
--- a/net/nimble/pkg.yml
+++ b/net/nimble/pkg.yml
@@ -26,7 +26,7 @@ pkg.keywords:
     - bluetooth
 
 pkg.deps:
-    - libs/os
+    - kernel/os
 
 pkg.syscfg_defs:
     # Supported GAP roles.  By default, all four roles are enabled.

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/net/nimble/transport/ram/pkg.yml
----------------------------------------------------------------------
diff --git a/net/nimble/transport/ram/pkg.yml b/net/nimble/transport/ram/pkg.yml
index 3d551fe..6126116 100644
--- a/net/nimble/transport/ram/pkg.yml
+++ b/net/nimble/transport/ram/pkg.yml
@@ -27,7 +27,7 @@ pkg.keywords:
 
 pkg.deps:
     - net/nimble
-    - libs/os
+    - kernel/os
 
 pkg.apis:
     - ble_transport

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/net/nimble/transport/uart/pkg.yml
----------------------------------------------------------------------
diff --git a/net/nimble/transport/uart/pkg.yml b/net/nimble/transport/uart/pkg.yml
index 252feba..c48c16b 100644
--- a/net/nimble/transport/uart/pkg.yml
+++ b/net/nimble/transport/uart/pkg.yml
@@ -27,7 +27,7 @@ pkg.keywords:
 
 pkg.deps:
     - hw/hal
-    - libs/os
+    - kernel/os
     - net/nimble
 
 pkg.apis:

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/net/wifi/wifi_mgmt/pkg.yml
----------------------------------------------------------------------
diff --git a/net/wifi/wifi_mgmt/pkg.yml b/net/wifi/wifi_mgmt/pkg.yml
index 38e58ca..bc96a43 100644
--- a/net/wifi/wifi_mgmt/pkg.yml
+++ b/net/wifi/wifi_mgmt/pkg.yml
@@ -23,7 +23,7 @@ pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
 pkg.homepage: "http://mynewt.apache.org/"
 pkg.keywords:
 pkg.deps:
-    - "@apache-mynewt-core/libs/os"
+    - "@apache-mynewt-core/kernel/os"
     - "@apache-mynewt-core/libs/util"
 pkg.deps.WIFI_MGMT_CLI:
     - libs/shell

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/config/pkg.yml
----------------------------------------------------------------------
diff --git a/sys/config/pkg.yml b/sys/config/pkg.yml
index f674867..4b4b6ff 100644
--- a/sys/config/pkg.yml
+++ b/sys/config/pkg.yml
@@ -26,11 +26,11 @@ pkg.keywords:
 pkg.deps:
     - libs/util
 pkg.deps.CONFIG_CLI:
-    - libs/shell
+    - sys/shell
 pkg.deps.CONFIG_NEWTMGR:
-    - libs/json
+    - encoding/json
 pkg.deps.CONFIG_FCB:
-    - sys/fcb
+    - fs/fcb
 pkg.deps.CONFIG_NFFS:
     - fs/nffs
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/config/src/config.c
----------------------------------------------------------------------
diff --git a/sys/config/src/config.c b/sys/config/src/config.c
index e41bfda..805d138 100644
--- a/sys/config/src/config.c
+++ b/sys/config/src/config.c
@@ -23,7 +23,7 @@
 #include "sysinit/sysinit.h"
 #include "syscfg/syscfg.h"
 #include "os/os.h"
-#include "util/base64.h"
+#include "base64/base64.h"
 
 #include "config/config.h"
 #include "config_priv.h"

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/console/README.md
----------------------------------------------------------------------
diff --git a/sys/console/README.md b/sys/console/README.md
new file mode 100644
index 0000000..4ef8bd7
--- /dev/null
+++ b/sys/console/README.md
@@ -0,0 +1,33 @@
+<!--
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+#
+-->
+
+# Console
+
+There are two versions of this library;
+  * full - contains actual implemetation
+  * stub - has stubs for the API
+
+You can write a package which uses ```console_printf()```, and builder of a
+project can select which one they'll use.
+For the package, list in the pkg.yml console as the required capability.
+Project builder will then include either libs/console/full or
+libs/console/stub as their choice.
+

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/console/full/include/console/console.h
----------------------------------------------------------------------
diff --git a/sys/console/full/include/console/console.h b/sys/console/full/include/console/console.h
new file mode 100644
index 0000000..a196f01
--- /dev/null
+++ b/sys/console/full/include/console/console.h
@@ -0,0 +1,38 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 __CONSOLE_H__
+#define __CONSOLE_H__
+
+#include <stdarg.h>
+
+typedef void (*console_rx_cb)(void);
+
+int console_init(console_rx_cb rx_cb);
+int console_is_init(void);
+void console_write(const char *str, int cnt);
+int console_read(char *str, int cnt, int *newline);
+void console_blocking_mode(void);
+void console_echo(int on);
+
+void console_printf(const char *fmt, ...)
+    __attribute__ ((format (printf, 1, 2)));;
+
+extern int console_is_midline;
+
+#endif /* __CONSOLE_H__ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/console/full/include/console/prompt.h
----------------------------------------------------------------------
diff --git a/sys/console/full/include/console/prompt.h b/sys/console/full/include/console/prompt.h
new file mode 100644
index 0000000..849ec7e
--- /dev/null
+++ b/sys/console/full/include/console/prompt.h
@@ -0,0 +1,33 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 __CONSOLE_PROMPT_H__
+#define __CONSOLE_PROMPT_H__
+
+#include <stdarg.h>
+
+
+/* print console prompt */
+void console_print_prompt();
+/* set the console prompt character */
+void console_set_prompt(char);
+
+void console_no_prompt(void);
+
+#endif /* __CONSOLE_PROMPT_H__ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/console/full/pkg.yml
----------------------------------------------------------------------
diff --git a/sys/console/full/pkg.yml b/sys/console/full/pkg.yml
new file mode 100644
index 0000000..59b11c6
--- /dev/null
+++ b/sys/console/full/pkg.yml
@@ -0,0 +1,44 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+#
+
+pkg.name: sys/console/full
+pkg.description: Text-based IO interface.
+pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
+pkg.homepage: "http://mynewt.apache.org/"
+pkg.keywords:
+
+pkg.deps:
+    - hw/hal
+    - kernel/os
+    - hw/drivers/uart
+pkg.apis: console
+
+pkg.init_function: console_pkg_init
+pkg.init_stage: 0
+
+pkg.syscfg_defs:
+    CONSOLE_PROMPT:
+        description: 'Default console prompt '
+        value: '0'
+    CONSOLE_ECHO:
+        description: 'Default console echo '
+        value: '1'
+    CONSOLE_HIST_ENABLE:
+        description: 'Console history '
+        value: 1

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/console/full/src/cons_fmt.c
----------------------------------------------------------------------
diff --git a/sys/console/full/src/cons_fmt.c b/sys/console/full/src/cons_fmt.c
new file mode 100644
index 0000000..2b64c01
--- /dev/null
+++ b/sys/console/full/src/cons_fmt.c
@@ -0,0 +1,77 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+#include <stdarg.h>
+#include <stdio.h>
+#include "syscfg/syscfg.h"
+#include "console/console.h"
+#include "os/os_time.h"
+
+#define CONS_OUTPUT_MAX_LINE	128
+
+#if MYNEWT_PKG(LIBS_BASELIBC)
+size_t console_file_write(FILE *p, const char *str, size_t cnt);
+
+static const struct File_methods console_file_ops = {
+    .write = console_file_write,
+    .read = NULL
+};
+
+static const FILE console_file = {
+    .vmt = &console_file_ops
+};
+
+void
+console_printf(const char *fmt, ...)
+{
+    va_list args;
+
+    /* Prefix each line with a timestamp. */
+    if (!console_is_midline) {
+        fprintf((FILE *)&console_file, "%lu:", (unsigned long)os_time_get());
+    }
+
+    va_start(args, fmt);
+    vfprintf((FILE *)&console_file, fmt, args);
+    va_end(args);
+}
+
+#else
+
+void
+console_printf(const char *fmt, ...)
+{
+    va_list args;
+    char buf[CONS_OUTPUT_MAX_LINE];
+    int len;
+
+    /* Prefix each line with a timestamp. */
+    if (!console_is_midline) {
+        len = snprintf(buf, sizeof(buf), "%lu:", (unsigned long)os_time_get());
+        console_write(buf, len);
+    }
+
+    va_start(args, fmt);
+    len = vsnprintf(buf, sizeof(buf), fmt, args);
+    if (len >= sizeof(buf)) {
+        len = sizeof(buf) - 1;
+    }
+    console_write(buf, len);
+    va_end(args);
+}
+#endif


[24/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/cmsis-core/src/ext/core_cm4_simd.h
----------------------------------------------------------------------
diff --git a/libs/cmsis-core/src/ext/core_cm4_simd.h b/libs/cmsis-core/src/ext/core_cm4_simd.h
deleted file mode 100644
index 83db95b..0000000
--- a/libs/cmsis-core/src/ext/core_cm4_simd.h
+++ /dev/null
@@ -1,673 +0,0 @@
-/**************************************************************************//**
- * @file     core_cm4_simd.h
- * @brief    CMSIS Cortex-M4 SIMD Header File
- * @version  V3.20
- * @date     25. February 2013
- *
- * @note
- *
- ******************************************************************************/
-/* Copyright (c) 2009 - 2013 ARM LIMITED
-
-   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 ARM 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 COPYRIGHT HOLDERS AND 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.
-   ---------------------------------------------------------------------------*/
-
-
-#ifdef __cplusplus
- extern "C" {
-#endif
-
-#ifndef __CORE_CM4_SIMD_H
-#define __CORE_CM4_SIMD_H
-
-
-/*******************************************************************************
- *                Hardware Abstraction Layer
- ******************************************************************************/
-
-
-/* ###################  Compiler specific Intrinsics  ########################### */
-/** \defgroup CMSIS_SIMD_intrinsics CMSIS SIMD Intrinsics
-  Access to dedicated SIMD instructions
-  @{
-*/
-
-#if   defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/
-/* ARM armcc specific functions */
-
-/*------ CM4 SIMD Intrinsics -----------------------------------------------------*/
-#define __SADD8                           __sadd8
-#define __QADD8                           __qadd8
-#define __SHADD8                          __shadd8
-#define __UADD8                           __uadd8
-#define __UQADD8                          __uqadd8
-#define __UHADD8                          __uhadd8
-#define __SSUB8                           __ssub8
-#define __QSUB8                           __qsub8
-#define __SHSUB8                          __shsub8
-#define __USUB8                           __usub8
-#define __UQSUB8                          __uqsub8
-#define __UHSUB8                          __uhsub8
-#define __SADD16                          __sadd16
-#define __QADD16                          __qadd16
-#define __SHADD16                         __shadd16
-#define __UADD16                          __uadd16
-#define __UQADD16                         __uqadd16
-#define __UHADD16                         __uhadd16
-#define __SSUB16                          __ssub16
-#define __QSUB16                          __qsub16
-#define __SHSUB16                         __shsub16
-#define __USUB16                          __usub16
-#define __UQSUB16                         __uqsub16
-#define __UHSUB16                         __uhsub16
-#define __SASX                            __sasx
-#define __QASX                            __qasx
-#define __SHASX                           __shasx
-#define __UASX                            __uasx
-#define __UQASX                           __uqasx
-#define __UHASX                           __uhasx
-#define __SSAX                            __ssax
-#define __QSAX                            __qsax
-#define __SHSAX                           __shsax
-#define __USAX                            __usax
-#define __UQSAX                           __uqsax
-#define __UHSAX                           __uhsax
-#define __USAD8                           __usad8
-#define __USADA8                          __usada8
-#define __SSAT16                          __ssat16
-#define __USAT16                          __usat16
-#define __UXTB16                          __uxtb16
-#define __UXTAB16                         __uxtab16
-#define __SXTB16                          __sxtb16
-#define __SXTAB16                         __sxtab16
-#define __SMUAD                           __smuad
-#define __SMUADX                          __smuadx
-#define __SMLAD                           __smlad
-#define __SMLADX                          __smladx
-#define __SMLALD                          __smlald
-#define __SMLALDX                         __smlaldx
-#define __SMUSD                           __smusd
-#define __SMUSDX                          __smusdx
-#define __SMLSD                           __smlsd
-#define __SMLSDX                          __smlsdx
-#define __SMLSLD                          __smlsld
-#define __SMLSLDX                         __smlsldx
-#define __SEL                             __sel
-#define __QADD                            __qadd
-#define __QSUB                            __qsub
-
-#define __PKHBT(ARG1,ARG2,ARG3)          ( ((((uint32_t)(ARG1))          ) & 0x0000FFFFUL) |  \
-                                           ((((uint32_t)(ARG2)) << (ARG3)) & 0xFFFF0000UL)  )
-
-#define __PKHTB(ARG1,ARG2,ARG3)          ( ((((uint32_t)(ARG1))          ) & 0xFFFF0000UL) |  \
-                                           ((((uint32_t)(ARG2)) >> (ARG3)) & 0x0000FFFFUL)  )
-
-#define __SMMLA(ARG1,ARG2,ARG3)          ( (int32_t)((((int64_t)(ARG1) * (ARG2)) + \
-                                                      ((int64_t)(ARG3) << 32)      ) >> 32))
-
-/*-- End CM4 SIMD Intrinsics -----------------------------------------------------*/
-
-
-
-#elif defined ( __ICCARM__ ) /*------------------ ICC Compiler -------------------*/
-/* IAR iccarm specific functions */
-
-/*------ CM4 SIMD Intrinsics -----------------------------------------------------*/
-#include <cmsis_iar.h>
-
-/*-- End CM4 SIMD Intrinsics -----------------------------------------------------*/
-
-
-
-#elif defined ( __TMS470__ ) /*---------------- TI CCS Compiler ------------------*/
-/* TI CCS specific functions */
-
-/*------ CM4 SIMD Intrinsics -----------------------------------------------------*/
-#include <cmsis_ccs.h>
-
-/*-- End CM4 SIMD Intrinsics -----------------------------------------------------*/
-
-
-
-#elif defined ( __GNUC__ ) /*------------------ GNU Compiler ---------------------*/
-/* GNU gcc specific functions */
-
-/*------ CM4 SIMD Intrinsics -----------------------------------------------------*/
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SADD8(uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("sadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD8(uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("qadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHADD8(uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("shadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UADD8(uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("uadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQADD8(uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("uqadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHADD8(uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("uhadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSUB8(uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("ssub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB8(uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("qsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSUB8(uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("shsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USUB8(uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("usub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSUB8(uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("uqsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSUB8(uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("uhsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SADD16(uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("sadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD16(uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("qadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHADD16(uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("shadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UADD16(uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("uadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQADD16(uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("uqadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHADD16(uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("uhadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSUB16(uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("ssub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB16(uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("qsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSUB16(uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("shsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USUB16(uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("usub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSUB16(uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("uqsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSUB16(uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("uhsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SASX(uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("sasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QASX(uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("qasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHASX(uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("shasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UASX(uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("uasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQASX(uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("uqasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHASX(uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("uhasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSAX(uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("ssax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSAX(uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("qsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSAX(uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("shsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USAX(uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("usax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSAX(uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("uqsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSAX(uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("uhsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USAD8(uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("usad8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USADA8(uint32_t op1, uint32_t op2, uint32_t op3)
-{
-  uint32_t result;
-
-  __ASM volatile ("usada8 %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) );
-  return(result);
-}
-
-#define __SSAT16(ARG1,ARG2) \
-({                          \
-  uint32_t __RES, __ARG1 = (ARG1); \
-  __ASM ("ssat16 %0, %1, %2" : "=r" (__RES) :  "I" (ARG2), "r" (__ARG1) ); \
-  __RES; \
- })
-
-#define __USAT16(ARG1,ARG2) \
-({                          \
-  uint32_t __RES, __ARG1 = (ARG1); \
-  __ASM ("usat16 %0, %1, %2" : "=r" (__RES) :  "I" (ARG2), "r" (__ARG1) ); \
-  __RES; \
- })
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UXTB16(uint32_t op1)
-{
-  uint32_t result;
-
-  __ASM volatile ("uxtb16 %0, %1" : "=r" (result) : "r" (op1));
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UXTAB16(uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("uxtab16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SXTB16(uint32_t op1)
-{
-  uint32_t result;
-
-  __ASM volatile ("sxtb16 %0, %1" : "=r" (result) : "r" (op1));
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SXTAB16(uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("sxtab16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUAD  (uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("smuad %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUADX (uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("smuadx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLAD (uint32_t op1, uint32_t op2, uint32_t op3)
-{
-  uint32_t result;
-
-  __ASM volatile ("smlad %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) );
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLADX (uint32_t op1, uint32_t op2, uint32_t op3)
-{
-  uint32_t result;
-
-  __ASM volatile ("smladx %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) );
-  return(result);
-}
-
-#define __SMLALD(ARG1,ARG2,ARG3) \
-({ \
-  uint32_t __ARG1 = (ARG1), __ARG2 = (ARG2), __ARG3_H = (uint32_t)((uint64_t)(ARG3) >> 32), __ARG3_L = (uint32_t)((uint64_t)(ARG3) & 0xFFFFFFFFUL); \
-  __ASM volatile ("smlald %0, %1, %2, %3" : "=r" (__ARG3_L), "=r" (__ARG3_H) : "r" (__ARG1), "r" (__ARG2), "0" (__ARG3_L), "1" (__ARG3_H) ); \
-  (uint64_t)(((uint64_t)__ARG3_H << 32) | __ARG3_L); \
- })
-
-#define __SMLALDX(ARG1,ARG2,ARG3) \
-({ \
-  uint32_t __ARG1 = (ARG1), __ARG2 = (ARG2), __ARG3_H = (uint32_t)((uint64_t)(ARG3) >> 32), __ARG3_L = (uint32_t)((uint64_t)(ARG3) & 0xFFFFFFFFUL); \
-  __ASM volatile ("smlaldx %0, %1, %2, %3" : "=r" (__ARG3_L), "=r" (__ARG3_H) : "r" (__ARG1), "r" (__ARG2), "0" (__ARG3_L), "1" (__ARG3_H) ); \
-  (uint64_t)(((uint64_t)__ARG3_H << 32) | __ARG3_L); \
- })
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUSD  (uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("smusd %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUSDX (uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("smusdx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLSD (uint32_t op1, uint32_t op2, uint32_t op3)
-{
-  uint32_t result;
-
-  __ASM volatile ("smlsd %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) );
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLSDX (uint32_t op1, uint32_t op2, uint32_t op3)
-{
-  uint32_t result;
-
-  __ASM volatile ("smlsdx %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) );
-  return(result);
-}
-
-#define __SMLSLD(ARG1,ARG2,ARG3) \
-({ \
-  uint32_t __ARG1 = (ARG1), __ARG2 = (ARG2), __ARG3_H = (uint32_t)((ARG3) >> 32), __ARG3_L = (uint32_t)((ARG3) & 0xFFFFFFFFUL); \
-  __ASM volatile ("smlsld %0, %1, %2, %3" : "=r" (__ARG3_L), "=r" (__ARG3_H) : "r" (__ARG1), "r" (__ARG2), "0" (__ARG3_L), "1" (__ARG3_H) ); \
-  (uint64_t)(((uint64_t)__ARG3_H << 32) | __ARG3_L); \
- })
-
-#define __SMLSLDX(ARG1,ARG2,ARG3) \
-({ \
-  uint32_t __ARG1 = (ARG1), __ARG2 = (ARG2), __ARG3_H = (uint32_t)((ARG3) >> 32), __ARG3_L = (uint32_t)((ARG3) & 0xFFFFFFFFUL); \
-  __ASM volatile ("smlsldx %0, %1, %2, %3" : "=r" (__ARG3_L), "=r" (__ARG3_H) : "r" (__ARG1), "r" (__ARG2), "0" (__ARG3_L), "1" (__ARG3_H) ); \
-  (uint64_t)(((uint64_t)__ARG3_H << 32) | __ARG3_L); \
- })
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SEL  (uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("sel %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD(uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("qadd %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB(uint32_t op1, uint32_t op2)
-{
-  uint32_t result;
-
-  __ASM volatile ("qsub %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
-  return(result);
-}
-
-#define __PKHBT(ARG1,ARG2,ARG3) \
-({                          \
-  uint32_t __RES, __ARG1 = (ARG1), __ARG2 = (ARG2); \
-  __ASM ("pkhbt %0, %1, %2, lsl %3" : "=r" (__RES) :  "r" (__ARG1), "r" (__ARG2), "I" (ARG3)  ); \
-  __RES; \
- })
-
-#define __PKHTB(ARG1,ARG2,ARG3) \
-({                          \
-  uint32_t __RES, __ARG1 = (ARG1), __ARG2 = (ARG2); \
-  if (ARG3 == 0) \
-    __ASM ("pkhtb %0, %1, %2" : "=r" (__RES) :  "r" (__ARG1), "r" (__ARG2)  ); \
-  else \
-    __ASM ("pkhtb %0, %1, %2, asr %3" : "=r" (__RES) :  "r" (__ARG1), "r" (__ARG2), "I" (ARG3)  ); \
-  __RES; \
- })
-
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMMLA (int32_t op1, int32_t op2, int32_t op3)
-{
- int32_t result;
-
- __ASM volatile ("smmla %0, %1, %2, %3" : "=r" (result): "r"  (op1), "r" (op2), "r" (op3) );
- return(result);
-}
-
-/*-- End CM4 SIMD Intrinsics -----------------------------------------------------*/
-
-
-
-#elif defined ( __TASKING__ ) /*------------------ TASKING Compiler --------------*/
-/* TASKING carm specific functions */
-
-
-/*------ CM4 SIMD Intrinsics -----------------------------------------------------*/
-/* not yet supported */
-/*-- End CM4 SIMD Intrinsics -----------------------------------------------------*/
-
-
-#endif
-
-/*@} end of group CMSIS_SIMD_intrinsics */
-
-
-#endif /* __CORE_CM4_SIMD_H */
-
-#ifdef __cplusplus
-}
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/cmsis-core/src/ext/core_cmFunc.h
----------------------------------------------------------------------
diff --git a/libs/cmsis-core/src/ext/core_cmFunc.h b/libs/cmsis-core/src/ext/core_cmFunc.h
deleted file mode 100644
index 0a18faf..0000000
--- a/libs/cmsis-core/src/ext/core_cmFunc.h
+++ /dev/null
@@ -1,636 +0,0 @@
-/**************************************************************************//**
- * @file     core_cmFunc.h
- * @brief    CMSIS Cortex-M Core Function Access Header File
- * @version  V3.20
- * @date     25. February 2013
- *
- * @note
- *
- ******************************************************************************/
-/* Copyright (c) 2009 - 2013 ARM LIMITED
-
-   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 ARM 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 COPYRIGHT HOLDERS AND 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.
-   ---------------------------------------------------------------------------*/
-
-
-#ifndef __CORE_CMFUNC_H
-#define __CORE_CMFUNC_H
-
-
-/* ###########################  Core Function Access  ########################### */
-/** \ingroup  CMSIS_Core_FunctionInterface
-    \defgroup CMSIS_Core_RegAccFunctions CMSIS Core Register Access Functions
-  @{
- */
-
-#if   defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/
-/* ARM armcc specific functions */
-
-#if (__ARMCC_VERSION < 400677)
-  #error "Please use ARM Compiler Toolchain V4.0.677 or later!"
-#endif
-
-/* intrinsic void __enable_irq();     */
-/* intrinsic void __disable_irq();    */
-
-/** \brief  Get Control Register
-
-    This function returns the content of the Control Register.
-
-    \return               Control Register value
- */
-__STATIC_INLINE uint32_t __get_CONTROL(void)
-{
-  register uint32_t __regControl         __ASM("control");
-  return(__regControl);
-}
-
-
-/** \brief  Set Control Register
-
-    This function writes the given value to the Control Register.
-
-    \param [in]    control  Control Register value to set
- */
-__STATIC_INLINE void __set_CONTROL(uint32_t control)
-{
-  register uint32_t __regControl         __ASM("control");
-  __regControl = control;
-}
-
-
-/** \brief  Get IPSR Register
-
-    This function returns the content of the IPSR Register.
-
-    \return               IPSR Register value
- */
-__STATIC_INLINE uint32_t __get_IPSR(void)
-{
-  register uint32_t __regIPSR          __ASM("ipsr");
-  return(__regIPSR);
-}
-
-
-/** \brief  Get APSR Register
-
-    This function returns the content of the APSR Register.
-
-    \return               APSR Register value
- */
-__STATIC_INLINE uint32_t __get_APSR(void)
-{
-  register uint32_t __regAPSR          __ASM("apsr");
-  return(__regAPSR);
-}
-
-
-/** \brief  Get xPSR Register
-
-    This function returns the content of the xPSR Register.
-
-    \return               xPSR Register value
- */
-__STATIC_INLINE uint32_t __get_xPSR(void)
-{
-  register uint32_t __regXPSR          __ASM("xpsr");
-  return(__regXPSR);
-}
-
-
-/** \brief  Get Process Stack Pointer
-
-    This function returns the current value of the Process Stack Pointer (PSP).
-
-    \return               PSP Register value
- */
-__STATIC_INLINE uint32_t __get_PSP(void)
-{
-  register uint32_t __regProcessStackPointer  __ASM("psp");
-  return(__regProcessStackPointer);
-}
-
-
-/** \brief  Set Process Stack Pointer
-
-    This function assigns the given value to the Process Stack Pointer (PSP).
-
-    \param [in]    topOfProcStack  Process Stack Pointer value to set
- */
-__STATIC_INLINE void __set_PSP(uint32_t topOfProcStack)
-{
-  register uint32_t __regProcessStackPointer  __ASM("psp");
-  __regProcessStackPointer = topOfProcStack;
-}
-
-
-/** \brief  Get Main Stack Pointer
-
-    This function returns the current value of the Main Stack Pointer (MSP).
-
-    \return               MSP Register value
- */
-__STATIC_INLINE uint32_t __get_MSP(void)
-{
-  register uint32_t __regMainStackPointer     __ASM("msp");
-  return(__regMainStackPointer);
-}
-
-
-/** \brief  Set Main Stack Pointer
-
-    This function assigns the given value to the Main Stack Pointer (MSP).
-
-    \param [in]    topOfMainStack  Main Stack Pointer value to set
- */
-__STATIC_INLINE void __set_MSP(uint32_t topOfMainStack)
-{
-  register uint32_t __regMainStackPointer     __ASM("msp");
-  __regMainStackPointer = topOfMainStack;
-}
-
-
-/** \brief  Get Priority Mask
-
-    This function returns the current state of the priority mask bit from the Priority Mask Register.
-
-    \return               Priority Mask value
- */
-__STATIC_INLINE uint32_t __get_PRIMASK(void)
-{
-  register uint32_t __regPriMask         __ASM("primask");
-  return(__regPriMask);
-}
-
-
-/** \brief  Set Priority Mask
-
-    This function assigns the given value to the Priority Mask Register.
-
-    \param [in]    priMask  Priority Mask
- */
-__STATIC_INLINE void __set_PRIMASK(uint32_t priMask)
-{
-  register uint32_t __regPriMask         __ASM("primask");
-  __regPriMask = (priMask);
-}
-
-
-#if       (__CORTEX_M >= 0x03)
-
-/** \brief  Enable FIQ
-
-    This function enables FIQ interrupts by clearing the F-bit in the CPSR.
-    Can only be executed in Privileged modes.
- */
-#define __enable_fault_irq                __enable_fiq
-
-
-/** \brief  Disable FIQ
-
-    This function disables FIQ interrupts by setting the F-bit in the CPSR.
-    Can only be executed in Privileged modes.
- */
-#define __disable_fault_irq               __disable_fiq
-
-
-/** \brief  Get Base Priority
-
-    This function returns the current value of the Base Priority register.
-
-    \return               Base Priority register value
- */
-__STATIC_INLINE uint32_t  __get_BASEPRI(void)
-{
-  register uint32_t __regBasePri         __ASM("basepri");
-  return(__regBasePri);
-}
-
-
-/** \brief  Set Base Priority
-
-    This function assigns the given value to the Base Priority register.
-
-    \param [in]    basePri  Base Priority value to set
- */
-__STATIC_INLINE void __set_BASEPRI(uint32_t basePri)
-{
-  register uint32_t __regBasePri         __ASM("basepri");
-  __regBasePri = (basePri & 0xff);
-}
-
-
-/** \brief  Get Fault Mask
-
-    This function returns the current value of the Fault Mask register.
-
-    \return               Fault Mask register value
- */
-__STATIC_INLINE uint32_t __get_FAULTMASK(void)
-{
-  register uint32_t __regFaultMask       __ASM("faultmask");
-  return(__regFaultMask);
-}
-
-
-/** \brief  Set Fault Mask
-
-    This function assigns the given value to the Fault Mask register.
-
-    \param [in]    faultMask  Fault Mask value to set
- */
-__STATIC_INLINE void __set_FAULTMASK(uint32_t faultMask)
-{
-  register uint32_t __regFaultMask       __ASM("faultmask");
-  __regFaultMask = (faultMask & (uint32_t)1);
-}
-
-#endif /* (__CORTEX_M >= 0x03) */
-
-
-#if       (__CORTEX_M == 0x04)
-
-/** \brief  Get FPSCR
-
-    This function returns the current value of the Floating Point Status/Control register.
-
-    \return               Floating Point Status/Control register value
- */
-__STATIC_INLINE uint32_t __get_FPSCR(void)
-{
-#if (__FPU_PRESENT == 1) && (__FPU_USED == 1)
-  register uint32_t __regfpscr         __ASM("fpscr");
-  return(__regfpscr);
-#else
-   return(0);
-#endif
-}
-
-
-/** \brief  Set FPSCR
-
-    This function assigns the given value to the Floating Point Status/Control register.
-
-    \param [in]    fpscr  Floating Point Status/Control value to set
- */
-__STATIC_INLINE void __set_FPSCR(uint32_t fpscr)
-{
-#if (__FPU_PRESENT == 1) && (__FPU_USED == 1)
-  register uint32_t __regfpscr         __ASM("fpscr");
-  __regfpscr = (fpscr);
-#endif
-}
-
-#endif /* (__CORTEX_M == 0x04) */
-
-
-#elif defined ( __ICCARM__ ) /*------------------ ICC Compiler -------------------*/
-/* IAR iccarm specific functions */
-
-#include <cmsis_iar.h>
-
-
-#elif defined ( __TMS470__ ) /*---------------- TI CCS Compiler ------------------*/
-/* TI CCS specific functions */
-
-#include <cmsis_ccs.h>
-
-
-#elif defined ( __GNUC__ ) /*------------------ GNU Compiler ---------------------*/
-/* GNU gcc specific functions */
-
-/** \brief  Enable IRQ Interrupts
-
-  This function enables IRQ interrupts by clearing the I-bit in the CPSR.
-  Can only be executed in Privileged modes.
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_irq(void)
-{
-  __ASM volatile ("cpsie i" : : : "memory");
-}
-
-
-/** \brief  Disable IRQ Interrupts
-
-  This function disables IRQ interrupts by setting the I-bit in the CPSR.
-  Can only be executed in Privileged modes.
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_irq(void)
-{
-  __ASM volatile ("cpsid i" : : : "memory");
-}
-
-
-/** \brief  Get Control Register
-
-    This function returns the content of the Control Register.
-
-    \return               Control Register value
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_CONTROL(void)
-{
-  uint32_t result;
-
-  __ASM volatile ("MRS %0, control" : "=r" (result) );
-  return(result);
-}
-
-
-/** \brief  Set Control Register
-
-    This function writes the given value to the Control Register.
-
-    \param [in]    control  Control Register value to set
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_CONTROL(uint32_t control)
-{
-  __ASM volatile ("MSR control, %0" : : "r" (control) : "memory");
-}
-
-
-/** \brief  Get IPSR Register
-
-    This function returns the content of the IPSR Register.
-
-    \return               IPSR Register value
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_IPSR(void)
-{
-  uint32_t result;
-
-  __ASM volatile ("MRS %0, ipsr" : "=r" (result) );
-  return(result);
-}
-
-
-/** \brief  Get APSR Register
-
-    This function returns the content of the APSR Register.
-
-    \return               APSR Register value
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_APSR(void)
-{
-  uint32_t result;
-
-  __ASM volatile ("MRS %0, apsr" : "=r" (result) );
-  return(result);
-}
-
-
-/** \brief  Get xPSR Register
-
-    This function returns the content of the xPSR Register.
-
-    \return               xPSR Register value
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_xPSR(void)
-{
-  uint32_t result;
-
-  __ASM volatile ("MRS %0, xpsr" : "=r" (result) );
-  return(result);
-}
-
-
-/** \brief  Get Process Stack Pointer
-
-    This function returns the current value of the Process Stack Pointer (PSP).
-
-    \return               PSP Register value
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_PSP(void)
-{
-  register uint32_t result;
-
-  __ASM volatile ("MRS %0, psp\n"  : "=r" (result) );
-  return(result);
-}
-
-
-/** \brief  Set Process Stack Pointer
-
-    This function assigns the given value to the Process Stack Pointer (PSP).
-
-    \param [in]    topOfProcStack  Process Stack Pointer value to set
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_PSP(uint32_t topOfProcStack)
-{
-  __ASM volatile ("MSR psp, %0\n" : : "r" (topOfProcStack) : "sp");
-}
-
-
-/** \brief  Get Main Stack Pointer
-
-    This function returns the current value of the Main Stack Pointer (MSP).
-
-    \return               MSP Register value
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_MSP(void)
-{
-  register uint32_t result;
-
-  __ASM volatile ("MRS %0, msp\n" : "=r" (result) );
-  return(result);
-}
-
-
-/** \brief  Set Main Stack Pointer
-
-    This function assigns the given value to the Main Stack Pointer (MSP).
-
-    \param [in]    topOfMainStack  Main Stack Pointer value to set
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_MSP(uint32_t topOfMainStack)
-{
-  __ASM volatile ("MSR msp, %0\n" : : "r" (topOfMainStack) : "sp");
-}
-
-
-/** \brief  Get Priority Mask
-
-    This function returns the current state of the priority mask bit from the Priority Mask Register.
-
-    \return               Priority Mask value
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_PRIMASK(void)
-{
-  uint32_t result;
-
-  __ASM volatile ("MRS %0, primask" : "=r" (result) );
-  return(result);
-}
-
-
-/** \brief  Set Priority Mask
-
-    This function assigns the given value to the Priority Mask Register.
-
-    \param [in]    priMask  Priority Mask
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_PRIMASK(uint32_t priMask)
-{
-  __ASM volatile ("MSR primask, %0" : : "r" (priMask) : "memory");
-}
-
-
-#if       (__CORTEX_M >= 0x03)
-
-/** \brief  Enable FIQ
-
-    This function enables FIQ interrupts by clearing the F-bit in the CPSR.
-    Can only be executed in Privileged modes.
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_fault_irq(void)
-{
-  __ASM volatile ("cpsie f" : : : "memory");
-}
-
-
-/** \brief  Disable FIQ
-
-    This function disables FIQ interrupts by setting the F-bit in the CPSR.
-    Can only be executed in Privileged modes.
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_fault_irq(void)
-{
-  __ASM volatile ("cpsid f" : : : "memory");
-}
-
-
-/** \brief  Get Base Priority
-
-    This function returns the current value of the Base Priority register.
-
-    \return               Base Priority register value
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_BASEPRI(void)
-{
-  uint32_t result;
-
-  __ASM volatile ("MRS %0, basepri_max" : "=r" (result) );
-  return(result);
-}
-
-
-/** \brief  Set Base Priority
-
-    This function assigns the given value to the Base Priority register.
-
-    \param [in]    basePri  Base Priority value to set
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_BASEPRI(uint32_t value)
-{
-  __ASM volatile ("MSR basepri, %0" : : "r" (value) : "memory");
-}
-
-
-/** \brief  Get Fault Mask
-
-    This function returns the current value of the Fault Mask register.
-
-    \return               Fault Mask register value
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_FAULTMASK(void)
-{
-  uint32_t result;
-
-  __ASM volatile ("MRS %0, faultmask" : "=r" (result) );
-  return(result);
-}
-
-
-/** \brief  Set Fault Mask
-
-    This function assigns the given value to the Fault Mask register.
-
-    \param [in]    faultMask  Fault Mask value to set
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_FAULTMASK(uint32_t faultMask)
-{
-  __ASM volatile ("MSR faultmask, %0" : : "r" (faultMask) : "memory");
-}
-
-#endif /* (__CORTEX_M >= 0x03) */
-
-
-#if       (__CORTEX_M == 0x04)
-
-/** \brief  Get FPSCR
-
-    This function returns the current value of the Floating Point Status/Control register.
-
-    \return               Floating Point Status/Control register value
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_FPSCR(void)
-{
-#if (__FPU_PRESENT == 1) && (__FPU_USED == 1)
-  uint32_t result;
-
-  /* Empty asm statement works as a scheduling barrier */
-  __ASM volatile ("");
-  __ASM volatile ("VMRS %0, fpscr" : "=r" (result) );
-  __ASM volatile ("");
-  return(result);
-#else
-   return(0);
-#endif
-}
-
-
-/** \brief  Set FPSCR
-
-    This function assigns the given value to the Floating Point Status/Control register.
-
-    \param [in]    fpscr  Floating Point Status/Control value to set
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_FPSCR(uint32_t fpscr)
-{
-#if (__FPU_PRESENT == 1) && (__FPU_USED == 1)
-  /* Empty asm statement works as a scheduling barrier */
-  __ASM volatile ("");
-  __ASM volatile ("VMSR fpscr, %0" : : "r" (fpscr) : "vfpcc");
-  __ASM volatile ("");
-#endif
-}
-
-#endif /* (__CORTEX_M == 0x04) */
-
-
-#elif defined ( __TASKING__ ) /*------------------ TASKING Compiler --------------*/
-/* TASKING carm specific functions */
-
-/*
- * The CMSIS functions have been implemented as intrinsics in the compiler.
- * Please use "carm -?i" to get an up to date list of all instrinsics,
- * Including the CMSIS ones.
- */
-
-#endif
-
-/*@} end of CMSIS_Core_RegAccFunctions */
-
-
-#endif /* __CORE_CMFUNC_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/cmsis-core/src/ext/core_cmInstr.h
----------------------------------------------------------------------
diff --git a/libs/cmsis-core/src/ext/core_cmInstr.h b/libs/cmsis-core/src/ext/core_cmInstr.h
deleted file mode 100644
index d213f0e..0000000
--- a/libs/cmsis-core/src/ext/core_cmInstr.h
+++ /dev/null
@@ -1,688 +0,0 @@
-/**************************************************************************//**
- * @file     core_cmInstr.h
- * @brief    CMSIS Cortex-M Core Instruction Access Header File
- * @version  V3.20
- * @date     05. March 2013
- *
- * @note
- *
- ******************************************************************************/
-/* Copyright (c) 2009 - 2013 ARM LIMITED
-
-   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 ARM 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 COPYRIGHT HOLDERS AND 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.
-   ---------------------------------------------------------------------------*/
-
-
-#ifndef __CORE_CMINSTR_H
-#define __CORE_CMINSTR_H
-
-
-/* ##########################  Core Instruction Access  ######################### */
-/** \defgroup CMSIS_Core_InstructionInterface CMSIS Core Instruction Interface
-  Access to dedicated instructions
-  @{
-*/
-
-#if   defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/
-/* ARM armcc specific functions */
-
-#if (__ARMCC_VERSION < 400677)
-  #error "Please use ARM Compiler Toolchain V4.0.677 or later!"
-#endif
-
-
-/** \brief  No Operation
-
-    No Operation does nothing. This instruction can be used for code alignment purposes.
- */
-#define __NOP                             __nop
-
-
-/** \brief  Wait For Interrupt
-
-    Wait For Interrupt is a hint instruction that suspends execution
-    until one of a number of events occurs.
- */
-#define __WFI                             __wfi
-
-
-/** \brief  Wait For Event
-
-    Wait For Event is a hint instruction that permits the processor to enter
-    a low-power state until one of a number of events occurs.
- */
-#define __WFE                             __wfe
-
-
-/** \brief  Send Event
-
-    Send Event is a hint instruction. It causes an event to be signaled to the CPU.
- */
-#define __SEV                             __sev
-
-
-/** \brief  Instruction Synchronization Barrier
-
-    Instruction Synchronization Barrier flushes the pipeline in the processor,
-    so that all instructions following the ISB are fetched from cache or
-    memory, after the instruction has been completed.
- */
-#define __ISB()                           __isb(0xF)
-
-
-/** \brief  Data Synchronization Barrier
-
-    This function acts as a special kind of Data Memory Barrier.
-    It completes when all explicit memory accesses before this instruction complete.
- */
-#define __DSB()                           __dsb(0xF)
-
-
-/** \brief  Data Memory Barrier
-
-    This function ensures the apparent order of the explicit memory operations before
-    and after the instruction, without ensuring their completion.
- */
-#define __DMB()                           __dmb(0xF)
-
-
-/** \brief  Reverse byte order (32 bit)
-
-    This function reverses the byte order in integer value.
-
-    \param [in]    value  Value to reverse
-    \return               Reversed value
- */
-#define __REV                             __rev
-
-
-/** \brief  Reverse byte order (16 bit)
-
-    This function reverses the byte order in two unsigned short values.
-
-    \param [in]    value  Value to reverse
-    \return               Reversed value
- */
-#ifndef __NO_EMBEDDED_ASM
-__attribute__((section(".rev16_text"))) __STATIC_INLINE __ASM uint32_t __REV16(uint32_t value)
-{
-  rev16 r0, r0
-  bx lr
-}
-#endif
-
-/** \brief  Reverse byte order in signed short value
-
-    This function reverses the byte order in a signed short value with sign extension to integer.
-
-    \param [in]    value  Value to reverse
-    \return               Reversed value
- */
-#ifndef __NO_EMBEDDED_ASM
-__attribute__((section(".revsh_text"))) __STATIC_INLINE __ASM int32_t __REVSH(int32_t value)
-{
-  revsh r0, r0
-  bx lr
-}
-#endif
-
-
-/** \brief  Rotate Right in unsigned value (32 bit)
-
-    This function Rotate Right (immediate) provides the value of the contents of a register rotated by a variable number of bits.
-
-    \param [in]    value  Value to rotate
-    \param [in]    value  Number of Bits to rotate
-    \return               Rotated value
- */
-#define __ROR                             __ror
-
-
-/** \brief  Breakpoint
-
-    This function causes the processor to enter Debug state.
-    Debug tools can use this to investigate system state when the instruction at a particular address is reached.
-
-    \param [in]    value  is ignored by the processor.
-                   If required, a debugger can use it to store additional information about the breakpoint.
- */
-#define __BKPT(value)                       __breakpoint(value)
-
-
-#if       (__CORTEX_M >= 0x03)
-
-/** \brief  Reverse bit order of value
-
-    This function reverses the bit order of the given value.
-
-    \param [in]    value  Value to reverse
-    \return               Reversed value
- */
-#define __RBIT                            __rbit
-
-
-/** \brief  LDR Exclusive (8 bit)
-
-    This function performs a exclusive LDR command for 8 bit value.
-
-    \param [in]    ptr  Pointer to data
-    \return             value of type uint8_t at (*ptr)
- */
-#define __LDREXB(ptr)                     ((uint8_t ) __ldrex(ptr))
-
-
-/** \brief  LDR Exclusive (16 bit)
-
-    This function performs a exclusive LDR command for 16 bit values.
-
-    \param [in]    ptr  Pointer to data
-    \return        value of type uint16_t at (*ptr)
- */
-#define __LDREXH(ptr)                     ((uint16_t) __ldrex(ptr))
-
-
-/** \brief  LDR Exclusive (32 bit)
-
-    This function performs a exclusive LDR command for 32 bit values.
-
-    \param [in]    ptr  Pointer to data
-    \return        value of type uint32_t at (*ptr)
- */
-#define __LDREXW(ptr)                     ((uint32_t ) __ldrex(ptr))
-
-
-/** \brief  STR Exclusive (8 bit)
-
-    This function performs a exclusive STR command for 8 bit values.
-
-    \param [in]  value  Value to store
-    \param [in]    ptr  Pointer to location
-    \return          0  Function succeeded
-    \return          1  Function failed
- */
-#define __STREXB(value, ptr)              __strex(value, ptr)
-
-
-/** \brief  STR Exclusive (16 bit)
-
-    This function performs a exclusive STR command for 16 bit values.
-
-    \param [in]  value  Value to store
-    \param [in]    ptr  Pointer to location
-    \return          0  Function succeeded
-    \return          1  Function failed
- */
-#define __STREXH(value, ptr)              __strex(value, ptr)
-
-
-/** \brief  STR Exclusive (32 bit)
-
-    This function performs a exclusive STR command for 32 bit values.
-
-    \param [in]  value  Value to store
-    \param [in]    ptr  Pointer to location
-    \return          0  Function succeeded
-    \return          1  Function failed
- */
-#define __STREXW(value, ptr)              __strex(value, ptr)
-
-
-/** \brief  Remove the exclusive lock
-
-    This function removes the exclusive lock which is created by LDREX.
-
- */
-#define __CLREX                           __clrex
-
-
-/** \brief  Signed Saturate
-
-    This function saturates a signed value.
-
-    \param [in]  value  Value to be saturated
-    \param [in]    sat  Bit position to saturate to (1..32)
-    \return             Saturated value
- */
-#define __SSAT                            __ssat
-
-
-/** \brief  Unsigned Saturate
-
-    This function saturates an unsigned value.
-
-    \param [in]  value  Value to be saturated
-    \param [in]    sat  Bit position to saturate to (0..31)
-    \return             Saturated value
- */
-#define __USAT                            __usat
-
-
-/** \brief  Count leading zeros
-
-    This function counts the number of leading zeros of a data value.
-
-    \param [in]  value  Value to count the leading zeros
-    \return             number of leading zeros in value
- */
-#define __CLZ                             __clz
-
-#endif /* (__CORTEX_M >= 0x03) */
-
-
-
-#elif defined ( __ICCARM__ ) /*------------------ ICC Compiler -------------------*/
-/* IAR iccarm specific functions */
-
-#include <cmsis_iar.h>
-
-
-#elif defined ( __TMS470__ ) /*---------------- TI CCS Compiler ------------------*/
-/* TI CCS specific functions */
-
-#include <cmsis_ccs.h>
-
-
-#elif defined ( __GNUC__ ) /*------------------ GNU Compiler ---------------------*/
-/* GNU gcc specific functions */
-
-/* Define macros for porting to both thumb1 and thumb2.
- * For thumb1, use low register (r0-r7), specified by constrant "l"
- * Otherwise, use general registers, specified by constrant "r" */
-#if defined (__thumb__) && !defined (__thumb2__)
-#define __CMSIS_GCC_OUT_REG(r) "=l" (r)
-#define __CMSIS_GCC_USE_REG(r) "l" (r)
-#else
-#define __CMSIS_GCC_OUT_REG(r) "=r" (r)
-#define __CMSIS_GCC_USE_REG(r) "r" (r)
-#endif
-
-/** \brief  No Operation
-
-    No Operation does nothing. This instruction can be used for code alignment purposes.
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE void __NOP(void)
-{
-  __ASM volatile ("nop");
-}
-
-
-/** \brief  Wait For Interrupt
-
-    Wait For Interrupt is a hint instruction that suspends execution
-    until one of a number of events occurs.
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE void __WFI(void)
-{
-  __ASM volatile ("wfi");
-}
-
-
-/** \brief  Wait For Event
-
-    Wait For Event is a hint instruction that permits the processor to enter
-    a low-power state until one of a number of events occurs.
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE void __WFE(void)
-{
-  __ASM volatile ("wfe");
-}
-
-
-/** \brief  Send Event
-
-    Send Event is a hint instruction. It causes an event to be signaled to the CPU.
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE void __SEV(void)
-{
-  __ASM volatile ("sev");
-}
-
-
-/** \brief  Instruction Synchronization Barrier
-
-    Instruction Synchronization Barrier flushes the pipeline in the processor,
-    so that all instructions following the ISB are fetched from cache or
-    memory, after the instruction has been completed.
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE void __ISB(void)
-{
-  __ASM volatile ("isb");
-}
-
-
-/** \brief  Data Synchronization Barrier
-
-    This function acts as a special kind of Data Memory Barrier.
-    It completes when all explicit memory accesses before this instruction complete.
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE void __DSB(void)
-{
-  __ASM volatile ("dsb");
-}
-
-
-/** \brief  Data Memory Barrier
-
-    This function ensures the apparent order of the explicit memory operations before
-    and after the instruction, without ensuring their completion.
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE void __DMB(void)
-{
-  __ASM volatile ("dmb");
-}
-
-
-/** \brief  Reverse byte order (32 bit)
-
-    This function reverses the byte order in integer value.
-
-    \param [in]    value  Value to reverse
-    \return               Reversed value
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __REV(uint32_t value)
-{
-#if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5)
-  return __builtin_bswap32(value);
-#else
-  uint32_t result;
-
-  __ASM volatile ("rev %0, %1" : __CMSIS_GCC_OUT_REG (result) : __CMSIS_GCC_USE_REG (value) );
-  return(result);
-#endif
-}
-
-
-/** \brief  Reverse byte order (16 bit)
-
-    This function reverses the byte order in two unsigned short values.
-
-    \param [in]    value  Value to reverse
-    \return               Reversed value
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __REV16(uint32_t value)
-{
-  uint32_t result;
-
-  __ASM volatile ("rev16 %0, %1" : __CMSIS_GCC_OUT_REG (result) : __CMSIS_GCC_USE_REG (value) );
-  return(result);
-}
-
-
-/** \brief  Reverse byte order in signed short value
-
-    This function reverses the byte order in a signed short value with sign extension to integer.
-
-    \param [in]    value  Value to reverse
-    \return               Reversed value
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE int32_t __REVSH(int32_t value)
-{
-#if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)
-  return (short)__builtin_bswap16(value);
-#else
-  uint32_t result;
-
-  __ASM volatile ("revsh %0, %1" : __CMSIS_GCC_OUT_REG (result) : __CMSIS_GCC_USE_REG (value) );
-  return(result);
-#endif
-}
-
-
-/** \brief  Rotate Right in unsigned value (32 bit)
-
-    This function Rotate Right (immediate) provides the value of the contents of a register rotated by a variable number of bits.
-
-    \param [in]    value  Value to rotate
-    \param [in]    value  Number of Bits to rotate
-    \return               Rotated value
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __ROR(uint32_t op1, uint32_t op2)
-{
-  return (op1 >> op2) | (op1 << (32 - op2)); 
-}
-
-
-/** \brief  Breakpoint
-
-    This function causes the processor to enter Debug state.
-    Debug tools can use this to investigate system state when the instruction at a particular address is reached.
-
-    \param [in]    value  is ignored by the processor.
-                   If required, a debugger can use it to store additional information about the breakpoint.
- */
-#define __BKPT(value)                       __ASM volatile ("bkpt "#value)
-
-
-#if       (__CORTEX_M >= 0x03)
-
-/** \brief  Reverse bit order of value
-
-    This function reverses the bit order of the given value.
-
-    \param [in]    value  Value to reverse
-    \return               Reversed value
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __RBIT(uint32_t value)
-{
-  uint32_t result;
-
-   __ASM volatile ("rbit %0, %1" : "=r" (result) : "r" (value) );
-   return(result);
-}
-
-
-/** \brief  LDR Exclusive (8 bit)
-
-    This function performs a exclusive LDR command for 8 bit value.
-
-    \param [in]    ptr  Pointer to data
-    \return             value of type uint8_t at (*ptr)
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint8_t __LDREXB(volatile uint8_t *addr)
-{
-    uint32_t result;
-
-#if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)
-   __ASM volatile ("ldrexb %0, %1" : "=r" (result) : "Q" (*addr) );
-#else
-    /* Prior to GCC 4.8, "Q" will be expanded to [rx, #0] which is not
-       accepted by assembler. So has to use following less efficient pattern.
-    */
-   __ASM volatile ("ldrexb %0, [%1]" : "=r" (result) : "r" (addr) : "memory" );
-#endif
-   return(result);
-}
-
-
-/** \brief  LDR Exclusive (16 bit)
-
-    This function performs a exclusive LDR command for 16 bit values.
-
-    \param [in]    ptr  Pointer to data
-    \return        value of type uint16_t at (*ptr)
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint16_t __LDREXH(volatile uint16_t *addr)
-{
-    uint32_t result;
-
-#if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)
-   __ASM volatile ("ldrexh %0, %1" : "=r" (result) : "Q" (*addr) );
-#else
-    /* Prior to GCC 4.8, "Q" will be expanded to [rx, #0] which is not
-       accepted by assembler. So has to use following less efficient pattern.
-    */
-   __ASM volatile ("ldrexh %0, [%1]" : "=r" (result) : "r" (addr) : "memory" );
-#endif
-   return(result);
-}
-
-
-/** \brief  LDR Exclusive (32 bit)
-
-    This function performs a exclusive LDR command for 32 bit values.
-
-    \param [in]    ptr  Pointer to data
-    \return        value of type uint32_t at (*ptr)
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __LDREXW(volatile uint32_t *addr)
-{
-    uint32_t result;
-
-   __ASM volatile ("ldrex %0, %1" : "=r" (result) : "Q" (*addr) );
-   return(result);
-}
-
-
-/** \brief  STR Exclusive (8 bit)
-
-    This function performs a exclusive STR command for 8 bit values.
-
-    \param [in]  value  Value to store
-    \param [in]    ptr  Pointer to location
-    \return          0  Function succeeded
-    \return          1  Function failed
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __STREXB(uint8_t value, volatile uint8_t *addr)
-{
-   uint32_t result;
-
-   __ASM volatile ("strexb %0, %2, %1" : "=&r" (result), "=Q" (*addr) : "r" (value) );
-   return(result);
-}
-
-
-/** \brief  STR Exclusive (16 bit)
-
-    This function performs a exclusive STR command for 16 bit values.
-
-    \param [in]  value  Value to store
-    \param [in]    ptr  Pointer to location
-    \return          0  Function succeeded
-    \return          1  Function failed
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __STREXH(uint16_t value, volatile uint16_t *addr)
-{
-   uint32_t result;
-
-   __ASM volatile ("strexh %0, %2, %1" : "=&r" (result), "=Q" (*addr) : "r" (value) );
-   return(result);
-}
-
-
-/** \brief  STR Exclusive (32 bit)
-
-    This function performs a exclusive STR command for 32 bit values.
-
-    \param [in]  value  Value to store
-    \param [in]    ptr  Pointer to location
-    \return          0  Function succeeded
-    \return          1  Function failed
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __STREXW(uint32_t value, volatile uint32_t *addr)
-{
-   uint32_t result;
-
-   __ASM volatile ("strex %0, %2, %1" : "=&r" (result), "=Q" (*addr) : "r" (value) );
-   return(result);
-}
-
-
-/** \brief  Remove the exclusive lock
-
-    This function removes the exclusive lock which is created by LDREX.
-
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE void __CLREX(void)
-{
-  __ASM volatile ("clrex" ::: "memory");
-}
-
-
-/** \brief  Signed Saturate
-
-    This function saturates a signed value.
-
-    \param [in]  value  Value to be saturated
-    \param [in]    sat  Bit position to saturate to (1..32)
-    \return             Saturated value
- */
-#define __SSAT(ARG1,ARG2) \
-({                          \
-  uint32_t __RES, __ARG1 = (ARG1); \
-  __ASM ("ssat %0, %1, %2" : "=r" (__RES) :  "I" (ARG2), "r" (__ARG1) ); \
-  __RES; \
- })
-
-
-/** \brief  Unsigned Saturate
-
-    This function saturates an unsigned value.
-
-    \param [in]  value  Value to be saturated
-    \param [in]    sat  Bit position to saturate to (0..31)
-    \return             Saturated value
- */
-#define __USAT(ARG1,ARG2) \
-({                          \
-  uint32_t __RES, __ARG1 = (ARG1); \
-  __ASM ("usat %0, %1, %2" : "=r" (__RES) :  "I" (ARG2), "r" (__ARG1) ); \
-  __RES; \
- })
-
-
-/** \brief  Count leading zeros
-
-    This function counts the number of leading zeros of a data value.
-
-    \param [in]  value  Value to count the leading zeros
-    \return             number of leading zeros in value
- */
-__attribute__( ( always_inline ) ) __STATIC_INLINE uint8_t __CLZ(uint32_t value)
-{
-   uint32_t result;
-
-  __ASM volatile ("clz %0, %1" : "=r" (result) : "r" (value) );
-  return(result);
-}
-
-#endif /* (__CORTEX_M >= 0x03) */
-
-
-
-
-#elif defined ( __TASKING__ ) /*------------------ TASKING Compiler --------------*/
-/* TASKING carm specific functions */
-
-/*
- * The CMSIS functions have been implemented as intrinsics in the compiler.
- * Please use "carm -?i" to get an up to date list of all intrinsics,
- * Including the CMSIS ones.
- */
-
-#endif
-
-/*@}*/ /* end of group CMSIS_Core_InstructionInterface */
-
-#endif /* __CORE_CMINSTR_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/console/README.md
----------------------------------------------------------------------
diff --git a/libs/console/README.md b/libs/console/README.md
deleted file mode 100644
index 4ef8bd7..0000000
--- a/libs/console/README.md
+++ /dev/null
@@ -1,33 +0,0 @@
-<!--
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you 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.
-#
--->
-
-# Console
-
-There are two versions of this library;
-  * full - contains actual implemetation
-  * stub - has stubs for the API
-
-You can write a package which uses ```console_printf()```, and builder of a
-project can select which one they'll use.
-For the package, list in the pkg.yml console as the required capability.
-Project builder will then include either libs/console/full or
-libs/console/stub as their choice.
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/console/full/include/console/console.h
----------------------------------------------------------------------
diff --git a/libs/console/full/include/console/console.h b/libs/console/full/include/console/console.h
deleted file mode 100644
index a196f01..0000000
--- a/libs/console/full/include/console/console.h
+++ /dev/null
@@ -1,38 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 __CONSOLE_H__
-#define __CONSOLE_H__
-
-#include <stdarg.h>
-
-typedef void (*console_rx_cb)(void);
-
-int console_init(console_rx_cb rx_cb);
-int console_is_init(void);
-void console_write(const char *str, int cnt);
-int console_read(char *str, int cnt, int *newline);
-void console_blocking_mode(void);
-void console_echo(int on);
-
-void console_printf(const char *fmt, ...)
-    __attribute__ ((format (printf, 1, 2)));;
-
-extern int console_is_midline;
-
-#endif /* __CONSOLE_H__ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/console/full/include/console/prompt.h
----------------------------------------------------------------------
diff --git a/libs/console/full/include/console/prompt.h b/libs/console/full/include/console/prompt.h
deleted file mode 100644
index 849ec7e..0000000
--- a/libs/console/full/include/console/prompt.h
+++ /dev/null
@@ -1,33 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 __CONSOLE_PROMPT_H__
-#define __CONSOLE_PROMPT_H__
-
-#include <stdarg.h>
-
-
-/* print console prompt */
-void console_print_prompt();
-/* set the console prompt character */
-void console_set_prompt(char);
-
-void console_no_prompt(void);
-
-#endif /* __CONSOLE_PROMPT_H__ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/console/full/pkg.yml
----------------------------------------------------------------------
diff --git a/libs/console/full/pkg.yml b/libs/console/full/pkg.yml
deleted file mode 100644
index d6b95d7..0000000
--- a/libs/console/full/pkg.yml
+++ /dev/null
@@ -1,44 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you 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.
-#
-
-pkg.name: libs/console/full
-pkg.description: Text-based IO interface.
-pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
-pkg.homepage: "http://mynewt.apache.org/"
-pkg.keywords:
-
-pkg.deps:
-    - hw/hal
-    - libs/os
-    - hw/drivers/uart
-pkg.apis: console
-
-pkg.init_function: console_pkg_init
-pkg.init_stage: 0
-
-pkg.syscfg_defs:
-    CONSOLE_PROMPT:
-        description: 'Default console prompt '
-        value: '0'
-    CONSOLE_ECHO:
-        description: 'Default console echo '
-        value: '1'
-    CONSOLE_HIST_ENABLE:
-        description: 'Console history '
-        value: 1

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/console/full/src/cons_fmt.c
----------------------------------------------------------------------
diff --git a/libs/console/full/src/cons_fmt.c b/libs/console/full/src/cons_fmt.c
deleted file mode 100644
index 2b64c01..0000000
--- a/libs/console/full/src/cons_fmt.c
+++ /dev/null
@@ -1,77 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-#include <stdarg.h>
-#include <stdio.h>
-#include "syscfg/syscfg.h"
-#include "console/console.h"
-#include "os/os_time.h"
-
-#define CONS_OUTPUT_MAX_LINE	128
-
-#if MYNEWT_PKG(LIBS_BASELIBC)
-size_t console_file_write(FILE *p, const char *str, size_t cnt);
-
-static const struct File_methods console_file_ops = {
-    .write = console_file_write,
-    .read = NULL
-};
-
-static const FILE console_file = {
-    .vmt = &console_file_ops
-};
-
-void
-console_printf(const char *fmt, ...)
-{
-    va_list args;
-
-    /* Prefix each line with a timestamp. */
-    if (!console_is_midline) {
-        fprintf((FILE *)&console_file, "%lu:", (unsigned long)os_time_get());
-    }
-
-    va_start(args, fmt);
-    vfprintf((FILE *)&console_file, fmt, args);
-    va_end(args);
-}
-
-#else
-
-void
-console_printf(const char *fmt, ...)
-{
-    va_list args;
-    char buf[CONS_OUTPUT_MAX_LINE];
-    int len;
-
-    /* Prefix each line with a timestamp. */
-    if (!console_is_midline) {
-        len = snprintf(buf, sizeof(buf), "%lu:", (unsigned long)os_time_get());
-        console_write(buf, len);
-    }
-
-    va_start(args, fmt);
-    len = vsnprintf(buf, sizeof(buf), fmt, args);
-    if (len >= sizeof(buf)) {
-        len = sizeof(buf) - 1;
-    }
-    console_write(buf, len);
-    va_end(args);
-}
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/console/full/src/cons_tty.c
----------------------------------------------------------------------
diff --git a/libs/console/full/src/cons_tty.c b/libs/console/full/src/cons_tty.c
deleted file mode 100644
index 157ed48..0000000
--- a/libs/console/full/src/cons_tty.c
+++ /dev/null
@@ -1,561 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include <inttypes.h>
-#include <assert.h>
-#include "syscfg/syscfg.h"
-#include "sysinit/sysinit.h"
-#include "os/os.h"
-#include "uart/uart.h"
-#include "bsp/bsp.h"
-
-#include "console/console.h"
-#include "console/prompt.h"
-
-/** Indicates whether the previous line of output was completed. */
-int console_is_midline;
-
-#define CONSOLE_TX_BUF_SZ       32      /* IO buffering, must be power of 2 */
-#define CONSOLE_RX_BUF_SZ       128
-#define CONSOLE_RX_CHUNK        16
-
-#if MYNEWT_VAL(CONSOLE_HIST_ENABLE)
-#define CONSOLE_HIST_SZ         32
-#endif
-
-#define CONSOLE_DEL             0x7f    /* del character */
-#define CONSOLE_ESC             0x1b    /* esc character */
-#define CONSOLE_LEFT            'D'     /* esc-[-D emitted when moving left */
-#define CONSOLE_UP              'A'     /* esc-[-A moving up */
-#define CONSOLE_RIGHT           'C'     /* esc-[-C moving right */
-#define CONSOLE_DOWN            'B'     /* esc-[-B moving down */
-
-#define CONSOLE_HEAD_INC(cr)    (((cr)->cr_head + 1) & ((cr)->cr_size - 1))
-#define CONSOLE_TAIL_INC(cr)    (((cr)->cr_tail + 1) & ((cr)->cr_size - 1))
-
-typedef void (*console_write_char)(char);
-void console_print_prompt(void);
-
-struct console_ring {
-    uint8_t cr_head;
-    uint8_t cr_tail;
-    uint8_t cr_size;
-    uint8_t _pad;
-    uint8_t *cr_buf;
-};
-
-struct console_tty {
-    struct uart_dev *ct_dev;
-    struct console_ring ct_tx;
-    uint8_t ct_tx_buf[CONSOLE_TX_BUF_SZ]; /* must be after console_ring */
-    struct console_ring ct_rx;
-    uint8_t ct_rx_buf[CONSOLE_RX_BUF_SZ]; /* must be after console_ring */
-    console_rx_cb ct_rx_cb; /* callback that input is ready */
-    console_write_char ct_write_char;
-    uint8_t ct_echo_off:1;
-    uint8_t ct_esc_seq:2;
-} console_tty;
-
-#if MYNEWT_VAL(CONSOLE_HIST_ENABLE)
-struct console_hist {
-    uint8_t ch_head;
-    uint8_t ch_tail;
-    uint8_t ch_size;
-    uint8_t ch_curr;
-    uint8_t ch_buf[CONSOLE_HIST_SZ][CONSOLE_RX_BUF_SZ];
-} console_hist;
-#endif
-
-static void
-console_add_char(struct console_ring *cr, char ch)
-{
-    cr->cr_buf[cr->cr_head] = ch;
-    cr->cr_head = CONSOLE_HEAD_INC(cr);
-}
-
-static uint8_t
-console_pull_char(struct console_ring *cr)
-{
-    uint8_t ch;
-
-    ch = cr->cr_buf[cr->cr_tail];
-    cr->cr_tail = CONSOLE_TAIL_INC(cr);
-    return ch;
-}
-
-static int
-console_pull_char_head(struct console_ring *cr)
-{
-    if (cr->cr_head != cr->cr_tail) {
-        cr->cr_head = (cr->cr_head - 1) & (cr->cr_size - 1);
-        return 0;
-    } else {
-        return -1;
-    }
-}
-
-static void
-console_queue_char(char ch)
-{
-    struct console_tty *ct = &console_tty;
-    int sr;
-
-    OS_ENTER_CRITICAL(sr);
-    while (CONSOLE_HEAD_INC(&ct->ct_tx) == ct->ct_tx.cr_tail) {
-        /* TX needs to drain */
-        uart_start_tx(ct->ct_dev);
-        OS_EXIT_CRITICAL(sr);
-        if (os_started()) {
-            os_time_delay(1);
-        }
-        OS_ENTER_CRITICAL(sr);
-    }
-    console_add_char(&ct->ct_tx, ch);
-    OS_EXIT_CRITICAL(sr);
-}
-
-#if MYNEWT_VAL(CONSOLE_HIST_ENABLE)
-static void
-console_hist_init(void)
-{
-    struct console_hist *ch = &console_hist;
-
-    ch->ch_head = 0;
-    ch->ch_tail = 0;
-    ch->ch_curr = 0;
-    ch->ch_size = CONSOLE_HIST_SZ;
-}
-
-static void
-console_hist_add(struct console_ring *rx)
-{
-    struct console_hist *ch = &console_hist;
-    uint8_t *str = ch->ch_buf[ch->ch_head];
-    uint8_t tail;
-    uint8_t empty = 1;
-
-    tail = rx->cr_tail;
-    while (tail != rx->cr_head) {
-        *str = rx->cr_buf[tail];
-        if (*str != ' ' && *str != '\t' && *str != '\n') {
-            empty = 0;
-        }
-        if (*str == '\n') {
-            *str = '\0';
-            /* don't save empty history */
-            if (empty) {
-                return;
-            }
-            break;
-        }
-        str++;
-        tail = (tail + 1) % CONSOLE_RX_BUF_SZ;
-    }
-
-    ch->ch_head = (ch->ch_head + 1) & (ch->ch_size - 1);
-    ch->ch_curr = ch->ch_head;
-
-    /* buffer full, start overwriting old history */
-    if (ch->ch_head == ch->ch_tail) {
-        ch->ch_tail = (ch->ch_tail + 1) & (ch->ch_size - 1);
-    }
-}
-
-static int
-console_hist_move(struct console_ring *rx, uint8_t *tx_buf, uint8_t direction)
-{
-    struct console_hist *ch = &console_hist;
-    uint8_t *str = NULL;
-    int space = 0;
-    int i;
-    uint8_t limit = direction == CONSOLE_UP ? ch->ch_tail : ch->ch_head;
-
-    /* no more history to return in this direction */
-    if (ch->ch_curr == limit) {
-        return 0;
-    }
-
-    if (direction == CONSOLE_UP) {
-        ch->ch_curr = (ch->ch_curr - 1) & (ch->ch_size - 1);
-    } else {
-        ch->ch_curr = (ch->ch_curr + 1) & (ch->ch_size - 1);
-    }
-
-    /* consume all chars */
-    while (console_pull_char_head(rx) == 0) {
-        /* do nothing */
-    }
-
-    str = ch->ch_buf[ch->ch_curr];
-    for (i = 0; i < CONSOLE_RX_BUF_SZ; ++i) {
-        if (str[i] == '\0') {
-            break;
-        }
-        tx_buf[i] = str[i];
-        console_add_char(rx, str[i]);
-        space++;
-    }
-
-    return space;
-}
-#endif
-
-static void
-console_blocking_tx(char ch)
-{
-    struct console_tty *ct = &console_tty;
-
-    uart_blocking_tx(ct->ct_dev, ch);
-}
-
-/*
- * Flush cnt characters from console output queue.
- */
-static void
-console_tx_flush(struct console_tty *ct, int cnt)
-{
-    int i;
-    uint8_t byte;
-
-    for (i = 0; i < cnt; i++) {
-        if (ct->ct_tx.cr_head == ct->ct_tx.cr_tail) {
-            /*
-             * Queue is empty.
-             */
-            break;
-        }
-        byte = console_pull_char(&ct->ct_tx);
-        console_blocking_tx(byte);
-    }
-}
-
-void
-console_blocking_mode(void)
-{
-    struct console_tty *ct = &console_tty;
-    int sr;
-
-    OS_ENTER_CRITICAL(sr);
-    if (ct->ct_write_char) {
-        ct->ct_write_char = console_blocking_tx;
-
-        console_tx_flush(ct, CONSOLE_TX_BUF_SZ);
-    }
-    OS_EXIT_CRITICAL(sr);
-}
-
-void
-console_echo(int on)
-{
-    struct console_tty *ct = &console_tty;
-
-    ct->ct_echo_off = !on;
-}
-
-size_t
-console_file_write(void *arg, const char *str, size_t cnt)
-{
-    struct console_tty *ct = &console_tty;
-    int i;
-
-    if (!ct->ct_write_char) {
-        return cnt;
-    }
-    for (i = 0; i < cnt; i++) {
-        if (str[i] == '\n') {
-            ct->ct_write_char('\r');
-        }
-        ct->ct_write_char(str[i]);
-    }
-    if (cnt > 0) {
-        console_is_midline = str[cnt - 1] != '\n';
-    }
-    uart_start_tx(ct->ct_dev);
-    return cnt;
-}
-
-void
-console_write(const char *str, int cnt)
-{
-    console_file_write(NULL, str, cnt);
-}
-
-int
-console_read(char *str, int cnt, int *newline)
-{
-    struct console_tty *ct = &console_tty;
-    struct console_ring *cr = &ct->ct_rx;
-    int sr;
-    int i;
-    uint8_t ch;
-
-    *newline = 0;
-    OS_ENTER_CRITICAL(sr);
-    for (i = 0; i < cnt; i++) {
-        if (cr->cr_head == cr->cr_tail) {
-            break;
-        }
-
-        if ((i & (CONSOLE_RX_CHUNK - 1)) == (CONSOLE_RX_CHUNK - 1)) {
-            /*
-             * Make a break from blocking interrupts during the copy.
-             */
-            OS_EXIT_CRITICAL(sr);
-            OS_ENTER_CRITICAL(sr);
-        }
-
-        ch = console_pull_char(cr);
-        if (ch == '\n') {
-            *str = '\0';
-            *newline = 1;
-            break;
-        }
-        *str++ = ch;
-    }
-    OS_EXIT_CRITICAL(sr);
-    if (i > 0 || *newline) {
-        uart_start_rx(ct->ct_dev);
-    }
-    return i;
-}
-
-/*
- * Interrupts disabled when console_tx_char/console_rx_char are called.
- */
-static int
-console_tx_char(void *arg)
-{
-    struct console_tty *ct = (struct console_tty *)arg;
-    struct console_ring *cr = &ct->ct_tx;
-
-    if (cr->cr_head == cr->cr_tail) {
-        /*
-         * No more data.
-         */
-        return -1;
-    }
-    return console_pull_char(cr);
-}
-
-static int
-console_buf_space(struct console_ring *cr)
-{
-    int space;
-
-    space = (cr->cr_tail - cr->cr_head) & (cr->cr_size - 1);
-    return space - 1;
-}
-
-static int
-console_rx_char(void *arg, uint8_t data)
-{
-    struct console_tty *ct = (struct console_tty *)arg;
-    struct console_ring *tx = &ct->ct_tx;
-    struct console_ring *rx = &ct->ct_rx;
-    int tx_space = 0;
-    int i;
-#if MYNEWT_VAL(CONSOLE_HIST_ENABLE)
-    uint8_t tx_buf[CONSOLE_RX_BUF_SZ];
-#else
-    uint8_t tx_buf[3];
-#endif
-
-    if (CONSOLE_HEAD_INC(&ct->ct_rx) == ct->ct_rx.cr_tail) {
-        /*
-         * RX queue full. Reader must drain this.
-         */
-        if (ct->ct_rx_cb) {
-            ct->ct_rx_cb();
-        }
-        return -1;
-    }
-
-    /* echo */
-    switch (data) {
-    case '\r':
-    case '\n':
-        /*
-         * linefeed
-         */
-        tx_buf[0] = '\n';
-        tx_buf[1] = '\r';
-        tx_space = 2;
-        console_add_char(rx, '\n');
-#if MYNEWT_VAL(CONSOLE_HIST_ENABLE)
-        console_hist_add(rx);
-#endif
-        if (ct->ct_rx_cb) {
-            ct->ct_rx_cb();
-        }
-        break;
-    case CONSOLE_ESC:
-        ct->ct_esc_seq = 1;
-        goto out;
-    case '[':
-        if (ct->ct_esc_seq == 1) {
-            ct->ct_esc_seq = 2;
-            goto out;
-        } else {
-            goto queue_char;
-        }
-        break;
-    case CONSOLE_LEFT:
-        if (ct->ct_esc_seq == 2) {
-            goto backspace;
-        } else {
-            goto queue_char;
-        }
-        break;
-    case CONSOLE_UP:
-    case CONSOLE_DOWN:
-        if (ct->ct_esc_seq != 2) {
-            goto queue_char;
-        }
-#if MYNEWT_VAL(CONSOLE_HIST_ENABLE)
-        tx_space = console_hist_move(rx, tx_buf, data);
-        tx_buf[tx_space] = 0;
-        ct->ct_esc_seq = 0;
-        /*
-         * when moving up, stop on oldest history entry
-         * when moving down, let it delete input before leaving...
-         */
-        if (data == CONSOLE_UP && tx_space == 0) {
-            goto out;
-        }
-        if (!ct->ct_echo_off) {
-            /* HACK: clean line by backspacing up to maximum possible space */
-            for (i = 0; i < CONSOLE_TX_BUF_SZ; i++) {
-                if (console_buf_space(tx) < 3) {
-                    console_tx_flush(ct, 3);
-                }
-                console_add_char(tx, '\b');
-                console_add_char(tx, ' ');
-                console_add_char(tx, '\b');
-                uart_start_tx(ct->ct_dev);
-            }
-            if (tx_space == 0) {
-                goto out;
-            }
-        } else {
-            goto queue_char;
-        }
-        break;
-#else
-        ct->ct_esc_seq = 0;
-        goto out;
-#endif
-    case CONSOLE_RIGHT:
-        if (ct->ct_esc_seq == 2) {
-            data = ' '; /* add space */
-        }
-        goto queue_char;
-    case '\b':
-    case CONSOLE_DEL:
-backspace:
-        /*
-         * backspace
-         */
-        ct->ct_esc_seq = 0;
-        if (console_pull_char_head(rx) == 0) {
-            /*
-             * Only wipe out char if we can pull stuff off from head.
-             */
-            tx_buf[0] = '\b';
-            tx_buf[1] = ' ';
-            tx_buf[2] = '\b';
-            tx_space = 3;
-        } else {
-            goto out;
-        }
-        break;
-    default:
-queue_char:
-        tx_buf[0] = data;
-        tx_space = 1;
-        ct->ct_esc_seq = 0;
-        console_add_char(rx, data);
-        break;
-    }
-    if (!ct->ct_echo_off) {
-        if (console_buf_space(tx) < tx_space) {
-            console_tx_flush(ct, tx_space);
-        }
-        for (i = 0; i < tx_space; i++) {
-            console_add_char(tx, tx_buf[i]);
-        }
-        uart_start_tx(ct->ct_dev);
-    }
-out:
-    return 0;
-}
-
-int
-console_is_init(void)
-{
-    struct console_tty *ct = &console_tty;
-
-    return (ct->ct_dev != NULL);
-}
-
-int
-console_init(console_rx_cb rx_cb)
-{
-    struct console_tty *ct = &console_tty;
-    struct uart_conf uc = {
-        .uc_speed = CONSOLE_UART_SPEED,
-        .uc_databits = 8,
-        .uc_stopbits = 1,
-        .uc_parity = UART_PARITY_NONE,
-        .uc_flow_ctl = UART_FLOW_CTL_NONE,
-        .uc_tx_char = console_tx_char,
-        .uc_rx_char = console_rx_char,
-        .uc_cb_arg = ct
-    };
-
-    ct->ct_rx_cb = rx_cb;
-    if (!ct->ct_dev) {
-        ct->ct_tx.cr_size = CONSOLE_TX_BUF_SZ;
-        ct->ct_tx.cr_buf = ct->ct_tx_buf;
-        ct->ct_rx.cr_size = CONSOLE_RX_BUF_SZ;
-        ct->ct_rx.cr_buf = ct->ct_rx_buf;
-        ct->ct_write_char = console_queue_char;
-
-        ct->ct_dev = (struct uart_dev *)os_dev_open(CONSOLE_UART,
-          OS_TIMEOUT_NEVER, &uc);
-        if (!ct->ct_dev) {
-            return -1;
-        }
-        ct->ct_echo_off = ! MYNEWT_VAL(CONSOLE_ECHO);
-    }
-
-#if MYNEWT_VAL(CONSOLE_HIST_ENABLE)
-    console_hist_init();
-#endif
-
-    return 0;
-}
-
-void
-console_pkg_init(void)
-{
-    int rc;
-
-    rc = console_init(NULL);
-    SYSINIT_PANIC_ASSERT(rc == 0);
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/console/full/src/prompt.c
----------------------------------------------------------------------
diff --git a/libs/console/full/src/prompt.c b/libs/console/full/src/prompt.c
deleted file mode 100644
index 33e37c0..0000000
--- a/libs/console/full/src/prompt.c
+++ /dev/null
@@ -1,49 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-
-#include "console/console.h"
-#include "console/prompt.h"
-#include <syscfg/syscfg.h>
-
-/* console prompt, always followed by a space */
-static char console_prompt[] = " > ";
-static char do_prompt = MYNEWT_VAL(CONSOLE_PROMPT);
-
-
-/* set the prompt character, leave the space */
-void
-console_set_prompt(char p)
-{
-    do_prompt = 1;
-    console_prompt[1] = p;
-}
-
-void console_no_prompt(void) {
-    do_prompt = 0;
-}
-
-/* print the prompt to the console */
-void
-console_print_prompt(void)
-{
-    if (do_prompt) {
-        console_printf("%s", console_prompt);
-    }
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/console/stub/include/console/console.h
----------------------------------------------------------------------
diff --git a/libs/console/stub/include/console/console.h b/libs/console/stub/include/console/console.h
deleted file mode 100644
index 99db457..0000000
--- a/libs/console/stub/include/console/console.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 __CONSOLE_H__
-#define __CONSOLE_H__
-
-#include <stdarg.h>
-
-typedef void (*console_rx_cb)(void);
-
-static int inline
-console_is_init(void)
-{
-    return 0;
-}
-
-static int inline
-console_init(console_rx_cb rxcb)
-{
-    return 0;
-}
-
-static int inline
-console_read(char *str, int cnt, int *newline)
-{
-    *newline = 0;
-    return 0;
-}
-
-static void inline
-console_blocking_mode(void)
-{
-}
-
-static void inline
-console_write(const char *str, int cnt)
-{
-}
-
-static void inline console_printf(const char *fmt, ...)
-    __attribute__ ((format (printf, 1, 2)));
-
-static void inline
-console_printf(const char *fmt, ...)
-{
-}
-
-static void inline
-console_echo(int on)
-{
-}
-
-#define console_is_midline  (0)
-
-#endif /* __CONSOLE__ */
-



[17/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/luac.c.donotcompile
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/luac.c.donotcompile b/libs/elua/elua_base/src/luac.c.donotcompile
deleted file mode 100644
index 3746997..0000000
--- a/libs/elua/elua_base/src/luac.c.donotcompile
+++ /dev/null
@@ -1,242 +0,0 @@
-/*
-** $Id: luac.c,v 1.54 2006/06/02 17:37:11 lhf Exp $
-** Lua compiler (saves bytecodes to files; also list bytecodes)
-** See Copyright Notice in lua.h
-*/
-
-#include <errno.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#define luac_c
-#define LUA_CORE
-
-#include "lua.h"
-#include "lauxlib.h"
-
-#include "ldo.h"
-#include "lfunc.h"
-#include "lmem.h"
-#include "lobject.h"
-#include "lopcodes.h"
-#include "lstring.h"
-#include "lundump.h"
-
-#define PROGNAME	"luac"		/* default program name */
-#define	OUTPUT		PROGNAME ".out"	/* default output file */
-
-static int listing=0;			/* list bytecodes? */
-static int dumping=1;			/* dump bytecodes? */
-static int stripping=0;			/* strip debug information? */
-static char Output[]={ OUTPUT };	/* default output file name */
-static const char* output=Output;	/* actual output file name */
-static const char* progname=PROGNAME;	/* actual program name */
-static DumpTargetInfo target;
-
-static void fatal(const char* message)
-{
- fprintf(stderr,"%s: %s\n",progname,message);
- exit(EXIT_FAILURE);
-}
-
-static void cannot(const char* what)
-{
- fprintf(stderr,"%s: cannot %s %s: %s\n",progname,what,output,strerror(errno));
- exit(EXIT_FAILURE);
-}
-
-static void usage(const char* message)
-{
- if (*message=='-')
-  fprintf(stderr,"%s: unrecognized option " LUA_QS "\n",progname,message);
- else
-  fprintf(stderr,"%s: %s\n",progname,message);
- fprintf(stderr,
- "usage: %s [options] [filenames].\n"
- "Available options are:\n"
- "  -        process stdin\n"
- "  -l       list\n"
- "  -o name  output to file " LUA_QL("name") " (default is \"%s\")\n"
- "  -p       parse only\n"
- "  -s       strip debug information\n"
- "  -v       show version information\n"
- "  -cci bits       cross-compile with given integer size\n"
- "  -ccn type bits  cross-compile with given lua_Number type and size\n"
- "  -cce endian     cross-compile with given endianness ('big' or 'little')\n"
- "  --       stop handling options\n",
- progname,Output);
- exit(EXIT_FAILURE);
-}
-
-#define	IS(s)	(strcmp(argv[i],s)==0)
-
-static int doargs(int argc, char* argv[])
-{
- int i;
- int version=0;
- if (argv[0]!=NULL && *argv[0]!=0) progname=argv[0];
- for (i=1; i<argc; i++)
- {
-  if (*argv[i]!='-')			/* end of options; keep it */
-   break;
-  else if (IS("--"))			/* end of options; skip it */
-  {
-   ++i;
-   if (version) ++version;
-   break;
-  }
-  else if (IS("-"))			/* end of options; use stdin */
-   break;
-  else if (IS("-l"))			/* list */
-   ++listing;
-  else if (IS("-o"))			/* output file */
-  {
-   output=argv[++i];
-   if (output==NULL || *output==0) usage(LUA_QL("-o") " needs argument");
-   if (IS("-")) output=NULL;
-  }
-  else if (IS("-p"))			/* parse only */
-   dumping=0;
-  else if (IS("-s"))			/* strip debug information */
-   stripping=1;
-  else if (IS("-v"))			/* show version */
-   ++version;
-  else if (IS("-cci")) /* target integer size */
-  {
-   int s = target.sizeof_int = atoi(argv[++i])/8;
-   if (!(s==1 || s==2 || s==4)) fatal(LUA_QL("-cci") " must be 8, 16 or 32");
-  }
-  else if (IS("-ccn")) /* target lua_Number type and size */
-  {
-   const char *type=argv[++i];
-   if (strcmp(type,"int")==0) target.lua_Number_integral=1;
-   else if (strcmp(type,"float")==0) target.lua_Number_integral=0;
-   else if (strcmp(type,"float_arm")==0)
-   {
-     target.lua_Number_integral=0;
-     target.is_arm_fpa=1;
-   }
-   else fatal(LUA_QL("-ccn") " type must be " LUA_QL("int") " or " LUA_QL("float") " or " LUA_QL("float_arm"));
-   int s = target.sizeof_lua_Number = atoi(argv[++i])/8;
-   if (target.lua_Number_integral && !(s==1 || s==2 || s==4)) fatal(LUA_QL("-ccn") " size must be 8, 16, or 32 for int");
-   if (!target.lua_Number_integral && !(s==4 || s==8)) fatal(LUA_QL("-ccn") " size must be 32 or 64 for float");
-  }
-  else if (IS("-cce")) /* target endianness */
-  {
-   const char *val=argv[++i];
-   if (strcmp(val,"big")==0) target.little_endian=0;
-   else if (strcmp(val,"little")==0) target.little_endian=1;
-   else fatal(LUA_QL("-cce") " must be " LUA_QL("big") " or " LUA_QL("little"));
-  }
-  else					/* unknown option */
-   usage(argv[i]);
- }
- if (i==argc && (listing || !dumping))
- {
-  dumping=0;
-  argv[--i]=Output;
- }
- if (version)
- {
-  printf("%s  %s\n",LUA_RELEASE,LUA_COPYRIGHT);
-  if (version==argc-1) exit(EXIT_SUCCESS);
- }
- return i;
-}
-
-#define toproto(L,i) (clvalue(L->top+(i))->l.p)
-
-static const Proto* combine(lua_State* L, int n)
-{
- if (n==1)
-  return toproto(L,-1);
- else
- {
-  int i,pc;
-  Proto* f=luaF_newproto(L);
-  setptvalue2s(L,L->top,f); incr_top(L);
-  f->source=luaS_newliteral(L,"=(" PROGNAME ")");
-  f->maxstacksize=1;
-  pc=2*n+1;
-  f->code=luaM_newvector(L,pc,Instruction);
-  f->sizecode=pc;
-  f->p=luaM_newvector(L,n,Proto*);
-  f->sizep=n;
-  pc=0;
-  for (i=0; i<n; i++)
-  {
-   f->p[i]=toproto(L,i-n-1);
-   f->code[pc++]=CREATE_ABx(OP_CLOSURE,0,i);
-   f->code[pc++]=CREATE_ABC(OP_CALL,0,1,1);
-  }
-  f->code[pc++]=CREATE_ABC(OP_RETURN,0,1,0);
-  return f;
- }
-}
-
-static int writer(lua_State* L, const void* p, size_t size, void* u)
-{
- UNUSED(L);
- return (fwrite(p,size,1,(FILE*)u)!=1) && (size!=0);
-}
-
-struct Smain {
- int argc;
- char** argv;
-};
-
-static int pmain(lua_State* L)
-{
- struct Smain* s = (struct Smain*)lua_touserdata(L, 1);
- int argc=s->argc;
- char** argv=s->argv;
- const Proto* f;
- int i;
- if (!lua_checkstack(L,argc)) fatal("too many input files");
- for (i=0; i<argc; i++)
- {
-  const char* filename=IS("-") ? NULL : argv[i];
-  if (luaL_loadfile(L,filename)!=0) fatal(lua_tostring(L,-1));
- }
- f=combine(L,argc);
- if (listing) luaU_print(f,listing>1);
- if (dumping)
- {
-  FILE* D= (output==NULL) ? stdout : fopen(output,"wb");
-  if (D==NULL) cannot("open");
-  lua_lock(L);
-  int result=luaU_dump_crosscompile(L,f,writer,D,stripping,target);
-  lua_unlock(L);
-  if (result==LUA_ERR_CC_INTOVERFLOW) fatal("value too big or small for target integer type");
-  if (result==LUA_ERR_CC_NOTINTEGER) fatal("target lua_Number is integral but fractional value found");
-  if (ferror(D)) cannot("write");
-  if (fclose(D)) cannot("close");
- }
- return 0;
-}
-
-int main(int argc, char* argv[])
-{
- lua_State* L;
- struct Smain s;
- 
- int test=1;
- target.little_endian=*(char*)&test;
- target.sizeof_int=sizeof(int);
- target.sizeof_strsize_t=sizeof(strsize_t);
- target.sizeof_lua_Number=sizeof(lua_Number);
- target.lua_Number_integral=(((lua_Number)0.5)==0);
- target.is_arm_fpa=0;
-
- int i=doargs(argc,argv);
- argc-=i; argv+=i;
- if (argc<=0) usage("no input files given");
- L=lua_open();
- if (L==NULL) fatal("not enough memory for state");
- s.argc=argc;
- s.argv=argv;
- if (lua_cpcall(L,pmain,&s)!=0) fatal(lua_tostring(L,-1));
- lua_close(L);
- return EXIT_SUCCESS;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/luaconf.h
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/luaconf.h b/libs/elua/elua_base/src/luaconf.h
deleted file mode 100644
index 8711489..0000000
--- a/libs/elua/elua_base/src/luaconf.h
+++ /dev/null
@@ -1,891 +0,0 @@
-/*
-** $Id: luaconf.h,v 1.82.1.7 2008/02/11 16:25:08 roberto Exp $
-** Configuration file for Lua
-** See Copyright Notice in lua.h
-*/
-
-
-#ifndef lconfig_h
-#define lconfig_h
-
-#include <limits.h>
-#include <stddef.h>
-
-/*
-** ==================================================================
-** Search for "@@" to find all configurable definitions.
-** ===================================================================
-*/
-
-
-/*
-@@ LUA_ANSI controls the use of non-ansi features.
-** CHANGE it (define it) if you want Lua to avoid the use of any
-** non-ansi feature or library.
-*/
-#if defined(__STRICT_ANSI__)
-#define LUA_ANSI
-#endif
-
-
-#if !defined(LUA_ANSI) && defined(_WIN32)
-#define LUA_WIN
-#endif
-
-#if defined(LUA_USE_LINUX)
-#define LUA_USE_POSIX
-#define LUA_USE_DLOPEN		/* needs an extra library: -ldl */
-#define LUA_USE_READLINE	/* needs some extra libraries */
-#endif
-
-#if defined(LUA_USE_MACOSX)
-#define LUA_USE_POSIX
-#define LUA_DL_DYLD		/* does not need extra library */
-#endif
-
-
-
-/*
-@@ LUA_USE_POSIX includes all functionallity listed as X/Open System
-@* Interfaces Extension (XSI).
-** CHANGE it (define it) if your system is XSI compatible.
-*/
-#if defined(LUA_USE_POSIX)
-#define LUA_USE_MKSTEMP
-#define LUA_USE_ISATTY
-#define LUA_USE_POPEN
-#define LUA_USE_ULONGJMP
-#endif
-
-
-/*
-@@ LUA_PATH and LUA_CPATH are the names of the environment variables that
-@* Lua check to set its paths.
-@@ LUA_INIT is the name of the environment variable that Lua
-@* checks for initialization code.
-** CHANGE them if you want different names.
-*/
-#define LUA_PATH        "LUA_PATH"
-#define LUA_CPATH       "LUA_CPATH"
-#define LUA_INIT	"LUA_INIT"
-
-
-/*
-@@ LUA_PATH_DEFAULT is the default path that Lua uses to look for
-@* Lua libraries.
-@@ LUA_CPATH_DEFAULT is the default path that Lua uses to look for
-@* C libraries.
-** CHANGE them if your machine has a non-conventional directory
-** hierarchy or if you want to install your libraries in
-** non-conventional directories.
-*/
-#if defined(_WIN32)
-/*
-** In Windows, any exclamation mark ('!') in the path is replaced by the
-** path of the directory of the executable file of the current process.
-*/
-#define LUA_LDIR	"!\\lua\\"
-#define LUA_CDIR	"!\\"
-
-//## Modified for eLua
-//## Defaults search modules path to our ROM File System
-#ifndef LUA_RPC
-
-#ifndef LUA_PATH_DEFAULT
-#define LUA_PATH_DEFAULT  "/rfs/?.lua;/rfs/?.lc;/mmc/?.lua;/mmc/?.lc;/wo/?.lua;/wo/?.lc;/rom/?.lua;/rom/?.lc;/semi/?.lua;/semi/?.lc;"
-#endif
-
-#define LUA_CPATH_DEFAULT ""
-#else // #ifndef LUA_RPC
-#define LUA_PATH_DEFAULT  \
-		".\\?.lua;"  LUA_LDIR"?.lua;"  LUA_LDIR"?\\init.lua;" \
-		             LUA_CDIR"?.lua;"  LUA_CDIR"?\\init.lua"
-#define LUA_CPATH_DEFAULT \
-	".\\?.dll;"  LUA_CDIR"?.dll;" LUA_CDIR"loadall.dll"
-#endif // #ifndef LUA_RPC
-
-#else // #if defined(_WIN32)
-
-#define LUA_ROOT	"/usr/local/"
-#define LUA_LDIR	LUA_ROOT "share/lua/5.1/"
-#define LUA_CDIR	LUA_ROOT "lib/lua/5.1/"
-
-#ifndef LUA_RPC
-#ifndef LUA_PATH_DEFAULT
-#define LUA_PATH_DEFAULT  "/mmc/?.lua;/mmc/?.lc;/wo/?.lua;/wo/?.lc;/rom/?.lua;/rom/?.lc;/semi/?.lua;/semi/?.lc;"
-#endif
-#define LUA_CPATH_DEFAULT ""
-#else // #ifndef LUA_RPC
-#define LUA_PATH_DEFAULT  \
-		"./?.lua;"  LUA_LDIR"?.lua;"  LUA_LDIR"?/init.lua;" \
-		            LUA_CDIR"?.lua;"  LUA_CDIR"?/init.lua"
-#define LUA_CPATH_DEFAULT \
-	"./?.so;"  LUA_CDIR"?.so;" LUA_CDIR"loadall.so"
-#endif // #ifndef LUA_RPC
-
-#endif // #if defined(_WIN32)
-
-
-/*
-@@ LUA_DIRSEP is the directory separator (for submodules).
-** CHANGE it if your machine does not use "/" as the directory separator
-** and is not Windows. (On Windows Lua automatically uses "\".)
-*/
-#if defined(_WIN32)
-#define LUA_DIRSEP	"\\"
-#else
-#define LUA_DIRSEP	"/"
-#endif
-
-
-/*
-@@ LUA_PATHSEP is the character that separates templates in a path.
-@@ LUA_PATH_MARK is the string that marks the substitution points in a
-@* template.
-@@ LUA_EXECDIR in a Windows path is replaced by the executable's
-@* directory.
-@@ LUA_IGMARK is a mark to ignore all before it when bulding the
-@* luaopen_ function name.
-** CHANGE them if for some reason your system cannot use those
-** characters. (E.g., if one of those characters is a common character
-** in file/directory names.) Probably you do not need to change them.
-*/
-#define LUA_PATHSEP	";"
-#define LUA_PATH_MARK	"?"
-#define LUA_EXECDIR	"!"
-#define LUA_IGMARK	"-"
-
-
-/*
-@@ LUA_INTEGER is the integral type used by lua_pushinteger/lua_tointeger.
-** CHANGE that if ptrdiff_t is not adequate on your machine. (On most
-** machines, ptrdiff_t gives a good choice between int or long.)
-*/
-
-/* Changed to long for use with integral Lua numbers. */
-#if !defined LUA_NUMBER_INTEGRAL
-#define LUA_INTEGER ptrdiff_t
-#else
-  #if !defined LUA_INTEGRAL_LONGLONG
-  #define LUA_INTEGER	long
-  #else
-  #define LUA_INTEGER long long
-  #endif // #if !defined LUA_INTEGRAL_LONGLONG
-#endif // #if !defined LUA_NUMBER_INTEGRAL
-
-/*
-@@ LUA_API is a mark for all core API functions.
-@@ LUALIB_API is a mark for all standard library functions.
-** CHANGE them if you need to define those functions in some special way.
-** For instance, if you want to create one Windows DLL with the core and
-** the libraries, you may want to use the following definition (define
-** LUA_BUILD_AS_DLL to get it).
-*/
-#if defined(LUA_BUILD_AS_DLL)
-
-#if defined(LUA_CORE) || defined(LUA_LIB)
-#define LUA_API __declspec(dllexport)
-#else
-#define LUA_API __declspec(dllimport)
-#endif
-
-#else
-
-#define LUA_API		extern
-
-#endif
-
-/* more often than not the libs go together with the core */
-#define LUALIB_API	LUA_API
-
-
-/*
-@@ LUAI_FUNC is a mark for all extern functions that are not to be
-@* exported to outside modules.
-@@ LUAI_DATA is a mark for all extern (const) variables that are not to
-@* be exported to outside modules.
-** CHANGE them if you need to mark them in some special way. Elf/gcc
-** (versions 3.2 and later) mark them as "hidden" to optimize access
-** when Lua is compiled as a shared library.
-*/
-#if defined(luaall_c)
-#define LUAI_FUNC	static
-#define LUAI_DATA	/* empty */
-
-#elif defined(__GNUC__) && ((__GNUC__*100 + __GNUC_MINOR__) >= 302) && \
-      defined(__ELF__)
-#define LUAI_FUNC	__attribute__((visibility("hidden"))) extern
-#define LUAI_DATA	LUAI_FUNC
-
-#else
-#define LUAI_FUNC	extern
-#define LUAI_DATA	extern
-#endif
-
-
-
-/*
-@@ LUA_QL describes how error messages quote program elements.
-** CHANGE it if you want a different appearance.
-*/
-#define LUA_QL(x)	"'" x "'"
-#define LUA_QS		LUA_QL("%s")
-
-
-/*
-@@ LUA_IDSIZE gives the maximum size for the description of the source
-@* of a function in debug information.
-** CHANGE it if you want a different size.
-*/
-#define LUA_IDSIZE	60
-
-
-/*
-** {==================================================================
-** Stand-alone configuration
-** ===================================================================
-*/
-
-#if defined(lua_c) || defined(luaall_c)
-
-/*
-@@ lua_stdin_is_tty detects whether the standard input is a 'tty' (that
-@* is, whether we're running lua interactively).
-** CHANGE it if you have a better definition for non-POSIX/non-Windows
-** systems.
-*/
-#if defined(LUA_USE_ISATTY)
-#include <unistd.h>
-#define lua_stdin_is_tty()	isatty(0)
-#elif defined(LUA_WIN)
-#include <io.h>
-#include <stdio.h>
-#define lua_stdin_is_tty()	_isatty(_fileno(stdin))
-#else
-#define lua_stdin_is_tty()	1  /* assume stdin is a tty */
-#endif
-
-
-/*
-@@ LUA_PROMPT is the default prompt used by stand-alone Lua.
-@@ LUA_PROMPT2 is the default continuation prompt used by stand-alone Lua.
-** CHANGE them if you want different prompts. (You can also change the
-** prompts dynamically, assigning to globals _PROMPT/_PROMPT2.)
-*/
-#define LUA_PROMPT		"> "
-#define LUA_PROMPT2		">> "
-
-
-/*
-@@ LUA_PROGNAME is the default name for the stand-alone Lua program.
-** CHANGE it if your stand-alone interpreter has a different name and
-** your system is not able to detect that name automatically.
-*/
-#define LUA_PROGNAME		"lua"
-
-
-/*
-@@ LUA_MAXINPUT is the maximum length for an input line in the
-@* stand-alone interpreter.
-** CHANGE it if you need longer lines.
-*/
-#define LUA_MAXINPUT	128
-               
-
-/*
-@@ lua_readline defines how to show a prompt and then read a line from
-@* the standard input.
-@@ lua_saveline defines how to "save" a read line in a "history".
-@@ lua_freeline defines how to free a line read by lua_readline.
-** CHANGE them if you want to improve this functionality (e.g., by using
-** GNU readline and history facilities).
-*/
-#if defined(LUA_CROSS_COMPILER)
-#if defined(LUA_USE_READLINE)
-#include <stdio.h>
-#include <readline/readline.h>
-#include <readline/history.h>
-#define lua_readline(L,b,p)	((void)L, ((b)=readline(p)) != NULL)
-#define lua_saveline(L,idx) \
-	if (lua_strlen(L,idx) > 0)  /* non-empty line? */ \
-	  add_history(lua_tostring(L, idx));  /* add it to history */
-#define lua_freeline(L,b)	((void)L, free(b))
-#elif defined(LUA_USE_LINENOISE) // #if defined(LUA_USE_READLINE)
-#include "linenoise_posix.h"
-#define lua_readline(L,b,p)     ((void)L, ((b)=linenoise(p)) != NULL)
-#define lua_saveline(L,idx) \
-  if (lua_strlen(L,idx) > 0)  /* non-empty line? */ \
-    linenoiseHistoryAdd(lua_tostring(L, idx));  /* add it to history */
-#define lua_freeline(L,b)       ((void)L, free(b))
-#else // #if defined(LUA_USE_READLINE)
-#define lua_readline(L,b,p)	\
-	((void)L, fputs(p, stdout), fflush(stdout),  /* show prompt */ \
-	fgets(b, LUA_MAXINPUT, stdin) != NULL)  /* get line */
-#define lua_saveline(L,idx)	{ (void)L; (void)idx; }
-#define lua_freeline(L,b)	{ (void)L; (void)b; }
-#endif // #if defined(LUA_USE_READLINE)
-
-#else // #if defined(LUA_CROSS_COMPILER)
-
-#include "linenoise.h"
-#define lua_readline(L,b,p)	((void)L, (linenoise_getline(LINENOISE_ID_LUA,b,LUA_MAXINPUT,p)) != -1)
-#define lua_saveline(L,idx) \
-	if (lua_strlen(L,idx) > 0)  /* non-empty line? */ \
-	  linenoise_addhistory(LINENOISE_ID_LUA, lua_tostring(L, idx));  /* add it to history */
-#define lua_freeline(L,b)	{ (void)L; (void)b; }
-
-#endif // #if defined(LUA_CROSS_COMPILER)
-
-#endif
-
-/* }================================================================== */
-
-
-/*
-@@ LUAI_GCPAUSE defines the default pause between garbage-collector cycles
-@* as a percentage.
-** CHANGE it if you want the GC to run faster or slower (higher values
-** mean larger pauses which mean slower collection.) You can also change
-** this value dynamically.
-*/
-#define LUAI_GCPAUSE	110  /* 110% (wait memory to grow 10% before next gc) */
-
-
-/*
-@@ LUAI_GCMUL defines the default speed of garbage collection relative to
-@* memory allocation as a percentage.
-** CHANGE it if you want to change the granularity of the garbage
-** collection. (Higher values mean coarser collections. 0 represents
-** infinity, where each step performs a full collection.) You can also
-** change this value dynamically.
-*/
-#define LUAI_GCMUL	200 /* GC runs 'twice the speed' of memory allocation */
-
-
-
-/*
-@@ LUA_COMPAT_GETN controls compatibility with old getn behavior.
-** CHANGE it (define it) if you want exact compatibility with the
-** behavior of setn/getn in Lua 5.0.
-*/
-#undef LUA_COMPAT_GETN
-
-/*
-@@ LUA_COMPAT_LOADLIB controls compatibility about global loadlib.
-** CHANGE it to undefined as soon as you do not need a global 'loadlib'
-** function (the function is still available as 'package.loadlib').
-*/
-#undef LUA_COMPAT_LOADLIB
-
-/*
-@@ LUA_COMPAT_VARARG controls compatibility with old vararg feature.
-** CHANGE it to undefined as soon as your programs use only '...' to
-** access vararg parameters (instead of the old 'arg' table).
-*/
-#define LUA_COMPAT_VARARG
-
-/*
-@@ LUA_COMPAT_MOD controls compatibility with old math.mod function.
-** CHANGE it to undefined as soon as your programs use 'math.fmod' or
-** the new '%' operator instead of 'math.mod'.
-*/
-#define LUA_COMPAT_MOD
-
-/*
-@@ LUA_COMPAT_LSTR controls compatibility with old long string nesting
-@* facility.
-** CHANGE it to 2 if you want the old behaviour, or undefine it to turn
-** off the advisory error when nesting [[...]].
-*/
-#define LUA_COMPAT_LSTR		1
-
-/*
-@@ LUA_COMPAT_GFIND controls compatibility with old 'string.gfind' name.
-** CHANGE it to undefined as soon as you rename 'string.gfind' to
-** 'string.gmatch'.
-*/
-#define LUA_COMPAT_GFIND
-
-/*
-@@ LUA_COMPAT_OPENLIB controls compatibility with old 'luaL_openlib'
-@* behavior.
-** CHANGE it to undefined as soon as you replace to 'luaL_register'
-** your uses of 'luaL_openlib'
-*/
-#define LUA_COMPAT_OPENLIB
-
-/*
-@@ LUA_STRESS_EMERGENCY_GC enables stress testing code for the Emergency GC.
-** CHANGE it to defined if you want to test for Emergency GC related bugs.
-** Note that this will make the Lua vm very slow, since it will force a
-** full GC on every new allocation.
-*/
-#undef LUA_STRESS_EMERGENCY_GC
-
-/*
-@@ luai_apicheck is the assert macro used by the Lua-C API.
-** CHANGE luai_apicheck if you want Lua to perform some checks in the
-** parameters it gets from API calls. This may slow down the interpreter
-** a bit, but may be quite useful when debugging C code that interfaces
-** with Lua. A useful redefinition is to use assert.h.
-*/
-#if defined(LUA_USE_APICHECK)
-#include <assert.h>
-#define luai_apicheck(L,o)	{ (void)L; assert(o); }
-#else
-#define luai_apicheck(L,o)	{ (void)L; }
-#endif
-
-
-/*
-@@ LUAI_BITSINT defines the number of bits in an int.
-** CHANGE here if Lua cannot automatically detect the number of bits of
-** your machine. Probably you do not need to change this.
-*/
-/* avoid overflows in comparison */
-#if INT_MAX-20 < 32760
-#define LUAI_BITSINT	16
-#elif INT_MAX > 2147483640L
-/* int has at least 32 bits */
-#define LUAI_BITSINT	32
-#else
-#error "you must define LUA_BITSINT with number of bits in an integer"
-#endif
-
-
-/*
-@@ LUAI_UINT32 is an unsigned integer with at least 32 bits.
-@@ LUAI_INT32 is an signed integer with at least 32 bits.
-@@ LUAI_UMEM is an unsigned integer big enough to count the total
-@* memory used by Lua.
-@@ LUAI_MEM is a signed integer big enough to count the total memory
-@* used by Lua.
-** CHANGE here if for some weird reason the default definitions are not
-** good enough for your machine. (The definitions in the 'else'
-** part always works, but may waste space on machines with 64-bit
-** longs.) Probably you do not need to change this.
-*/
-#if LUAI_BITSINT >= 32
-#define LUAI_UINT32	unsigned int
-#define LUAI_INT32	int
-#define LUAI_MAXINT32	INT_MAX
-#define LUAI_UMEM	size_t
-#define LUAI_MEM	ptrdiff_t
-#else
-/* 16-bit ints */
-#define LUAI_UINT32	unsigned long
-#define LUAI_INT32	long
-#define LUAI_MAXINT32	LONG_MAX
-#define LUAI_UMEM	unsigned long
-#define LUAI_MEM	long
-#endif
-
-
-/*
-@@ LUAI_MAXCALLS limits the number of nested calls.
-** CHANGE it if you need really deep recursive calls. This limit is
-** arbitrary; its only purpose is to stop infinite recursion before
-** exhausting memory.
-*/
-#define LUAI_MAXCALLS	20000
-
-
-/*
-@@ LUAI_MAXCSTACK limits the number of Lua stack slots that a C function
-@* can use.
-** CHANGE it if you need lots of (Lua) stack space for your C
-** functions. This limit is arbitrary; its only purpose is to stop C
-** functions to consume unlimited stack space. (must be smaller than
-** -LUA_REGISTRYINDEX)
-*/
-#define LUAI_MAXCSTACK	8000
-
-
-
-/*
-** {==================================================================
-** CHANGE (to smaller values) the following definitions if your system
-** has a small C stack. (Or you may want to change them to larger
-** values if your system has a large C stack and these limits are
-** too rigid for you.) Some of these constants control the size of
-** stack-allocated arrays used by the compiler or the interpreter, while
-** others limit the maximum number of recursive calls that the compiler
-** or the interpreter can perform. Values too large may cause a C stack
-** overflow for some forms of deep constructs.
-** ===================================================================
-*/
-
-
-/*
-@@ LUAI_MAXCCALLS is the maximum depth for nested C calls (short) and
-@* syntactical nested non-terminals in a program.
-*/
-#define LUAI_MAXCCALLS		200
-
-
-/*
-@@ LUAI_MAXVARS is the maximum number of local variables per function
-@* (must be smaller than 250).
-*/
-#define LUAI_MAXVARS		50
-
-
-/*
-@@ LUAI_MAXUPVALUES is the maximum number of upvalues per function
-@* (must be smaller than 250).
-*/
-#define LUAI_MAXUPVALUES	60
-
-
-/*
-@@ LUAL_BUFFERSIZE is the buffer size used by the lauxlib buffer system.
-*/
-#define LUAL_BUFFERSIZE		BUFSIZ
-
-/* }================================================================== */
-
-
-
-
-/*
-** {==================================================================
-@@ LUA_NUMBER is the type of numbers in Lua.
-** CHANGE the following definitions only if you want to build Lua
-** with a number type different from double. You may also need to
-** change lua_number2int & lua_number2integer.
-** ===================================================================
-*/
-
-/* Define LUA_NUMBER_INTEGRAL to produce a system that uses no
-   floating point operations by changing the type of Lua numbers from
-   double to long.  It implements division and modulus so that 
-
-   x == (x / y) * y + x % y.  
-   
-   The exponentiation function returns zero for negative exponents.
-   Defining LUA_NUMBER_INTEGRAL also removes the difftime function,
-   and the math module should not be used.  The string.format function
-   no longer handles the floating point directives %e, %E, %f, %g, and
-   %G. */
-
-#if defined LUA_NUMBER_INTEGRAL
-#define LUA_NUMBER	LUA_INTEGER
-#else
-#define LUA_NUMBER_DOUBLE
-#define LUA_NUMBER	double
-#endif
-
-/*
-@@ LUAI_UACNUMBER is the result of an 'usual argument conversion'
-@* over a number.
-*/
-#define LUAI_UACNUMBER	LUA_NUMBER
-
-
-/*
-@@ LUA_NUMBER_SCAN is the format for reading numbers.
-@@ LUA_NUMBER_FMT is the format for writing numbers.
-@@ lua_number2str converts a number to a string.
-@@ LUAI_MAXNUMBER2STR is maximum size of previous conversion.
-@@ lua_str2number converts a string to a number.
-*/
-#if defined LUA_NUMBER_INTEGRAL
-  #if !defined LUA_INTEGRAL_LONGLONG
-  #define LUA_NUMBER_SCAN		"%ld"
-  #define LUA_NUMBER_FMT		"%ld"
-  #else
-  #define LUA_NUMBER_SCAN   "%lld"
-  #define LUA_NUMBER_FMT    "%lld"
-  #endif // #if !defined LUA_INTEGRAL_LONGLONG
-#else
-#define LUA_NUMBER_SCAN		"%lf"
-#define LUA_NUMBER_FMT		"%.14g"
-#endif // #if defined LUA_NUMBER_INTEGRAL
-#define lua_number2str(s,n)	sprintf((s), LUA_NUMBER_FMT, (n))
-#define LUAI_MAXNUMBER2STR	32 /* 16 digits, sign, point, and \0 */
-#if defined LUA_NUMBER_INTEGRAL
-  #if !defined LUA_INTEGRAL_LONGLONG
-  #define lua_str2number(s,p)	strtol((s), (p), 10)
-  #else
-  #define lua_str2number(s,p) strtoll((s), (p), 10)
-  #endif // #if !defined LUA_INTEGRAL_LONGLONG
-#else
-#define lua_str2number(s,p)	strtod((s), (p))
-#endif // #if defined LUA_NUMBER_INTEGRAL
-
-/*
-@@ The luai_num* macros define the primitive operations over numbers.
-*/
-#if defined(LUA_CORE)
-#include <math.h>
-#define luai_numadd(a,b)	((a)+(b))
-#define luai_numsub(a,b)	((a)-(b))
-#define luai_nummul(a,b)	((a)*(b))
-#if defined LUA_NUMBER_INTEGRAL
-#define luai_numdiv(a,b)	\
-  (-1/2?			\
-   (a)/(b):			\
-   ((((a)<0)==((b)<0))||(((a)%(b))==0)?	\
-    (a)/(b):			\
-    (a)/(b)-1))
-#define luai_nummod(a,b)	\
-  (-1/2?			\
-   (a)%(b):			\
-   ((((a)<0)==((b)<0))||(((a)%(b))==0)?	\
-    (a)%(b):			\
-    (a)%(b)+(b)))
-#define luai_lnumdiv(a,b)	\
-  ((b)==0?			\
-   (luaG_runerror(L,"divide by zero"),0): \
-   luai_numdiv(a,b))
-#define luai_lnummod(a,b)	\
-  ((b)==0?			\
-   (luaG_runerror(L,"modulo by zero"),0): \
-   luai_nummod(a,b))
-LUA_NUMBER luai_ipow(LUA_NUMBER, LUA_NUMBER);
-#define luai_numpow(a,b)	(luai_ipow(a,b))
-#else
-#define luai_numdiv(a,b)	((a)/(b))
-#define luai_nummod(a,b)	((a) - floor((a)/(b))*(b))
-#define luai_lnumdiv(a,b)	(luai_numdiv(a,b))
-#define luai_lnummod(a,b)	(luai_nummod(a,b))
-#define luai_numpow(a,b)	(pow(a,b))
-#endif
-#define luai_numunm(a)		(-(a))
-#define luai_numeq(a,b)		((a)==(b))
-#define luai_numlt(a,b)		((a)<(b))
-#define luai_numle(a,b)		((a)<=(b))
-#define luai_numisnan(a)	(!luai_numeq((a), (a)))
-#endif
-
-
-/*
-@@ lua_number2int is a macro to convert lua_Number to int.
-@@ lua_number2integer is a macro to convert lua_Number to lua_Integer.
-** CHANGE them if you know a faster way to convert a lua_Number to
-** int (with any rounding method and without throwing errors) in your
-** system. In Pentium machines, a naive typecast from double to int
-** in C is extremely slow, so any alternative is worth trying.
-*/
-
-/* On a Pentium, resort to a trick */
-#if defined(LUA_NUMBER_DOUBLE) && !defined(LUA_ANSI) && !defined(__SSE2__) && \
-    (defined(__i386) || defined (_M_IX86) || defined(__i386__))
-
-/* On a Microsoft compiler, use assembler */
-#if defined(_MSC_VER)
-
-#define lua_number2int(i,d)   __asm fld d   __asm fistp i
-#define lua_number2integer(i,n)		lua_number2int(i, n)
-
-/* the next trick should work on any Pentium, but sometimes clashes
-   with a DirectX idiosyncrasy */
-#else
-
-union luai_Cast { double l_d; long l_l; };
-#define lua_number2int(i,d) \
-  { volatile union luai_Cast u; u.l_d = (d) + 6755399441055744.0; (i) = u.l_l; }
-#define lua_number2integer(i,n)		lua_number2int(i, n)
-
-#endif
-
-
-/* this option always works, but may be slow */
-#else
-#define lua_number2int(i,d)	((i)=(int)(d))
-#define lua_number2integer(i,d)	((i)=(lua_Integer)(d))
-
-#endif
-
-/* }================================================================== */
-
-
-/*
-@@ LUAI_USER_ALIGNMENT_T is a type that requires maximum alignment.
-** CHANGE it if your system requires alignments larger than double. (For
-** instance, if your system supports long doubles and they must be
-** aligned in 16-byte boundaries, then you should add long double in the
-** union.) Probably you do not need to change this.
-*/
-#define LUAI_USER_ALIGNMENT_T	union { double u; void *s; long l; }
-
-
-/*
-@@ LUAI_THROW/LUAI_TRY define how Lua does exception handling.
-** CHANGE them if you prefer to use longjmp/setjmp even with C++
-** or if want/don't to use _longjmp/_setjmp instead of regular
-** longjmp/setjmp. By default, Lua handles errors with exceptions when
-** compiling as C++ code, with _longjmp/_setjmp when asked to use them,
-** and with longjmp/setjmp otherwise.
-*/
-#if defined(__cplusplus)
-/* C++ exceptions */
-#define LUAI_THROW(L,c)	throw(c)
-#define LUAI_TRY(L,c,a)	try { a } catch(...) \
-	{ if ((c)->status == 0) (c)->status = -1; }
-#define luai_jmpbuf	int  /* dummy variable */
-
-#elif defined(LUA_USE_ULONGJMP)
-/* in Unix, try _longjmp/_setjmp (more efficient) */
-#define LUAI_THROW(L,c)	_longjmp((c)->b, 1)
-#define LUAI_TRY(L,c,a)	if (_setjmp((c)->b) == 0) { a }
-#define luai_jmpbuf	jmp_buf
-
-#else
-/* default handling with long jumps */
-#define LUAI_THROW(L,c)	longjmp((c)->b, 1)
-#define LUAI_TRY(L,c,a)	if (setjmp((c)->b) == 0) { a }
-#define luai_jmpbuf	jmp_buf
-
-#endif
-
-
-/*
-@@ LUA_MAXCAPTURES is the maximum number of captures that a pattern
-@* can do during pattern-matching.
-** CHANGE it if you need more captures. This limit is arbitrary.
-*/
-#define LUA_MAXCAPTURES		10
-
-
-/*
-@@ lua_tmpnam is the function that the OS library uses to create a
-@* temporary name.
-@@ LUA_TMPNAMBUFSIZE is the maximum size of a name created by lua_tmpnam.
-** CHANGE them if you have an alternative to tmpnam (which is considered
-** insecure) or if you want the original tmpnam anyway.  By default, Lua
-** uses tmpnam except when POSIX is available, where it uses mkstemp.
-*/
-#if defined(loslib_c) || defined(luaall_c)
-
-#if defined(LUA_USE_MKSTEMP)
-#include <unistd.h>
-#define LUA_TMPNAMBUFSIZE	32
-#define lua_tmpnam(b,e)	{ \
-	strcpy(b, "/tmp/lua_XXXXXX"); \
-	e = mkstemp(b); \
-	if (e != -1) close(e); \
-	e = (e == -1); }
-
-#else
-#define LUA_TMPNAMBUFSIZE	L_tmpnam
-#define lua_tmpnam(b,e)		{ e = (tmpnam(b) == NULL); }
-#endif
-
-#endif
-
-
-/*
-@@ lua_popen spawns a new process connected to the current one through
-@* the file streams.
-** CHANGE it if you have a way to implement it in your system.
-*/
-#if defined(LUA_USE_POPEN)
-
-#define lua_popen(L,c,m)	((void)L, fflush(NULL), popen(c,m))
-#define lua_pclose(L,file)	((void)L, (pclose(file) != -1))
-
-#elif defined(LUA_WIN)
-
-#define lua_popen(L,c,m)	((void)L, _popen(c,m))
-#define lua_pclose(L,file)	((void)L, (_pclose(file) != -1))
-
-#else
-
-#define lua_popen(L,c,m)	((void)((void)c, m),  \
-		luaL_error(L, LUA_QL("popen") " not supported"), (FILE*)0)
-#define lua_pclose(L,file)		((void)((void)L, file), 0)
-
-#endif
-
-/*
-@@ LUA_DL_* define which dynamic-library system Lua should use.
-** CHANGE here if Lua has problems choosing the appropriate
-** dynamic-library system for your platform (either Windows' DLL, Mac's
-** dyld, or Unix's dlopen). If your system is some kind of Unix, there
-** is a good chance that it has dlopen, so LUA_DL_DLOPEN will work for
-** it.  To use dlopen you also need to adapt the src/Makefile (probably
-** adding -ldl to the linker options), so Lua does not select it
-** automatically.  (When you change the makefile to add -ldl, you must
-** also add -DLUA_USE_DLOPEN.)
-** If you do not want any kind of dynamic library, undefine all these
-** options.
-** By default, _WIN32 gets LUA_DL_DLL and MAC OS X gets LUA_DL_DYLD.
-*/
-#if defined(LUA_USE_DLOPEN)
-#define LUA_DL_DLOPEN
-#endif
-
-#if defined(LUA_WIN)
-#define LUA_DL_DLL
-#endif
-
-
-/*
-@@ LUAI_EXTRASPACE allows you to add user-specific data in a lua_State
-@* (the data goes just *before* the lua_State pointer).
-** CHANGE (define) this if you really need that. This value must be
-** a multiple of the maximum alignment required for your machine.
-*/
-#define LUAI_EXTRASPACE		0
-
-
-/*
-@@ luai_userstate* allow user-specific actions on threads.
-** CHANGE them if you defined LUAI_EXTRASPACE and need to do something
-** extra when a thread is created/deleted/resumed/yielded.
-*/
-#define luai_userstateopen(L)		((void)L)
-#define luai_userstateclose(L)		((void)L)
-#define luai_userstatethread(L,L1)	((void)L)
-#define luai_userstatefree(L)		((void)L)
-#define luai_userstateresume(L,n)	((void)L)
-#define luai_userstateyield(L,n)	((void)L)
-
-
-/*
-@@ LUA_INTFRMLEN is the length modifier for integer conversions
-@* in 'string.format'.
-@@ LUA_INTFRM_T is the integer type correspoding to the previous length
-@* modifier.
-** CHANGE them if your system supports long long or does not support long.
-*/
-
-#if defined(LUA_USELONGLONG) || defined(LUA_INTEGRAL_LONGLONG)
-
-#define LUA_INTFRMLEN		"ll"
-#define LUA_INTFRM_T		long long
-
-#else
-
-#define LUA_INTFRMLEN		"l"
-#define LUA_INTFRM_T		long
-
-#endif
-
-
-
-/* =================================================================== */
-
-/*
-** Local configuration. You can use this space to add your redefinitions
-** without modifying the main part of the file.
-*/
-
-#if !defined(LUA_CROSS_COMPILER)
-typedef short int16_t;
-typedef long int32_t;
-#endif
-
-/* If you define the next macro you'll get the ability to set rotables as
-   metatables for tables/userdata/types (but the VM might run slower)
-*/
-#if (LUA_OPTIMIZE_MEMORY == 2) && !defined(LUA_CROSS_COMPILER)
-#define LUA_META_ROTABLES 
-#endif
-
-#if LUA_OPTIMIZE_MEMORY == 2 && defined(LUA_USE_POPEN)
-#error "Pipes not supported in aggresive optimization mode (LUA_OPTIMIZE_MEMORY=2)"
-#endif
-
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/lualib.h
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/lualib.h b/libs/elua/elua_base/src/lualib.h
deleted file mode 100644
index 469417f..0000000
--- a/libs/elua/elua_base/src/lualib.h
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
-** $Id: lualib.h,v 1.36.1.1 2007/12/27 13:02:25 roberto Exp $
-** Lua standard libraries
-** See Copyright Notice in lua.h
-*/
-
-
-#ifndef lualib_h
-#define lualib_h
-
-#include "lua.h"
-
-
-/* Key to file-handle type */
-#define LUA_FILEHANDLE		"FILE*"
-
-
-#define LUA_COLIBNAME	"coroutine"
-LUALIB_API int (luaopen_base) (lua_State *L);
-
-#define LUA_TABLIBNAME	"table"
-LUALIB_API int (luaopen_table) (lua_State *L);
-
-#define LUA_IOLIBNAME	"io"
-LUALIB_API int (luaopen_io) (lua_State *L);
-
-#define LUA_OSLIBNAME	"os"
-LUALIB_API int (luaopen_os) (lua_State *L);
-
-#define LUA_STRLIBNAME	"string"
-LUALIB_API int (luaopen_string) (lua_State *L);
-
-#define LUA_MATHLIBNAME	"math"
-LUALIB_API int (luaopen_math) (lua_State *L);
-
-#define LUA_DBLIBNAME	"debug"
-LUALIB_API int (luaopen_debug) (lua_State *L);
-
-#define LUA_LOADLIBNAME	"package"
-LUALIB_API int (luaopen_package) (lua_State *L);
-
-
-/* open all previous libraries */
-LUALIB_API void (luaL_openlibs) (lua_State *L); 
-
-
-
-#ifndef lua_assert
-#define lua_assert(x)	((void)0)
-#endif
-
-
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/lundump.c
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/lundump.c b/libs/elua/elua_base/src/lundump.c
deleted file mode 100644
index aa87c4e..0000000
--- a/libs/elua/elua_base/src/lundump.c
+++ /dev/null
@@ -1,336 +0,0 @@
-/*
-** $Id: lundump.c,v 2.7.1.4 2008/04/04 19:51:41 roberto Exp $
-** load precompiled Lua chunks
-** See Copyright Notice in lua.h
-*/
-
-#include <string.h>
-
-#define lundump_c
-#define LUA_CORE
-
-#include "lua.h"
-
-#include "ldebug.h"
-#include "ldo.h"
-#include "lfunc.h"
-#include "lmem.h"
-#include "lobject.h"
-#include "lstring.h"
-#include "lundump.h"
-#include "lzio.h"
-
-typedef struct {
- lua_State* L;
- ZIO* Z;
- Mbuffer* b;
- const char* name;
- int swap;
- int numsize;
- int toflt;
- size_t total;
-} LoadState;
-
-#ifdef LUAC_TRUST_BINARIES
-#define IF(c,s)
-#define error(S,s)
-#else
-#define IF(c,s)		if (c) error(S,s)
-
-static void error(LoadState* S, const char* why)
-{
- luaO_pushfstring(S->L,"%s: %s in precompiled chunk",S->name,why);
- luaD_throw(S->L,LUA_ERRSYNTAX);
-}
-#endif
-
-#define	LoadByte(S)		(lu_byte)LoadChar(S)
-#define LoadVar(S,x)		LoadMem(S,&x,1,sizeof(x))
-#define LoadVector(S,b,n,size)	LoadMem(S,b,n,size)
-
-static void LoadBlock(LoadState* S, void* b, size_t size)
-{
- size_t r=luaZ_read(S->Z,b,size);
- IF (r!=0, "unexpected end");
- S->total+=size;
-}
-
-static void LoadMem (LoadState* S, void* b, int n, size_t size)
-{
-  LoadBlock(S,b,n*size);
-  if (S->swap && b)
-  {
-    char* p=(char*) b;
-    char c;
-    switch (size)
-    {
-      case 1:
-        break;
-      case 2:
-	      while (n--)
-	      {
-	        c=p[0]; p[0]=p[1]; p[1]=c;
-	        p+=2;
-	      }
-  	    break;
-      case 4:
-	      while (n--)
-	      {
-	        c=p[0]; p[0]=p[3]; p[3]=c;
-	        c=p[1]; p[1]=p[2]; p[2]=c;
-	        p+=4;
-	      }
-  	    break;
-      case 8:
-	      while (n--)
-	      {
-          c=p[0]; p[0]=p[7]; p[7]=c;
-          c=p[1]; p[1]=p[6]; p[6]=c;
-          c=p[2]; p[2]=p[5]; p[5]=c;
-          c=p[3]; p[3]=p[4]; p[4]=c;
-          p+=8;
-        }
-  	    break;
-      default:
-   	    IF(1, "bad size");
-  	    break;
-    }
-  }
-}
-
-static int LoadChar(LoadState* S)
-{
- char x;
- LoadVar(S,x);
- return x;
-}
-
-static void Align4(LoadState* S)
-{
- while(S->total&3)
-  LoadChar(S);
-}
-
-static int LoadInt(LoadState* S)
-{
- int x;
- LoadVar(S,x);
- IF (x<0, "bad integer");
- return x;
-}
-
-static lua_Number LoadNumber(LoadState* S)
-{
- lua_Number x;
- if(S->toflt)
- {
-  switch(S->numsize)
-  {
-   case 1: {
-    int8_t y;
-    LoadVar(S,y);
-    x = (lua_Number)y;
-   } break;
-   case 2: {
-    int16_t y;
-    LoadVar(S,y);
-    x = (lua_Number)y;
-   } break;
-   case 4: {
-    int32_t y;
-    LoadVar(S,y);
-    x = (lua_Number)y;
-   } break;
-   case 8: {
-    int64_t y;
-    LoadVar(S,y);
-    x = (lua_Number)y;
-   } break;
-   default: lua_assert(0);
-  }
- }
- else
- {
-  LoadVar(S,x); /* should probably handle more cases for float here... */
- }
- return x;
-}
-
-static TString* LoadString(LoadState* S)
-{
- int32_t size;
- LoadVar(S,size);
- if (size==0)
-  return NULL;
- else
- {
-  char* s;
-  if (!luaZ_direct_mode(S->Z)) {
-   s = luaZ_openspace(S->L,S->b,size);
-   LoadBlock(S,s,size);
-   return luaS_newlstr(S->L,s,size-1); /* remove trailing zero */
-  } else {
-   s = (char*)luaZ_get_crt_address(S->Z);
-   LoadBlock(S,NULL,size);
-   return luaS_newrolstr(S->L,s,size-1);
-  }
- }
-}
-
-static void LoadCode(LoadState* S, Proto* f)
-{
- int n=LoadInt(S);
- Align4(S);
- if (!luaZ_direct_mode(S->Z)) {
-  f->code=luaM_newvector(S->L,n,Instruction);
-  LoadVector(S,f->code,n,sizeof(Instruction));
- } else {
-  f->code=(Instruction*)luaZ_get_crt_address(S->Z);
-  LoadVector(S,NULL,n,sizeof(Instruction));
- }
- f->sizecode=n;
-}
-
-static Proto* LoadFunction(LoadState* S, TString* p);
-
-static void LoadConstants(LoadState* S, Proto* f)
-{
- int i,n;
- n=LoadInt(S);
- f->k=luaM_newvector(S->L,n,TValue);
- f->sizek=n;
- for (i=0; i<n; i++) setnilvalue(&f->k[i]);
- for (i=0; i<n; i++)
- {
-  TValue* o=&f->k[i];
-  int t=LoadChar(S);
-  switch (t)
-  {
-   case LUA_TNIL:
-   	setnilvalue(o);
-	break;
-   case LUA_TBOOLEAN:
-   	setbvalue(o,LoadChar(S)!=0);
-	break;
-   case LUA_TNUMBER:
-	setnvalue(o,LoadNumber(S));
-	break;
-   case LUA_TSTRING:
-	setsvalue2n(S->L,o,LoadString(S));
-	break;
-   default:
-	error(S,"bad constant");
-	break;
-  }
- }
- n=LoadInt(S);
- f->p=luaM_newvector(S->L,n,Proto*);
- f->sizep=n;
- for (i=0; i<n; i++) f->p[i]=NULL;
- for (i=0; i<n; i++) f->p[i]=LoadFunction(S,f->source);
-}
-
-static void LoadDebug(LoadState* S, Proto* f)
-{
- int i,n;
- n=LoadInt(S);
- Align4(S);
- if (!luaZ_direct_mode(S->Z)) {
-   f->lineinfo=luaM_newvector(S->L,n,int);
-   LoadVector(S,f->lineinfo,n,sizeof(int));
- } else {
-   f->lineinfo=(int*)luaZ_get_crt_address(S->Z);
-   LoadVector(S,NULL,n,sizeof(int));
- }
- f->sizelineinfo=n;
- n=LoadInt(S);
- f->locvars=luaM_newvector(S->L,n,LocVar);
- f->sizelocvars=n;
- for (i=0; i<n; i++) f->locvars[i].varname=NULL;
- for (i=0; i<n; i++)
- {
-  f->locvars[i].varname=LoadString(S);
-  f->locvars[i].startpc=LoadInt(S);
-  f->locvars[i].endpc=LoadInt(S);
- }
- n=LoadInt(S);
- f->upvalues=luaM_newvector(S->L,n,TString*);
- f->sizeupvalues=n;
- for (i=0; i<n; i++) f->upvalues[i]=NULL;
- for (i=0; i<n; i++) f->upvalues[i]=LoadString(S);
-}
-
-static Proto* LoadFunction(LoadState* S, TString* p)
-{
- Proto* f;
- if (++S->L->nCcalls > LUAI_MAXCCALLS) error(S,"code too deep");
- f=luaF_newproto(S->L);
- if (luaZ_direct_mode(S->Z)) proto_readonly(f);
- setptvalue2s(S->L,S->L->top,f); incr_top(S->L);
- f->source=LoadString(S); if (f->source==NULL) f->source=p;
- f->linedefined=LoadInt(S);
- f->lastlinedefined=LoadInt(S);
- f->nups=LoadByte(S);
- f->numparams=LoadByte(S);
- f->is_vararg=LoadByte(S);
- f->maxstacksize=LoadByte(S);
- LoadCode(S,f);
- LoadConstants(S,f);
- LoadDebug(S,f);
- IF (!luaG_checkcode(f), "bad code");
- S->L->top--;
- S->L->nCcalls--;
- return f;
-}
-
-static void LoadHeader(LoadState* S)
-{
- char h[LUAC_HEADERSIZE];
- char s[LUAC_HEADERSIZE];
- int intck = (((lua_Number)0.5)==0); /* 0=float, 1=int */
- luaU_header(h);
- LoadBlock(S,s,LUAC_HEADERSIZE);
- S->swap=(s[6]!=h[6]); s[6]=h[6]; /* Check if byte-swapping is needed  */
- S->numsize=h[10]=s[10]; /* length of lua_Number */
- S->toflt=(s[11]>intck); /* check if conversion from int lua_Number to flt is needed */
- if(S->toflt) s[11]=h[11];
- IF (memcmp(h,s,LUAC_HEADERSIZE)!=0, "bad header");
-}
-
-/*
-** load precompiled chunk
-*/
-Proto* luaU_undump (lua_State* L, ZIO* Z, Mbuffer* buff, const char* name)
-{
- LoadState S;
- if (*name=='@' || *name=='=')
-  S.name=name+1;
- else if (*name==LUA_SIGNATURE[0])
-  S.name="binary string";
- else
-  S.name=name;
- S.L=L;
- S.Z=Z;
- S.b=buff;
- LoadHeader(&S);
- S.total=0;
- return LoadFunction(&S,luaS_newliteral(L,"=?"));
-}
-
-/*
-* make header
-*/
-void luaU_header (char* h)
-{
- int x=1;
- memcpy(h,LUA_SIGNATURE,sizeof(LUA_SIGNATURE)-1);
- h+=sizeof(LUA_SIGNATURE)-1;
- *h++=(char)LUAC_VERSION;
- *h++=(char)LUAC_FORMAT;
- *h++=(char)*(char*)&x;				/* endianness */
- *h++=(char)sizeof(int);
- *h++=(char)sizeof(int32_t);
- *h++=(char)sizeof(Instruction);
- *h++=(char)sizeof(lua_Number);
- *h++=(char)(((lua_Number)0.5)==0);		/* is lua_Number integral? */
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/lundump.h
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/lundump.h b/libs/elua/elua_base/src/lundump.h
deleted file mode 100644
index eaa5859..0000000
--- a/libs/elua/elua_base/src/lundump.h
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
-** $Id: lundump.h,v 1.37.1.1 2007/12/27 13:02:25 roberto Exp $
-** load precompiled Lua chunks
-** See Copyright Notice in lua.h
-*/
-
-#ifndef lundump_h
-#define lundump_h
-
-#include <stdint.h>
-
-#include "lobject.h"
-#include "lzio.h"
-
-typedef uint32_t strsize_t;
-
-/* info about target machine for cross-compilation */
-typedef struct {
- int little_endian;
- int sizeof_int;
- int sizeof_strsize_t;
- int sizeof_lua_Number;
- int lua_Number_integral;
- int is_arm_fpa;
-} DumpTargetInfo;
-
-/* load one chunk; from lundump.c */
-LUAI_FUNC Proto* luaU_undump (lua_State* L, ZIO* Z, Mbuffer* buff, const char* name);
-
-/* make header; from lundump.c */
-LUAI_FUNC void luaU_header (char* h);
-
-/* dump one chunk to a different target; from ldump.c */
-int luaU_dump_crosscompile (lua_State* L, const Proto* f, lua_Writer w, void* data, int strip, DumpTargetInfo target);
-
-/* dump one chunk; from ldump.c */
-LUAI_FUNC int luaU_dump (lua_State* L, const Proto* f, lua_Writer w, void* data, int strip);
-
-#ifdef luac_c
-/* print one chunk; from print.c */
-LUAI_FUNC void luaU_print (const Proto* f, int full);
-#endif
-
-/* for header of binary files -- this is Lua 5.1 */
-#define LUAC_VERSION		0x51
-
-/* for header of binary files -- this is the official format */
-#define LUAC_FORMAT		0
-
-/* size of header of binary files */
-#define LUAC_HEADERSIZE		12
-
-/* error codes from cross-compiler */
-/* target integer is too small to hold a value */
-#define LUA_ERR_CC_INTOVERFLOW 101
-
-/* target lua_Number is integral but a constant is non-integer */
-#define LUA_ERR_CC_NOTINTEGER 102
-
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/lvm.c
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/lvm.c b/libs/elua/elua_base/src/lvm.c
deleted file mode 100644
index 3e65503..0000000
--- a/libs/elua/elua_base/src/lvm.c
+++ /dev/null
@@ -1,825 +0,0 @@
-/*
-** $Id: lvm.c,v 2.63.1.4 2009/07/01 21:10:33 roberto Exp $
-** Lua virtual machine
-** See Copyright Notice in lua.h
-*/
-
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#define lvm_c
-#define LUA_CORE
-
-#include "lua.h"
-
-#include "ldebug.h"
-#include "ldo.h"
-#include "lfunc.h"
-#include "lgc.h"
-#include "lobject.h"
-#include "lopcodes.h"
-#include "lstate.h"
-#include "lstring.h"
-#include "ltable.h"
-#include "ltm.h"
-#include "lvm.h"
-#include "lrotable.h"
-
-
-/* limit for table tag-method chains (to avoid loops) */
-#define MAXTAGLOOP	100
-
-#if defined LUA_NUMBER_INTEGRAL
-LUA_NUMBER luai_ipow(LUA_NUMBER a, LUA_NUMBER b) {
-  if (b < 0)
-    return 0;
-  else if (b == 0)
-    return 1;
-  else {
-    LUA_NUMBER c = 1;
-    for (;;) {
-      if (b & 1)
-	c *= a;
-      b = b >> 1;
-      if (b == 0)
-	return c;
-      a *= a;
-    }
-  }
-}
-#endif
-
-const TValue *luaV_tonumber (const TValue *obj, TValue *n) {
-  lua_Number num;
-  if (ttisnumber(obj)) return obj;
-  if (ttisstring(obj) && luaO_str2d(svalue(obj), &num)) {
-    setnvalue(n, num);
-    return n;
-  }
-  else
-    return NULL;
-}
-
-
-int luaV_tostring (lua_State *L, StkId obj) {
-  if (!ttisnumber(obj))
-    return 0;
-  else {
-    char s[LUAI_MAXNUMBER2STR];
-    ptrdiff_t objr = savestack(L, obj);
-    lua_Number n = nvalue(obj);
-    lua_number2str(s, n);
-    setsvalue2s(L, restorestack(L, objr), luaS_new(L, s));
-    return 1;
-  }
-}
-
-
-static void traceexec (lua_State *L, const Instruction *pc) {
-  lu_byte mask = L->hookmask;
-  const Instruction *oldpc = L->savedpc;
-  L->savedpc = pc;
-  if ((mask & LUA_MASKCOUNT) && L->hookcount == 0) {
-    resethookcount(L);
-    luaD_callhook(L, LUA_HOOKCOUNT, -1);
-  }
-  if (mask & LUA_MASKLINE) {
-    Proto *p = ci_func(L->ci)->l.p;
-    int npc = pcRel(pc, p);
-    int newline = getline(p, npc);
-    /* call linehook when enter a new function, when jump back (loop),
-       or when enter a new line */
-    if (npc == 0 || pc <= oldpc || newline != getline(p, pcRel(oldpc, p)))
-      luaD_callhook(L, LUA_HOOKLINE, newline);
-  }
-}
-
-
-static void callTMres (lua_State *L, StkId res, const TValue *f,
-                        const TValue *p1, const TValue *p2) {
-  ptrdiff_t result = savestack(L, res);
-  setobj2s(L, L->top, f);  /* push function */
-  setobj2s(L, L->top+1, p1);  /* 1st argument */
-  setobj2s(L, L->top+2, p2);  /* 2nd argument */
-  luaD_checkstack(L, 3);
-  L->top += 3;
-  luaD_call(L, L->top - 3, 1);
-  res = restorestack(L, result);
-  L->top--;
-  setobjs2s(L, res, L->top);
-}
-
-
-
-static void callTM (lua_State *L, const TValue *f, const TValue *p1,
-                    const TValue *p2, const TValue *p3) {
-  setobj2s(L, L->top, f);  /* push function */
-  setobj2s(L, L->top+1, p1);  /* 1st argument */
-  setobj2s(L, L->top+2, p2);  /* 2nd argument */
-  setobj2s(L, L->top+3, p3);  /* 3th argument */
-  luaD_checkstack(L, 4);
-  L->top += 4;
-  luaD_call(L, L->top - 4, 0);
-}
-
-
-void luaV_gettable (lua_State *L, const TValue *t, TValue *key, StkId val) {
-  int loop;
-  TValue temp;
-  for (loop = 0; loop < MAXTAGLOOP; loop++) {
-    const TValue *tm;
-    if (ttistable(t) || ttisrotable(t)) {  /* `t' is a table? */
-      void *h = ttistable(t) ? hvalue(t) : rvalue(t);
-      const TValue *res = ttistable(t) ? luaH_get((Table*)h, key) : luaH_get_ro(h, key); /* do a primitive get */
-      if (!ttisnil(res) ||  /* result is no nil? */
-          (tm = fasttm(L, ttistable(t) ? ((Table*)h)->metatable : (Table*)luaR_getmeta(h), TM_INDEX)) == NULL) { /* or no TM? */
-        setobj2s(L, val, res);
-        return;
-      }      
-      /* else will try the tag method */
-    }
-    else if (ttisnil(tm = luaT_gettmbyobj(L, t, TM_INDEX)))
-        luaG_typeerror(L, t, "index");
-    if (ttisfunction(tm) || ttislightfunction(tm)) {
-      callTMres(L, val, tm, t, key);
-      return;
-    }
-    /* else repeat with `tm' */
-    setobj(L, &temp, tm);  /* avoid pointing inside table (may rehash) */
-    t = &temp;
-  }
-  luaG_runerror(L, "loop in gettable");
-}
-
-
-void luaV_settable (lua_State *L, const TValue *t, TValue *key, StkId val) {
-  int loop;
-  TValue temp;
-  setnilvalue(L->top);
-  L->top++;
-  fixedstack(L);
-  for (loop = 0; loop < MAXTAGLOOP; loop++) {
-    const TValue *tm;
-    if (ttistable(t) || ttisrotable(t)) {  /* `t' is a table? */
-      void *h = ttistable(t) ? hvalue(t) : rvalue(t);
-      TValue *oldval = ttistable(t) ? luaH_set(L, (Table*)h, key) : NULL; /* do a primitive set */
-      if ((oldval && !ttisnil(oldval)) ||  /* result is no nil? */
-          (tm = fasttm(L, ttistable(t) ? ((Table*)h)->metatable : (Table*)luaR_getmeta(h), TM_NEWINDEX)) == NULL) { /* or no TM? */
-        if(oldval) {
-          L->top--;
-          unfixedstack(L);
-          setobj2t(L, oldval, val);
-          ((Table *)h)->flags = 0;
-          luaC_barriert(L, (Table*)h, val);
-        }
-        return;
-      }
-      /* else will try the tag method */
-    }
-    else if (ttisnil(tm = luaT_gettmbyobj(L, t, TM_NEWINDEX)))
-      luaG_typeerror(L, t, "index");
-    if (ttisfunction(tm) || ttislightfunction(tm)) {
-      L->top--;
-      unfixedstack(L);
-      callTM(L, tm, t, key, val);
-      return;
-    }
-    /* else repeat with `tm' */
-    setobj(L, &temp, tm);  /* avoid pointing inside table (may rehash) */
-    t = &temp;
-    setobj2s(L, L->top-1, t);  /* need to protect value from EGC. */
-  }
-  luaG_runerror(L, "loop in settable");
-}
-
-
-static int call_binTM (lua_State *L, const TValue *p1, const TValue *p2,
-                       StkId res, TMS event) {
-  const TValue *tm = luaT_gettmbyobj(L, p1, event);  /* try first operand */
-  if (ttisnil(tm))
-    tm = luaT_gettmbyobj(L, p2, event);  /* try second operand */
-  if (ttisnil(tm)) return 0;
-  callTMres(L, res, tm, p1, p2);
-  return 1;
-}
-
-
-static const TValue *get_compTM (lua_State *L, Table *mt1, Table *mt2,
-                                  TMS event) {
-  const TValue *tm1 = fasttm(L, mt1, event);
-  const TValue *tm2;
-  if (tm1 == NULL) return NULL;  /* no metamethod */
-  if (mt1 == mt2) return tm1;  /* same metatables => same metamethods */
-  tm2 = fasttm(L, mt2, event);
-  if (tm2 == NULL) return NULL;  /* no metamethod */
-  if (luaO_rawequalObj(tm1, tm2))  /* same metamethods? */
-    return tm1;
-  return NULL;
-}
-
-
-static int call_orderTM (lua_State *L, const TValue *p1, const TValue *p2,
-                         TMS event) {
-  const TValue *tm1 = luaT_gettmbyobj(L, p1, event);
-  const TValue *tm2;
-  if (ttisnil(tm1)) return -1;  /* no metamethod? */
-  tm2 = luaT_gettmbyobj(L, p2, event);
-  if (!luaO_rawequalObj(tm1, tm2))  /* different metamethods? */
-    return -1;
-  callTMres(L, L->top, tm1, p1, p2);
-  return !l_isfalse(L->top);
-}
-
-
-static int l_strcmp (const TString *ls, const TString *rs) {
-  const char *l = getstr(ls);
-  size_t ll = ls->tsv.len;
-  const char *r = getstr(rs);
-  size_t lr = rs->tsv.len;
-  for (;;) {
-    int temp = strcoll(l, r);
-    if (temp != 0) return temp;
-    else {  /* strings are equal up to a `\0' */
-      size_t len = strlen(l);  /* index of first `\0' in both strings */
-      if (len == lr)  /* r is finished? */
-        return (len == ll) ? 0 : 1;
-      else if (len == ll)  /* l is finished? */
-        return -1;  /* l is smaller than r (because r is not finished) */
-      /* both strings longer than `len'; go on comparing (after the `\0') */
-      len++;
-      l += len; ll -= len; r += len; lr -= len;
-    }
-  }
-}
-
-
-int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r) {
-  int res;
-  if (ttype(l) != ttype(r))
-    return luaG_ordererror(L, l, r);
-  else if (ttisnumber(l))
-    return luai_numlt(nvalue(l), nvalue(r));
-  else if (ttisstring(l))
-    return l_strcmp(rawtsvalue(l), rawtsvalue(r)) < 0;
-  else if ((res = call_orderTM(L, l, r, TM_LT)) != -1)
-    return res;
-  return luaG_ordererror(L, l, r);
-}
-
-
-static int lessequal (lua_State *L, const TValue *l, const TValue *r) {
-  int res;
-  if (ttype(l) != ttype(r))
-    return luaG_ordererror(L, l, r);
-  else if (ttisnumber(l))
-    return luai_numle(nvalue(l), nvalue(r));
-  else if (ttisstring(l))
-    return l_strcmp(rawtsvalue(l), rawtsvalue(r)) <= 0;
-  else if ((res = call_orderTM(L, l, r, TM_LE)) != -1)  /* first try `le' */
-    return res;
-  else if ((res = call_orderTM(L, r, l, TM_LT)) != -1)  /* else try `lt' */
-    return !res;
-  return luaG_ordererror(L, l, r);
-}
-
-
-int luaV_equalval (lua_State *L, const TValue *t1, const TValue *t2) {
-  const TValue *tm;
-  lua_assert(ttype(t1) == ttype(t2));
-  switch (ttype(t1)) {
-    case LUA_TNIL: return 1;
-    case LUA_TNUMBER: return luai_numeq(nvalue(t1), nvalue(t2));
-    case LUA_TBOOLEAN: return bvalue(t1) == bvalue(t2);  /* true must be 1 !! */
-    case LUA_TLIGHTUSERDATA: 
-    case LUA_TROTABLE:
-    case LUA_TLIGHTFUNCTION:
-      return pvalue(t1) == pvalue(t2);
-    case LUA_TUSERDATA: {
-      if (uvalue(t1) == uvalue(t2)) return 1;
-      tm = get_compTM(L, uvalue(t1)->metatable, uvalue(t2)->metatable,
-                         TM_EQ);
-      break;  /* will try TM */
-    }
-    case LUA_TTABLE: {
-      if (hvalue(t1) == hvalue(t2)) return 1;
-      tm = get_compTM(L, hvalue(t1)->metatable, hvalue(t2)->metatable, TM_EQ);
-      break;  /* will try TM */
-    }
-    default: return gcvalue(t1) == gcvalue(t2);
-  }
-  if (tm == NULL) return 0;  /* no TM? */
-  callTMres(L, L->top, tm, t1, t2);  /* call TM */
-  return !l_isfalse(L->top);
-}
-
-
-void luaV_concat (lua_State *L, int total, int last) {
-  lu_mem max_sizet = MAX_SIZET;
-  if (G(L)->memlimit < max_sizet) max_sizet = G(L)->memlimit;
-  do {
-    StkId top = L->base + last + 1;
-    int n = 2;  /* number of elements handled in this pass (at least 2) */
-    if (!(ttisstring(top-2) || ttisnumber(top-2)) || !tostring(L, top-1)) {
-      if (!call_binTM(L, top-2, top-1, top-2, TM_CONCAT)) {
-        /* restore 'top' pointer, since stack might have been reallocted */
-        top = L->base + last + 1;
-        luaG_concaterror(L, top-2, top-1);
-      }
-    } else if (tsvalue(top-1)->len == 0)  /* second op is empty? */
-      (void)tostring(L, top - 2);  /* result is first op (as string) */
-    else {
-      /* at least two string values; get as many as possible */
-      size_t tl = tsvalue(top-1)->len;
-      char *buffer;
-      int i;
-      fixedstack(L);
-      /* collect total length */
-      for (n = 1; n < total && tostring(L, top-n-1); n++) {
-        size_t l = tsvalue(top-n-1)->len;
-        if (l >= max_sizet - tl) luaG_runerror(L, "string length overflow");
-        tl += l;
-      }
-      G(L)->buff.n = tl;
-      buffer = luaZ_openspace(L, &G(L)->buff, tl);
-      tl = 0;
-      for (i=n; i>0; i--) {  /* concat all strings */
-        size_t l = tsvalue(top-i)->len;
-        memcpy(buffer+tl, svalue(top-i), l);
-        tl += l;
-      }
-      setsvalue2s(L, top-n, luaS_newlstr(L, buffer, tl));
-      luaZ_resetbuffer(&G(L)->buff);
-      unfixedstack(L);
-    }
-    total -= n-1;  /* got `n' strings to create 1 new */
-    last -= n-1;
-  } while (total > 1);  /* repeat until only 1 result left */
-}
-
-
-static void Arith (lua_State *L, StkId ra, const TValue *rb,
-                   const TValue *rc, TMS op) {
-  TValue tempb, tempc;
-  const TValue *b, *c;
-  if ((b = luaV_tonumber(rb, &tempb)) != NULL &&
-      (c = luaV_tonumber(rc, &tempc)) != NULL) {
-    lua_Number nb = nvalue(b), nc = nvalue(c);
-    switch (op) {
-      case TM_ADD: setnvalue(ra, luai_numadd(nb, nc)); break;
-      case TM_SUB: setnvalue(ra, luai_numsub(nb, nc)); break;
-      case TM_MUL: setnvalue(ra, luai_nummul(nb, nc)); break;
-      case TM_DIV: setnvalue(ra, luai_lnumdiv(nb, nc)); break;
-      case TM_MOD: setnvalue(ra, luai_lnummod(nb, nc)); break;
-      case TM_POW: setnvalue(ra, luai_numpow(nb, nc)); break;
-      case TM_UNM: setnvalue(ra, luai_numunm(nb)); break;
-      default: lua_assert(0); break;
-    }
-  }
-  else {
-    ptrdiff_t br = savestack(L, rb);
-    ptrdiff_t cr = savestack(L, rc);
-    if (!call_binTM(L, rb, rc, ra, op)) {
-      luaG_aritherror(L, restorestack(L, br), restorestack(L, cr));
-    }
-  }
-}
-
-
-
-/*
-** some macros for common tasks in `luaV_execute'
-*/
-
-#define runtime_check(L, c)	{ if (!(c)) break; }
-
-#define RA(i)	(base+GETARG_A(i))
-/* to be used after possible stack reallocation */
-#define RB(i)	check_exp(getBMode(GET_OPCODE(i)) == OpArgR, base+GETARG_B(i))
-#define RC(i)	check_exp(getCMode(GET_OPCODE(i)) == OpArgR, base+GETARG_C(i))
-#define RKB(i)	check_exp(getBMode(GET_OPCODE(i)) == OpArgK, \
-	ISK(GETARG_B(i)) ? k+INDEXK(GETARG_B(i)) : base+GETARG_B(i))
-#define RKC(i)	check_exp(getCMode(GET_OPCODE(i)) == OpArgK, \
-	ISK(GETARG_C(i)) ? k+INDEXK(GETARG_C(i)) : base+GETARG_C(i))
-#define KBx(i)	check_exp(getBMode(GET_OPCODE(i)) == OpArgK, k+GETARG_Bx(i))
-
-
-#define dojump(L,pc,i)	{(pc) += (i); luai_threadyield(L);}
-
-
-#define Protect(x)	{ L->savedpc = pc; {x;}; base = L->base; }
-
-
-#define arith_op(op,tm) { \
-        TValue *rb = RKB(i); \
-        TValue *rc = RKC(i); \
-        if (ttisnumber(rb) && ttisnumber(rc)) { \
-          lua_Number nb = nvalue(rb), nc = nvalue(rc); \
-          setnvalue(ra, op(nb, nc)); \
-        } \
-        else \
-          Protect(Arith(L, ra, rb, rc, tm)); \
-      }
-
-
-
-void luaV_execute (lua_State *L, int nexeccalls) {
-  LClosure *cl;
-  StkId base;
-  TValue *k;
-  const Instruction *pc;
- reentry:  /* entry point */
-  lua_assert(isLua(L->ci));
-  pc = L->savedpc;
-  cl = &clvalue(L->ci->func)->l;
-  base = L->base;
-  k = cl->p->k;
-  /* main loop of interpreter */
-  for (;;) {
-    const Instruction i = *pc++;
-    StkId ra;
-    if ((L->hookmask & (LUA_MASKLINE | LUA_MASKCOUNT)) &&
-        (--L->hookcount == 0 || L->hookmask & LUA_MASKLINE)) {
-      traceexec(L, pc);
-      if (L->status == LUA_YIELD) {  /* did hook yield? */
-        L->savedpc = pc - 1;
-        return;
-      }
-      base = L->base;
-    }
-    /* warning!! several calls may realloc the stack and invalidate `ra' */
-    ra = RA(i);
-    lua_assert(base == L->base && L->base == L->ci->base);
-    lua_assert(base <= L->top && L->top <= L->stack + L->stacksize);
-    lua_assert(L->top == L->ci->top || luaG_checkopenop(i));
-    switch (GET_OPCODE(i)) {
-      case OP_MOVE: {
-        setobjs2s(L, ra, RB(i));
-        continue;
-      }
-      case OP_LOADK: {
-        setobj2s(L, ra, KBx(i));
-        continue;
-      }
-      case OP_LOADBOOL: {
-        setbvalue(ra, GETARG_B(i));
-        if (GETARG_C(i)) pc++;  /* skip next instruction (if C) */
-        continue;
-      }
-      case OP_LOADNIL: {
-        TValue *rb = RB(i);
-        do {
-          setnilvalue(rb--);
-        } while (rb >= ra);
-        continue;
-      }
-      case OP_GETUPVAL: {
-        int b = GETARG_B(i);
-        setobj2s(L, ra, cl->upvals[b]->v);
-        continue;
-      }
-      case OP_GETGLOBAL: {
-        TValue g;
-        TValue *rb = KBx(i);
-        sethvalue(L, &g, cl->env);
-        lua_assert(ttisstring(rb));
-        Protect(luaV_gettable(L, &g, rb, ra));
-        continue;
-      }
-      case OP_GETTABLE: {
-        Protect(luaV_gettable(L, RB(i), RKC(i), ra));
-        continue;
-      }
-      case OP_SETGLOBAL: {
-        TValue g;
-        sethvalue(L, &g, cl->env);
-        lua_assert(ttisstring(KBx(i)));
-        Protect(luaV_settable(L, &g, KBx(i), ra));
-        continue;
-      }
-      case OP_SETUPVAL: {
-        UpVal *uv = cl->upvals[GETARG_B(i)];
-        setobj(L, uv->v, ra);
-        luaC_barrier(L, uv, ra);
-        continue;
-      }
-      case OP_SETTABLE: {
-        Protect(luaV_settable(L, ra, RKB(i), RKC(i)));
-        continue;
-      }
-      case OP_NEWTABLE: {
-        int b = GETARG_B(i);
-        int c = GETARG_C(i);
-        Table *h;
-        Protect(h = luaH_new(L, luaO_fb2int(b), luaO_fb2int(c)));
-        sethvalue(L, RA(i), h);
-        Protect(luaC_checkGC(L));
-        continue;
-      }
-      case OP_SELF: {
-        StkId rb = RB(i);
-        setobjs2s(L, ra+1, rb);
-        Protect(luaV_gettable(L, rb, RKC(i), ra));
-        continue;
-      }
-      case OP_ADD: {
-        arith_op(luai_numadd, TM_ADD);
-        continue;
-      }
-      case OP_SUB: {
-        arith_op(luai_numsub, TM_SUB);
-        continue;
-      }
-      case OP_MUL: {
-        arith_op(luai_nummul, TM_MUL);
-        continue;
-      }
-      case OP_DIV: {
-        arith_op(luai_lnumdiv, TM_DIV);
-        continue;
-      }
-      case OP_MOD: {
-        arith_op(luai_lnummod, TM_MOD);
-        continue;
-      }
-      case OP_POW: {
-        arith_op(luai_numpow, TM_POW);
-        continue;
-      }
-      case OP_UNM: {
-        TValue *rb = RB(i);
-        if (ttisnumber(rb)) {
-          lua_Number nb = nvalue(rb);
-          setnvalue(ra, luai_numunm(nb));
-        }
-        else {
-          Protect(Arith(L, ra, rb, rb, TM_UNM));
-        }
-        continue;
-      }
-      case OP_NOT: {
-        int res = l_isfalse(RB(i));  /* next assignment may change this value */
-        setbvalue(ra, res);
-        continue;
-      }
-      case OP_LEN: {
-        const TValue *rb = RB(i);
-        switch (ttype(rb)) {
-          case LUA_TTABLE: 
-          case LUA_TROTABLE: {
-            setnvalue(ra, ttistable(rb) ? cast_num(luaH_getn(hvalue(rb))) : cast_num(luaH_getn_ro(rvalue(rb))));
-            break;
-          }
-          case LUA_TSTRING: {
-            setnvalue(ra, cast_num(tsvalue(rb)->len));
-            break;
-          }
-          default: {  /* try metamethod */
-            ptrdiff_t br = savestack(L, rb);
-            Protect(
-              if (!call_binTM(L, rb, luaO_nilobject, ra, TM_LEN))
-                luaG_typeerror(L, restorestack(L, br), "get length of");
-            )
-          }
-        }
-        continue;
-      }
-      case OP_CONCAT: {
-        int b = GETARG_B(i);
-        int c = GETARG_C(i);
-        Protect(luaV_concat(L, c-b+1, c); luaC_checkGC(L));
-        setobjs2s(L, RA(i), base+b);
-        continue;
-      }
-      case OP_JMP: {
-        dojump(L, pc, GETARG_sBx(i));
-        continue;
-      }
-      case OP_EQ: {
-        TValue *rb = RKB(i);
-        TValue *rc = RKC(i);
-        Protect(
-          if (equalobj(L, rb, rc) == GETARG_A(i))
-            dojump(L, pc, GETARG_sBx(*pc));
-        )
-        pc++;
-        continue;
-      }
-      case OP_LT: {
-        Protect(
-          if (luaV_lessthan(L, RKB(i), RKC(i)) == GETARG_A(i))
-            dojump(L, pc, GETARG_sBx(*pc));
-        )
-        pc++;
-        continue;
-      }
-      case OP_LE: {
-        Protect(
-          if (lessequal(L, RKB(i), RKC(i)) == GETARG_A(i))
-            dojump(L, pc, GETARG_sBx(*pc));
-        )
-        pc++;
-        continue;
-      }
-      case OP_TEST: {
-        if (l_isfalse(ra) != GETARG_C(i))
-          dojump(L, pc, GETARG_sBx(*pc));
-        pc++;
-        continue;
-      }
-      case OP_TESTSET: {
-        TValue *rb = RB(i);
-        if (l_isfalse(rb) != GETARG_C(i)) {
-          setobjs2s(L, ra, rb);
-          dojump(L, pc, GETARG_sBx(*pc));
-        }
-        pc++;
-        continue;
-      }
-      case OP_CALL: {
-        int b = GETARG_B(i);
-        int nresults = GETARG_C(i) - 1;
-        if (b != 0) L->top = ra+b;  /* else previous instruction set top */
-        L->savedpc = pc;
-        switch (luaD_precall(L, ra, nresults)) {
-          case PCRLUA: {
-            nexeccalls++;
-            goto reentry;  /* restart luaV_execute over new Lua function */
-          }
-          case PCRC: {
-            /* it was a C function (`precall' called it); adjust results */
-            if (nresults >= 0) L->top = L->ci->top;
-            base = L->base;
-            continue;
-          }
-          default: {
-            return;  /* yield */
-          }
-        }
-      }
-      case OP_TAILCALL: {
-        int b = GETARG_B(i);
-        if (b != 0) L->top = ra+b;  /* else previous instruction set top */
-        L->savedpc = pc;
-        lua_assert(GETARG_C(i) - 1 == LUA_MULTRET);
-        switch (luaD_precall(L, ra, LUA_MULTRET)) {
-          case PCRLUA: {
-            /* tail call: put new frame in place of previous one */
-            CallInfo *ci = L->ci - 1;  /* previous frame */
-            int aux;
-            StkId func = ci->func;
-            StkId pfunc = (ci+1)->func;  /* previous function index */
-            if (L->openupval) luaF_close(L, ci->base);
-            L->base = ci->base = ci->func + ((ci+1)->base - pfunc);
-            for (aux = 0; pfunc+aux < L->top; aux++)  /* move frame down */
-              setobjs2s(L, func+aux, pfunc+aux);
-            ci->top = L->top = func+aux;  /* correct top */
-            lua_assert(L->top == L->base + clvalue(func)->l.p->maxstacksize);
-            ci->savedpc = L->savedpc;
-            ci->tailcalls++;  /* one more call lost */
-            L->ci--;  /* remove new frame */
-            goto reentry;
-          }
-          case PCRC: {  /* it was a C function (`precall' called it) */
-            base = L->base;
-            continue;
-          }
-          default: {
-            return;  /* yield */
-          }
-        }
-      }
-      case OP_RETURN: {
-        int b = GETARG_B(i);
-        if (b != 0) L->top = ra+b-1;
-        if (L->openupval) luaF_close(L, base);
-        L->savedpc = pc;
-        b = luaD_poscall(L, ra);
-        if (--nexeccalls == 0)  /* was previous function running `here'? */
-          return;  /* no: return */
-        else {  /* yes: continue its execution */
-          if (b) L->top = L->ci->top;
-          lua_assert(isLua(L->ci));
-          lua_assert(GET_OPCODE(*((L->ci)->savedpc - 1)) == OP_CALL);
-          goto reentry;
-        }
-      }
-      case OP_FORLOOP: {
-        lua_Number step = nvalue(ra+2);
-        lua_Number idx = luai_numadd(nvalue(ra), step); /* increment index */
-        lua_Number limit = nvalue(ra+1);
-        if (luai_numlt(0, step) ? luai_numle(idx, limit)
-                                : luai_numle(limit, idx)) {
-          dojump(L, pc, GETARG_sBx(i));  /* jump back */
-          setnvalue(ra, idx);  /* update internal index... */
-          setnvalue(ra+3, idx);  /* ...and external index */
-        }
-        continue;
-      }
-      case OP_FORPREP: {
-        const TValue *init = ra;
-        const TValue *plimit = ra+1;
-        const TValue *pstep = ra+2;
-        L->savedpc = pc;  /* next steps may throw errors */
-        if (!tonumber(init, ra))
-          luaG_runerror(L, LUA_QL("for") " initial value must be a number");
-        else if (!tonumber(plimit, ra+1))
-          luaG_runerror(L, LUA_QL("for") " limit must be a number");
-        else if (!tonumber(pstep, ra+2))
-          luaG_runerror(L, LUA_QL("for") " step must be a number");
-        setnvalue(ra, luai_numsub(nvalue(ra), nvalue(pstep)));
-        dojump(L, pc, GETARG_sBx(i));
-        continue;
-      }
-      case OP_TFORLOOP: {
-        StkId cb = ra + 3;  /* call base */
-        setobjs2s(L, cb+2, ra+2);
-        setobjs2s(L, cb+1, ra+1);
-        setobjs2s(L, cb, ra);
-        L->top = cb+3;  /* func. + 2 args (state and index) */
-        Protect(luaD_call(L, cb, GETARG_C(i)));
-        L->top = L->ci->top;
-        cb = RA(i) + 3;  /* previous call may change the stack */
-        if (!ttisnil(cb)) {  /* continue loop? */
-          setobjs2s(L, cb-1, cb);  /* save control variable */
-          dojump(L, pc, GETARG_sBx(*pc));  /* jump back */
-        }
-        pc++;
-        continue;
-      }
-      case OP_SETLIST: {
-        int n = GETARG_B(i);
-        int c = GETARG_C(i);
-        int last;
-        Table *h;
-        fixedstack(L);
-        if (n == 0) {
-          n = cast_int(L->top - ra) - 1;
-          L->top = L->ci->top;
-        }
-        if (c == 0) c = cast_int(*pc++);
-        runtime_check(L, ttistable(ra));
-        h = hvalue(ra);
-        last = ((c-1)*LFIELDS_PER_FLUSH) + n;
-        if (last > h->sizearray)  /* needs more space? */
-          luaH_resizearray(L, h, last);  /* pre-alloc it at once */
-        for (; n > 0; n--) {
-          TValue *val = ra+n;
-          setobj2t(L, luaH_setnum(L, h, last--), val);
-          luaC_barriert(L, h, val);
-        }
-        unfixedstack(L);
-        continue;
-      }
-      case OP_CLOSE: {
-        luaF_close(L, ra);
-        continue;
-      }
-      case OP_CLOSURE: {
-        Proto *p;
-        Closure *ncl;
-        int nup, j;
-        p = cl->p->p[GETARG_Bx(i)];
-        nup = p->nups;
-        fixedstack(L);
-        ncl = luaF_newLclosure(L, nup, cl->env);
-        setclvalue(L, ra, ncl);
-        ncl->l.p = p;
-        for (j=0; j<nup; j++, pc++) {
-          if (GET_OPCODE(*pc) == OP_GETUPVAL)
-            ncl->l.upvals[j] = cl->upvals[GETARG_B(*pc)];
-          else {
-            lua_assert(GET_OPCODE(*pc) == OP_MOVE);
-            ncl->l.upvals[j] = luaF_findupval(L, base + GETARG_B(*pc));
-          }
-        }
-        unfixedstack(L);
-        Protect(luaC_checkGC(L));
-        continue;
-      }
-      case OP_VARARG: {
-        int b = GETARG_B(i) - 1;
-        int j;
-        CallInfo *ci = L->ci;
-        int n = cast_int(ci->base - ci->func) - cl->p->numparams - 1;
-        if (b == LUA_MULTRET) {
-          Protect(luaD_checkstack(L, n));
-          ra = RA(i);  /* previous call may change the stack */
-          b = n;
-          L->top = ra + n;
-        }
-        for (j = 0; j < b; j++) {
-          if (j < n) {
-            setobjs2s(L, ra + j, ci->base - n + j);
-          }
-          else {
-            setnilvalue(ra + j);
-          }
-        }
-        continue;
-      }
-    }
-  }
-}
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/lvm.h
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/lvm.h b/libs/elua/elua_base/src/lvm.h
deleted file mode 100644
index bfe4f56..0000000
--- a/libs/elua/elua_base/src/lvm.h
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
-** $Id: lvm.h,v 2.5.1.1 2007/12/27 13:02:25 roberto Exp $
-** Lua virtual machine
-** See Copyright Notice in lua.h
-*/
-
-#ifndef lvm_h
-#define lvm_h
-
-
-#include "ldo.h"
-#include "lobject.h"
-#include "ltm.h"
-
-
-#define tostring(L,o) ((ttype(o) == LUA_TSTRING) || (luaV_tostring(L, o)))
-
-#define tonumber(o,n)	(ttype(o) == LUA_TNUMBER || \
-                         (((o) = luaV_tonumber(o,n)) != NULL))
-
-#define equalobj(L,o1,o2) \
-	(ttype(o1) == ttype(o2) && luaV_equalval(L, o1, o2))
-
-
-LUAI_FUNC int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r);
-LUAI_FUNC int luaV_equalval (lua_State *L, const TValue *t1, const TValue *t2);
-LUAI_FUNC const TValue *luaV_tonumber (const TValue *obj, TValue *n);
-LUAI_FUNC int luaV_tostring (lua_State *L, StkId obj);
-LUAI_FUNC void luaV_gettable (lua_State *L, const TValue *t, TValue *key,
-                                            StkId val);
-LUAI_FUNC void luaV_settable (lua_State *L, const TValue *t, TValue *key,
-                                            StkId val);
-LUAI_FUNC void luaV_execute (lua_State *L, int nexeccalls);
-LUAI_FUNC void luaV_concat (lua_State *L, int total, int last);
-
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/lzio.c
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/lzio.c b/libs/elua/elua_base/src/lzio.c
deleted file mode 100644
index 72d57b8..0000000
--- a/libs/elua/elua_base/src/lzio.c
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
-** $Id: lzio.c,v 1.31.1.1 2007/12/27 13:02:25 roberto Exp $
-** a generic input stream interface
-** See Copyright Notice in lua.h
-*/
-
-
-#include <string.h>
-
-#define lzio_c
-#define LUA_CORE
-
-#include "lua.h"
-
-#include "llimits.h"
-#include "lmem.h"
-#include "lstate.h"
-#include "lzio.h"
-
-
-int luaZ_fill (ZIO *z) {
-  size_t size;
-  lua_State *L = z->L;
-  const char *buff;
-  lua_unlock(L);
-  buff = z->reader(L, z->data, &size);
-  lua_lock(L);
-  if (buff == NULL || size == 0) return EOZ;
-  z->n = size - 1;
-  z->p = buff;
-  return char2int(*(z->p++));
-}
-
-
-int luaZ_lookahead (ZIO *z) {
-  if (z->n == 0) {
-    if (luaZ_fill(z) == EOZ)
-      return EOZ;
-    else {
-      z->n++;  /* luaZ_fill removed first byte; put back it */
-      z->p--;
-    }
-  }
-  return char2int(*z->p);
-}
-
-
-void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, void *data) {
-  z->L = L;
-  z->reader = reader;
-  z->data = data;
-  z->n = z->i = 0;
-  z->p = NULL;
-}
-
-
-/* --------------------------------------------------------------- read --- */
-size_t luaZ_read (ZIO *z, void *b, size_t n) {
-  while (n) {
-    size_t m;
-    if (luaZ_lookahead(z) == EOZ)
-      return n;  /* return number of missing bytes */
-    m = (n <= z->n) ? n : z->n;  /* min. between n and z->n */
-    if (b)
-      memcpy(b, z->p, m);
-    z->n -= m;
-    z->i += m;
-    z->p += m;
-    if (b)
-      b = (char *)b + m;
-    n -= m;
-  }
-  return 0;
-}
-
-/* ------------------------------------------------------------------------ */
-char *luaZ_openspace (lua_State *L, Mbuffer *buff, size_t n) {
-  if (n > buff->buffsize) {
-    if (n < LUA_MINBUFFER) n = LUA_MINBUFFER;
-    luaZ_resizebuffer(L, buff, n);
-  }
-  return buff->buffer;
-}
-
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/lzio.h
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/lzio.h b/libs/elua/elua_base/src/lzio.h
deleted file mode 100644
index 7a31475..0000000
--- a/libs/elua/elua_base/src/lzio.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
-** $Id: lzio.h,v 1.21.1.1 2007/12/27 13:02:25 roberto Exp $
-** Buffered streams
-** See Copyright Notice in lua.h
-*/
-
-
-#ifndef lzio_h
-#define lzio_h
-
-#include "lua.h"
-
-#include "lmem.h"
-
-
-#define EOZ	(-1)			/* end of stream */
-
-typedef struct Zio ZIO;
-
-#define char2int(c)	cast(int, cast(unsigned char, (c)))
-
-#define zgetc(z)  (((z)->n--)>0 ?  char2int(*(z)->p++) : luaZ_fill(z))
-
-typedef struct Mbuffer {
-  char *buffer;
-  size_t n;
-  size_t buffsize;
-} Mbuffer;
-
-#define luaZ_initbuffer(L, buff) ((buff)->buffer = NULL, (buff)->n = 0, (buff)->buffsize = 0)
-
-#define luaZ_buffer(buff)	((buff)->buffer)
-#define luaZ_sizebuffer(buff)	((buff)->buffsize)
-#define luaZ_bufflen(buff)	((buff)->n)
-
-#define luaZ_resetbuffer(buff) ((buff)->n = 0)
-
-
-#define luaZ_resizebuffer(L, buff, size) \
-	(luaM_reallocvector(L, (buff)->buffer, (buff)->buffsize, size, char), \
-	(buff)->buffsize = size)
-
-#define luaZ_freebuffer(L, buff)	luaZ_resizebuffer(L, buff, 0)
-
-#define luaZ_freebuffer(L, buff)  luaZ_resizebuffer(L, buff, 0)
-#define luaZ_get_base_address(zio) ((const char *)((zio)->reader(NULL, (zio)->data, NULL)))
-#define luaZ_direct_mode(zio) (luaZ_get_base_address(zio) != NULL)
-#define luaZ_get_crt_address(zio) (luaZ_get_base_address(zio) + (zio)->i)
-
-LUAI_FUNC char *luaZ_openspace (lua_State *L, Mbuffer *buff, size_t n);
-LUAI_FUNC void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader,
-                                        void *data);
-LUAI_FUNC size_t luaZ_read (ZIO* z, void* b, size_t n);	/* read next n bytes */
-LUAI_FUNC int luaZ_lookahead (ZIO *z);
-
-
-
-/* --------- Private Part ------------------ */
-
-struct Zio {
-  size_t n;			/* bytes still unread */
-  size_t i;     /* buffer offset */
-  const char *p;		/* current position in buffer */
-  lua_Reader reader;
-  void* data;			/* additional data */
-  lua_State *L;			/* Lua state (for reader) */
-};
-
-
-LUAI_FUNC int luaZ_fill (ZIO *z);
-
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/elua/elua_base/src/print.c.donotcompile
----------------------------------------------------------------------
diff --git a/libs/elua/elua_base/src/print.c.donotcompile b/libs/elua/elua_base/src/print.c.donotcompile
deleted file mode 100644
index e240cfc..0000000
--- a/libs/elua/elua_base/src/print.c.donotcompile
+++ /dev/null
@@ -1,227 +0,0 @@
-/*
-** $Id: print.c,v 1.55a 2006/05/31 13:30:05 lhf Exp $
-** print bytecodes
-** See Copyright Notice in lua.h
-*/
-
-#include <ctype.h>
-#include <stdio.h>
-
-#define luac_c
-#define LUA_CORE
-
-#include "ldebug.h"
-#include "lobject.h"
-#include "lopcodes.h"
-#include "lundump.h"
-
-#define PrintFunction	luaU_print
-
-#define Sizeof(x)	((int)sizeof(x))
-#define VOID(p)		((const void*)(p))
-
-static void PrintString(const TString* ts)
-{
- const char* s=getstr(ts);
- size_t i,n=ts->tsv.len;
- putchar('"');
- for (i=0; i<n; i++)
- {
-  int c=s[i];
-  switch (c)
-  {
-   case '"': printf("\\\""); break;
-   case '\\': printf("\\\\"); break;
-   case '\a': printf("\\a"); break;
-   case '\b': printf("\\b"); break;
-   case '\f': printf("\\f"); break;
-   case '\n': printf("\\n"); break;
-   case '\r': printf("\\r"); break;
-   case '\t': printf("\\t"); break;
-   case '\v': printf("\\v"); break;
-   default:	if (isprint((unsigned char)c))
-   			putchar(c);
-		else
-			printf("\\%03u",(unsigned char)c);
-  }
- }
- putchar('"');
-}
-
-static void PrintConstant(const Proto* f, int i)
-{
- const TValue* o=&f->k[i];
- switch (ttype(o))
- {
-  case LUA_TNIL:
-	printf("nil");
-	break;
-  case LUA_TBOOLEAN:
-	printf(bvalue(o) ? "true" : "false");
-	break;
-  case LUA_TNUMBER:
-	printf(LUA_NUMBER_FMT,nvalue(o));
-	break;
-  case LUA_TSTRING:
-	PrintString(rawtsvalue(o));
-	break;
-  default:				/* cannot happen */
-	printf("? type=%d",ttype(o));
-	break;
- }
-}
-
-static void PrintCode(const Proto* f)
-{
- const Instruction* code=f->code;
- int pc,n=f->sizecode;
- for (pc=0; pc<n; pc++)
- {
-  Instruction i=code[pc];
-  OpCode o=GET_OPCODE(i);
-  int a=GETARG_A(i);
-  int b=GETARG_B(i);
-  int c=GETARG_C(i);
-  int bx=GETARG_Bx(i);
-  int sbx=GETARG_sBx(i);
-  int line=getline(f,pc);
-  printf("\t%d\t",pc+1);
-  if (line>0) printf("[%d]\t",line); else printf("[-]\t");
-  printf("%-9s\t",luaP_opnames[o]);
-  switch (getOpMode(o))
-  {
-   case iABC:
-    printf("%d",a);
-    if (getBMode(o)!=OpArgN) printf(" %d",ISK(b) ? (-1-INDEXK(b)) : b);
-    if (getCMode(o)!=OpArgN) printf(" %d",ISK(c) ? (-1-INDEXK(c)) : c);
-    break;
-   case iABx:
-    if (getBMode(o)==OpArgK) printf("%d %d",a,-1-bx); else printf("%d %d",a,bx);
-    break;
-   case iAsBx:
-    if (o==OP_JMP) printf("%d",sbx); else printf("%d %d",a,sbx);
-    break;
-  }
-  switch (o)
-  {
-   case OP_LOADK:
-    printf("\t; "); PrintConstant(f,bx);
-    break;
-   case OP_GETUPVAL:
-   case OP_SETUPVAL:
-    printf("\t; %s", (f->sizeupvalues>0) ? getstr(f->upvalues[b]) : "-");
-    break;
-   case OP_GETGLOBAL:
-   case OP_SETGLOBAL:
-    printf("\t; %s",svalue(&f->k[bx]));
-    break;
-   case OP_GETTABLE:
-   case OP_SELF:
-    if (ISK(c)) { printf("\t; "); PrintConstant(f,INDEXK(c)); }
-    break;
-   case OP_SETTABLE:
-   case OP_ADD:
-   case OP_SUB:
-   case OP_MUL:
-   case OP_DIV:
-   case OP_POW:
-   case OP_EQ:
-   case OP_LT:
-   case OP_LE:
-    if (ISK(b) || ISK(c))
-    {
-     printf("\t; ");
-     if (ISK(b)) PrintConstant(f,INDEXK(b)); else printf("-");
-     printf(" ");
-     if (ISK(c)) PrintConstant(f,INDEXK(c)); else printf("-");
-    }
-    break;
-   case OP_JMP:
-   case OP_FORLOOP:
-   case OP_FORPREP:
-    printf("\t; to %d",sbx+pc+2);
-    break;
-   case OP_CLOSURE:
-    printf("\t; %p",VOID(f->p[bx]));
-    break;
-   case OP_SETLIST:
-    if (c==0) printf("\t; %d",(int)code[++pc]);
-    else printf("\t; %d",c);
-    break;
-   default:
-    break;
-  }
-  printf("\n");
- }
-}
-
-#define SS(x)	(x==1)?"":"s"
-#define S(x)	x,SS(x)
-
-static void PrintHeader(const Proto* f)
-{
- const char* s=getstr(f->source);
- if (*s=='@' || *s=='=')
-  s++;
- else if (*s==LUA_SIGNATURE[0])
-  s="(bstring)";
- else
-  s="(string)";
- printf("\n%s <%s:%d,%d> (%d instruction%s, %d bytes at %p)\n",
- 	(f->linedefined==0)?"main":"function",s,
-	f->linedefined,f->lastlinedefined,
-	S(f->sizecode),f->sizecode*Sizeof(Instruction),VOID(f));
- printf("%d%s param%s, %d slot%s, %d upvalue%s, ",
-	f->numparams,f->is_vararg?"+":"",SS(f->numparams),
-	S(f->maxstacksize),S(f->nups));
- printf("%d local%s, %d constant%s, %d function%s\n",
-	S(f->sizelocvars),S(f->sizek),S(f->sizep));
-}
-
-static void PrintConstants(const Proto* f)
-{
- int i,n=f->sizek;
- printf("constants (%d) for %p:\n",n,VOID(f));
- for (i=0; i<n; i++)
- {
-  printf("\t%d\t",i+1);
-  PrintConstant(f,i);
-  printf("\n");
- }
-}
-
-static void PrintLocals(const Proto* f)
-{
- int i,n=f->sizelocvars;
- printf("locals (%d) for %p:\n",n,VOID(f));
- for (i=0; i<n; i++)
- {
-  printf("\t%d\t%s\t%d\t%d\n",
-  i,getstr(f->locvars[i].varname),f->locvars[i].startpc+1,f->locvars[i].endpc+1);
- }
-}
-
-static void PrintUpvalues(const Proto* f)
-{
- int i,n=f->sizeupvalues;
- printf("upvalues (%d) for %p:\n",n,VOID(f));
- if (f->upvalues==NULL) return;
- for (i=0; i<n; i++)
- {
-  printf("\t%d\t%s\n",i,getstr(f->upvalues[i]));
- }
-}
-
-void PrintFunction(const Proto* f, int full)
-{
- int i,n=f->sizep;
- PrintHeader(f);
- PrintCode(f);
- if (full)
- {
-  PrintConstants(f);
-  PrintLocals(f);
-  PrintUpvalues(f);
- }
- for (i=0; i<n; i++) PrintFunction(f->p[i],full);
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/flash_test/include/flash_test/flash_test.h
----------------------------------------------------------------------
diff --git a/libs/flash_test/include/flash_test/flash_test.h b/libs/flash_test/include/flash_test/flash_test.h
deleted file mode 100644
index f38f48c..0000000
--- a/libs/flash_test/include/flash_test/flash_test.h
+++ /dev/null
@@ -1,27 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 __FLASH_TEST_H__ 
-#define __FLASH_TEST_H__
-
-/**
- * adds the flash test commands to your shell */
-int
-flash_test_init(void);
-
-#endif /* __FLASH_TEST_H__ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/flash_test/pkg.yml
----------------------------------------------------------------------
diff --git a/libs/flash_test/pkg.yml b/libs/flash_test/pkg.yml
deleted file mode 100644
index e31b00d..0000000
--- a/libs/flash_test/pkg.yml
+++ /dev/null
@@ -1,30 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you 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.
-#
-
-pkg.name: libs/flash_test
-pkg.description: flash HAL tester
-pkg.homepage: "http://mynewt.apache.org/"
-pkg.keywords:
-
-pkg.deps:
-    - libs/os
-    - libs/util
-    - hw/hal
-pkg.req_apis:
-    - console


[15/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/include/os/os_dev.h
----------------------------------------------------------------------
diff --git a/libs/os/include/os/os_dev.h b/libs/os/include/os/os_dev.h
deleted file mode 100644
index def42c0..0000000
--- a/libs/os/include/os/os_dev.h
+++ /dev/null
@@ -1,114 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 _OS_DEV_H
-#define _OS_DEV_H
-
-#include <os/os.h>
-
-#include "os/queue.h"
-
-struct os_dev;
-
-/*
- * Initialization order, defines when a device should be initialized
- * by the Mynewt kernel.
- *
- */
-#define OS_DEV_INIT_PRIMARY   (1)
-#define OS_DEV_INIT_SECONDARY (2)
-#define OS_DEV_INIT_KERNEL    (3)
-
-#define OS_DEV_INIT_F_CRITICAL (1 << 0)
-
-
-#define OS_DEV_INIT_PRIO_DEFAULT (0xff)
-
-/**
- * Device status, so functions can ensure device is called in a
- * consistent state.
- */
-#define OS_DEV_F_STATUS_READY     (1 << 0)
-#define OS_DEV_F_STATUS_OPEN      (1 << 1)
-#define OS_DEV_F_STATUS_SUSPENDED (1 << 2)
-#define OS_DEV_F_INIT_CRITICAL    (1 << 3)
-
-typedef int (*os_dev_init_func_t)(struct os_dev *, void *);
-typedef int (*os_dev_open_func_t)(struct os_dev *, uint32_t,
-        void *);
-typedef int (*os_dev_suspend_func_t)(struct os_dev *, os_time_t, int);
-typedef int (*os_dev_resume_func_t)(struct os_dev *);
-typedef int (*os_dev_close_func_t)(struct os_dev *);
-
-struct os_dev_handlers {
-    os_dev_open_func_t od_open;
-    os_dev_suspend_func_t od_suspend;
-    os_dev_resume_func_t od_resume;
-    os_dev_close_func_t od_close;
-};
-
-/*
- * Device structure.
- */
-struct os_dev {
-    struct os_dev_handlers od_handlers;
-    os_dev_init_func_t od_init;
-    void *od_init_arg;
-    uint8_t od_stage;
-    uint8_t od_priority;
-    uint8_t od_open_ref;
-    uint8_t od_flags;
-    char *od_name;
-    STAILQ_ENTRY(os_dev) od_next;
-};
-
-#define OS_DEV_SETHANDLERS(__dev, __open, __close)          \
-    (__dev)->od_handlers.od_open = (__open);                \
-    (__dev)->od_handlers.od_close = (__close);
-
-static inline int
-os_dev_suspend(struct os_dev *dev, os_time_t suspend_t, uint8_t force)
-{
-    if (dev->od_handlers.od_suspend == NULL) {
-        return (0);
-    } else {
-        return (dev->od_handlers.od_suspend(dev, suspend_t, force));
-    }
-}
-
-static inline int
-os_dev_resume(struct os_dev *dev)
-{
-    if (dev->od_handlers.od_resume == NULL) {
-        return (0);
-    } else {
-        return (dev->od_handlers.od_resume(dev));
-    }
-}
-
-int os_dev_create(struct os_dev *dev, char *name, uint8_t stage,
-        uint8_t priority, os_dev_init_func_t od_init, void *arg);
-int os_dev_initialize_all(uint8_t stage);
-int os_dev_suspend_all(os_time_t, uint8_t);
-int os_dev_resume_all(void);
-struct os_dev *os_dev_open(char *devname, uint32_t timo, void *arg);
-int os_dev_close(struct os_dev *dev);
-void os_dev_reset(void);
-
-#endif /* _OS_DEV_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/include/os/os_eventq.h
----------------------------------------------------------------------
diff --git a/libs/os/include/os/os_eventq.h b/libs/os/include/os/os_eventq.h
deleted file mode 100644
index b298f92..0000000
--- a/libs/os/include/os/os_eventq.h
+++ /dev/null
@@ -1,51 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 _OS_EVENTQ_H
-#define _OS_EVENTQ_H
-
-#include <inttypes.h>
-#include <os/os_time.h>
-
-struct os_event {
-    uint8_t ev_queued;
-    uint8_t ev_type;
-    void *ev_arg;
-    STAILQ_ENTRY(os_event) ev_next;
-};
-
-#define OS_EVENT_QUEUED(__ev) ((__ev)->ev_queued)
-
-#define OS_EVENT_T_TIMER (1)
-#define OS_EVENT_T_MQUEUE_DATA (2)
-#define OS_EVENT_T_PERUSER (16)
-
-struct os_eventq {
-    struct os_task *evq_task;
-    STAILQ_HEAD(, os_event) evq_list;
-};
-
-void os_eventq_init(struct os_eventq *);
-void os_eventq_put(struct os_eventq *, struct os_event *);
-struct os_event *os_eventq_get(struct os_eventq *);
-struct os_event *os_eventq_poll(struct os_eventq **, int, os_time_t);
-void os_eventq_remove(struct os_eventq *, struct os_event *);
-
-#endif /* _OS_EVENTQ_H */
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/include/os/os_heap.h
----------------------------------------------------------------------
diff --git a/libs/os/include/os/os_heap.h b/libs/os/include/os/os_heap.h
deleted file mode 100644
index e526537..0000000
--- a/libs/os/include/os/os_heap.h
+++ /dev/null
@@ -1,30 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 H_OS_HEAP_
-#define H_OS_HEAP_
-
-#include <stddef.h>
-
-void *os_malloc(size_t size);
-void os_free(void *mem);
-void *os_realloc(void *ptr, size_t size);
-
-#endif
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/include/os/os_malloc.h
----------------------------------------------------------------------
diff --git a/libs/os/include/os/os_malloc.h b/libs/os/include/os/os_malloc.h
deleted file mode 100644
index 1823856..0000000
--- a/libs/os/include/os/os_malloc.h
+++ /dev/null
@@ -1,34 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 H_OS_MALLOC_
-#define H_OS_MALLOC_
-
-#include "os/os_heap.h"
-
-#undef  malloc
-#define malloc  os_malloc
-
-#undef  free
-#define free    os_free
-
-#undef  realloc
-#define realloc  os_realloc
-
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/include/os/os_mbuf.h
----------------------------------------------------------------------
diff --git a/libs/os/include/os/os_mbuf.h b/libs/os/include/os/os_mbuf.h
deleted file mode 100644
index e0733fd..0000000
--- a/libs/os/include/os/os_mbuf.h
+++ /dev/null
@@ -1,297 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 _OS_MBUF_H 
-#define _OS_MBUF_H 
-
-#include "os/queue.h"
-#include "os/os_eventq.h"
-
-/**
- * A mbuf pool from which to allocate mbufs. This contains a pointer to the os 
- * mempool to allocate mbufs out of, the total number of elements in the pool, 
- * and the amount of "user" data in a non-packet header mbuf. The total pool 
- * size, in bytes, should be: 
- *  os_mbuf_count * (omp_databuf_len + sizeof(struct os_mbuf))
- */
-struct os_mbuf_pool {
-    /** 
-     * Total length of the databuf in each mbuf.  This is the size of the 
-     * mempool block, minus the mbuf header
-     */
-    uint16_t omp_databuf_len;
-    /**
-     * Total number of memblock's allocated in this mempool.
-     */
-    uint16_t omp_mbuf_count;
-    /**
-     * The memory pool which to allocate mbufs out of 
-     */
-    struct os_mempool *omp_pool;
-
-    /**
-     * Link to the next mbuf pool for system memory pools.
-     */
-    STAILQ_ENTRY(os_mbuf_pool) omp_next;
-};
-
-
-/**
- * A packet header structure that preceeds the mbuf packet headers.
- */
-struct os_mbuf_pkthdr {
-    /**
-     * Overall length of the packet. 
-     */
-    uint16_t omp_len;
-    /**
-     * Flags
-     */
-    uint16_t omp_flags;
-    /**
-     * Next packet in the mbuf chain.
-     */
-    STAILQ_ENTRY(os_mbuf_pkthdr) omp_next;
-};
-
-/**
- * Chained memory buffer.
- */
-struct os_mbuf {
-    /**
-     * Current pointer to data in the structure
-     */
-    uint8_t *om_data;
-    /**
-     * Flags associated with this buffer, see OS_MBUF_F_* defintions
-     */
-    uint8_t om_flags;
-    /**
-     * Length of packet header
-     */
-    uint8_t om_pkthdr_len;
-    /**
-     * Length of data in this buffer 
-     */
-    uint16_t om_len;
-
-    /**
-     * The mbuf pool this mbuf was allocated out of 
-     */
-    struct os_mbuf_pool *om_omp;
-
-    /**
-     * Pointer to next entry in the chained memory buffer
-     */
-    SLIST_ENTRY(os_mbuf) om_next;
-
-    /**
-     * Pointer to the beginning of the data, after this buffer
-     */
-    uint8_t om_databuf[0];
-};
-
-struct os_mqueue {
-    STAILQ_HEAD(, os_mbuf_pkthdr) mq_head;
-    struct os_event mq_ev;
-};
-
-/*
- * Given a flag number, provide the mask for it
- *
- * @param __n The number of the flag in the mask 
- */
-#define OS_MBUF_F_MASK(__n) (1 << (__n))
-
-/* 
- * Checks whether a given mbuf is a packet header mbuf 
- *
- * @param __om The mbuf to check 
- */
-#define OS_MBUF_IS_PKTHDR(__om) \
-    ((__om)->om_pkthdr_len >= sizeof (struct os_mbuf_pkthdr))
-
-/* Get a packet header pointer given an mbuf pointer */
-#define OS_MBUF_PKTHDR(__om) ((struct os_mbuf_pkthdr *)     \
-    ((uint8_t *)&(__om)->om_data + sizeof(struct os_mbuf)))
-
-/* Given a mbuf packet header pointer, return a pointer to the mbuf */
-#define OS_MBUF_PKTHDR_TO_MBUF(__hdr)   \
-     (struct os_mbuf *)((uint8_t *)(__hdr) - sizeof(struct os_mbuf))
-
-/**
- * Gets the length of an entire mbuf chain.  The specified mbuf must have a
- * packet header.
- */
-#define OS_MBUF_PKTLEN(__om) (OS_MBUF_PKTHDR(__om)->omp_len)
-
-/*
- * Access the data of a mbuf, and cast it to type
- *
- * @param __om The mbuf to access, and cast 
- * @param __type The type to cast it to 
- */
-#define OS_MBUF_DATA(__om, __type) \
-     (__type) ((__om)->om_data)
-
-/**
- * Access the "user header" in the head of an mbuf chain.
- *
- * @param om                    Pointer to the head of an mbuf chain.
- */
-#define OS_MBUF_USRHDR(om)                              \
-    (void *)((uint8_t *)om + sizeof (struct os_mbuf) +  \
-             sizeof (struct os_mbuf_pkthdr))
-
-/**
- * Retrieves the length of the user header in an mbuf.
- *
- * @param om                    Pointer to the mbuf to query.
- */
-#define OS_MBUF_USRHDR_LEN(om) \
-    ((om)->om_pkthdr_len - sizeof (struct os_mbuf_pkthdr))
-
-/*
- * Called by OS_MBUF_LEADINGSPACE() macro
- */
-static inline uint16_t 
-_os_mbuf_leadingspace(struct os_mbuf *om)
-{
-    uint16_t startoff;
-    uint16_t leadingspace;
-
-    startoff = 0;
-    if (OS_MBUF_IS_PKTHDR(om)) {
-        startoff = om->om_pkthdr_len;
-    }
-
-    leadingspace = (uint16_t) (OS_MBUF_DATA(om, uint8_t *) - 
-        ((uint8_t *) &om->om_databuf[0] + startoff));
-
-    return (leadingspace);
-}
-
-/**
- * Returns the leading space (space at the beginning) of the mbuf. 
- * Works on both packet header, and regular mbufs, as it accounts 
- * for the additional space allocated to the packet header.
- * 
- * @param __omp Is the mbuf pool (which contains packet header length.)
- * @param __om  Is the mbuf in that pool to get the leadingspace for 
- *
- * @return Amount of leading space available in the mbuf 
- */
-#define OS_MBUF_LEADINGSPACE(__om) _os_mbuf_leadingspace(__om)
-
-/* Called by OS_MBUF_TRAILINGSPACE() macro. */
-static inline uint16_t 
-_os_mbuf_trailingspace(struct os_mbuf *om)
-{
-    struct os_mbuf_pool *omp;
-
-    omp = om->om_omp;
-
-    return (&om->om_databuf[0] + omp->omp_databuf_len) -
-      (om->om_data + om->om_len);
-}
-
-/**
- * Returns the trailing space (space at the end) of the mbuf.
- * Works on both packet header and regular mbufs.
- *
- * @param __omp The mbuf pool for this mbuf 
- * @param __om  Is the mbuf in that pool to get trailing space for 
- *
- * @return The amount of trailing space available in the mbuf 
- */
-#define OS_MBUF_TRAILINGSPACE(__om) _os_mbuf_trailingspace(__om)
-
-/* Mbuf queue functions */
-
-/* Initialize a mbuf queue */
-int os_mqueue_init(struct os_mqueue *, void *arg);
-
-/* Get an element from a mbuf queue */
-struct os_mbuf *os_mqueue_get(struct os_mqueue *);
-
-/* Put an element in a mbuf queue */
-int os_mqueue_put(struct os_mqueue *, struct os_eventq *, struct os_mbuf *);
-
-/* Register an mbuf pool with the system pool registry */
-int os_msys_register(struct os_mbuf_pool *);
-
-/* Return a mbuf from the system pool, given an indicative mbuf size */
-struct os_mbuf *os_msys_get(uint16_t dsize, uint16_t leadingspace);
-
-/* De-registers all mbuf pools from msys. */
-void os_msys_reset(void);
-
-/* Return a packet header mbuf from the system pool */
-struct os_mbuf *os_msys_get_pkthdr(uint16_t dsize, uint16_t user_hdr_len);
-
-int os_msys_count(void);
-int os_msys_num_free(void);
-
-/* Initialize a mbuf pool */
-int os_mbuf_pool_init(struct os_mbuf_pool *, struct os_mempool *mp, 
-        uint16_t, uint16_t);
-
-/* Allocate a new mbuf out of the os_mbuf_pool */ 
-struct os_mbuf *os_mbuf_get(struct os_mbuf_pool *omp, uint16_t);
-
-/* Allocate a new packet header mbuf out of the os_mbuf_pool */ 
-struct os_mbuf *os_mbuf_get_pkthdr(struct os_mbuf_pool *omp, 
-        uint8_t pkthdr_len);
-
-/* Duplicate a mbuf from the pool */
-struct os_mbuf *os_mbuf_dup(struct os_mbuf *m);
-
-struct os_mbuf *os_mbuf_off(const struct os_mbuf *om, int off,
-                            uint16_t *out_off);
-
-/* Copy data from an mbuf to a flat buffer. */
-int os_mbuf_copydata(const struct os_mbuf *m, int off, int len, void *dst);
-
-/* Append data onto a mbuf */
-int os_mbuf_append(struct os_mbuf *m, const void *, uint16_t);
-
-int os_mbuf_appendfrom(struct os_mbuf *dst, const struct os_mbuf *src,
-                       uint16_t src_off, uint16_t len);
-
-/* Free a mbuf */
-int os_mbuf_free(struct os_mbuf *mb);
-
-/* Free a mbuf chain */
-int os_mbuf_free_chain(struct os_mbuf *om);
-
-void os_mbuf_adj(struct os_mbuf *mp, int req_len);
-int os_mbuf_cmpf(const struct os_mbuf *om, int off, const void *data,
-                   int len);
-int os_mbuf_cmpm(const struct os_mbuf *om1, uint16_t offset1,
-                 const struct os_mbuf *om2, uint16_t offset2,
-                 uint16_t len);
-
-struct os_mbuf *os_mbuf_prepend(struct os_mbuf *om, int len);
-struct os_mbuf *os_mbuf_prepend_pullup(struct os_mbuf *om, uint16_t len);
-int os_mbuf_copyinto(struct os_mbuf *om, int off, const void *src, int len);
-void os_mbuf_concat(struct os_mbuf *first, struct os_mbuf *second);
-void *os_mbuf_extend(struct os_mbuf *om, uint16_t len);
-struct os_mbuf *os_mbuf_pullup(struct os_mbuf *om, uint16_t len);
-
-#endif /* _OS_MBUF_H */ 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/include/os/os_mempool.h
----------------------------------------------------------------------
diff --git a/libs/os/include/os/os_mempool.h b/libs/os/include/os/os_mempool.h
deleted file mode 100644
index a731618..0000000
--- a/libs/os/include/os/os_mempool.h
+++ /dev/null
@@ -1,94 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 _OS_MEMPOOL_H_
-#define _OS_MEMPOOL_H_
-
-#include "os/os.h"
-#include "os/queue.h"
-
-/* 
- * A memory block structure. This simply contains a pointer to the free list 
- * chain and is only used when the block is on the free list. When the block 
- * has been removed from the free list the entire memory block is usable by the 
- * caller. 
- */
-struct os_memblock {
-    SLIST_ENTRY(os_memblock) mb_next;
-};
-
-/* XXX: Change this structure so that we keep the first address in the pool? */
-/* XXX: add memory debug structure and associated code */
-/* XXX: Change how I coded the SLIST_HEAD here. It should be named:
-   SLIST_HEAD(,os_memblock) mp_head; */
-
-/* Memory pool */
-struct os_mempool {
-    int mp_block_size;          /* Size of the memory blocks, in bytes. */
-    int mp_num_blocks;          /* The number of memory blocks. */
-    int mp_num_free;            /* The number of free blocks left */
-    uint32_t mp_membuf_addr;    /* Address of memory buffer used by pool */
-    STAILQ_ENTRY(os_mempool) mp_list;
-    SLIST_HEAD(,os_memblock);   /* Pointer to list of free blocks */
-    char *name;                 /* Name for memory block */
-};
-
-#define OS_MEMPOOL_INFO_NAME_LEN (32)
-
-struct os_mempool_info {
-    int omi_block_size;
-    int omi_num_blocks;
-    int omi_num_free;
-    char omi_name[OS_MEMPOOL_INFO_NAME_LEN];
-};
-
-struct os_mempool *os_mempool_info_get_next(struct os_mempool *, 
-        struct os_mempool_info *);
-
-/* 
- * To calculate size of the memory buffer needed for the pool. NOTE: This size 
- * is NOT in bytes! The size is the number of os_membuf_t elements required for 
- * the memory pool.
- */
-#if (OS_CFG_ALIGNMENT == OS_CFG_ALIGN_4)
-#define OS_MEMPOOL_SIZE(n,blksize)      ((((blksize) + 3) / 4) * (n))
-typedef uint32_t os_membuf_t;
-#else
-#define OS_MEMPOOL_SIZE(n,blksize)      ((((blksize) + 7) / 8) * (n)) 
-typedef uint64_t os_membuf_t;
-#endif
-
-/** Calculates the number of bytes required to initialize a memory pool. */
-#define OS_MEMPOOL_BYTES(n,blksize)     \
-    (sizeof (os_membuf_t) * OS_MEMPOOL_SIZE((n), (blksize)))
-
-/* Initialize a memory pool */
-os_error_t os_mempool_init(struct os_mempool *mp, int blocks, int block_size, 
-                           void *membuf, char *name);
-
-/* Checks if a memory block was allocated from the specified mempool. */
-int os_memblock_from(struct os_mempool *mp, void *block_addr);
-
-/* Get a memory block from the pool */
-void *os_memblock_get(struct os_mempool *mp);
-
-/* Put the memory block back into the pool */
-os_error_t os_memblock_put(struct os_mempool *mp, void *block_addr);
-
-#endif  /* _OS_MEMPOOL_H_ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/include/os/os_mutex.h
----------------------------------------------------------------------
diff --git a/libs/os/include/os/os_mutex.h b/libs/os/include/os/os_mutex.h
deleted file mode 100644
index 46c15f2..0000000
--- a/libs/os/include/os/os_mutex.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 _OS_MUTEX_H_
-#define _OS_MUTEX_H_
-
-#include "os/os.h"
-#include "os/queue.h"
-
-struct os_mutex
-{
-    SLIST_HEAD(, os_task) mu_head;  /* chain of waiting tasks */
-    uint8_t     _pad;
-    uint8_t     mu_prio;            /* owner's default priority*/
-    uint16_t    mu_level;           /* call nesting level */
-    struct os_task *mu_owner;       /* owners task */
-};
-
-/* 
-  XXX: NOTES
-    -> Should we add a magic number or flag to the mutex structure so
-    that we know that this is a mutex? We can use it for double checking
-    that a proper mutex was passed in to the API.
-    -> What debug information should we add to this structure? Who last
-    acquired the mutex? File/line where it was released?
-    -> Should we add a name to the mutex?
-    -> Should we add a "os_mutex_inspect() api?
-*/
-
-/* XXX: api to create
-os_mutex_inspect(); 
-*/ 
-
-/* Initialize a mutex */
-os_error_t os_mutex_init(struct os_mutex *mu);
-
-/* Release a mutex */
-os_error_t os_mutex_release(struct os_mutex *mu);
-
-/* Pend (wait) for a mutex */
-os_error_t os_mutex_pend(struct os_mutex *mu, uint32_t timeout);
-
-#endif  /* _OS_MUTEX_H_ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/include/os/os_sanity.h
----------------------------------------------------------------------
diff --git a/libs/os/include/os/os_sanity.h b/libs/os/include/os/os_sanity.h
deleted file mode 100644
index fb93570..0000000
--- a/libs/os/include/os/os_sanity.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 _OS_SANITY_H
-#define _OS_SANITY_H
-
-#include <stdint.h>
-
-#include "os/os_time.h"
-#include "os/queue.h"
-
-struct os_sanity_check;
-typedef int (*os_sanity_check_func_t)(struct os_sanity_check *, void *);
-
-struct os_sanity_check {
-    os_time_t sc_checkin_last;
-    os_time_t sc_checkin_itvl;
-    os_sanity_check_func_t sc_func;
-    void *sc_arg;
-
-    SLIST_ENTRY(os_sanity_check) sc_next;
-
-};
-
-#define OS_SANITY_CHECK_SETFUNC(__sc, __f, __arg, __itvl)  \
-    (__sc)->sc_func = (__f);                               \
-    (__sc)->sc_arg = (__arg);                              \
-    (__sc)->sc_checkin_itvl = (__itvl) * OS_TICKS_PER_SEC;
-
-int os_sanity_init(void);
-void os_sanity_run(void);
-
-struct os_task;
-int os_sanity_task_checkin(struct os_task *);
-
-int os_sanity_check_init(struct os_sanity_check *);
-int os_sanity_check_register(struct os_sanity_check *);
-int os_sanity_check_reset(struct os_sanity_check *);
-
-#endif /* _OS_SANITY_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/include/os/os_sched.h
----------------------------------------------------------------------
diff --git a/libs/os/include/os/os_sched.h b/libs/os/include/os/os_sched.h
deleted file mode 100644
index ac45683..0000000
--- a/libs/os/include/os/os_sched.h
+++ /dev/null
@@ -1,37 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 _OS_SCHED_H
-#define _OS_SCHED_H
-
-#include "os/os_task.h"
-
-void os_sched_ctx_sw_hook(struct os_task *);
-struct os_task *os_sched_get_current_task(void);
-void os_sched_set_current_task(struct os_task *);
-struct os_task *os_sched_next_task(void);
-void os_sched(struct os_task *);
-void os_sched_os_timer_exp(void);
-os_error_t os_sched_insert(struct os_task *);
-int os_sched_sleep(struct os_task *, os_time_t nticks);
-int os_sched_wakeup(struct os_task *);
-void os_sched_resort(struct os_task *);
-os_time_t os_sched_wakeup_ticks(os_time_t now);
-
-#endif /* _OS_SCHED_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/include/os/os_sem.h
----------------------------------------------------------------------
diff --git a/libs/os/include/os/os_sem.h b/libs/os/include/os/os_sem.h
deleted file mode 100644
index 0d44f91..0000000
--- a/libs/os/include/os/os_sem.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 _OS_SEM_H_
-#define _OS_SEM_H_
-
-#include "os/queue.h"
-
-struct os_sem
-{
-    SLIST_HEAD(, os_task) sem_head;     /* chain of waiting tasks */
-    uint16_t    _pad;
-    uint16_t    sem_tokens;             /* # of tokens */
-};
-
-/* 
-  XXX: NOTES
-    -> Should we add a magic number or flag to the semaphore structure so
-    that we know that this is a semaphore? We can use it for double checking
-    that a proper semaphore was passed in to the API.
-    -> What debug information should we add to this structure? Who last
-    acquired the semaphore? File/line where it was released?
-    -> Should we add a name to the semaphore?
-    -> Should we add a "os_sem_inspect() api, like ucos?
-*/ 
-
-/* Create a semaphore */
-os_error_t os_sem_init(struct os_sem *sem, uint16_t tokens);
-
-/* Release a semaphore */
-os_error_t os_sem_release(struct os_sem *sem);
-
-/* Pend (wait) for a semaphore */
-os_error_t os_sem_pend(struct os_sem *sem, uint32_t timeout);
-
-#endif  /* _OS_MUTEX_H_ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/include/os/os_task.h
----------------------------------------------------------------------
diff --git a/libs/os/include/os/os_task.h b/libs/os/include/os/os_task.h
deleted file mode 100644
index 561583b..0000000
--- a/libs/os/include/os/os_task.h
+++ /dev/null
@@ -1,114 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 _OS_TASK_H
-#define _OS_TASK_H
-
-#include "os/os.h"
-#include "os/os_sanity.h" 
-#include "os/queue.h"
-
-/* The highest and lowest task priorities */
-#define OS_TASK_PRI_HIGHEST (0)
-#define OS_TASK_PRI_LOWEST  (0xff)
-
-/* 
- * Generic "object" structure. All objects that a task can wait on must
- * have a SLIST_HEAD(, os_task) head_name as the first element in the object 
- * structure. The element 'head_name' can be any name. See os_mutex.h or
- * os_sem.h for an example.
- */
-struct os_task_obj
-{
-    SLIST_HEAD(, os_task) obj_head;     /* chain of waiting tasks */
-};
-
-/* Task states */
-typedef enum os_task_state {
-    OS_TASK_READY = 1, 
-    OS_TASK_SLEEP = 2
-} os_task_state_t;
-
-/* Task flags */
-#define OS_TASK_FLAG_NO_TIMEOUT     (0x01U)
-#define OS_TASK_FLAG_SEM_WAIT       (0x02U)
-#define OS_TASK_FLAG_MUTEX_WAIT     (0x04U)
-
-typedef void (*os_task_func_t)(void *);
-
-#define OS_TASK_MAX_NAME_LEN (32)
-
-struct os_task {
-    os_stack_t *t_stackptr;
-    os_stack_t *t_stacktop;
-
-    uint16_t t_stacksize;
-    uint16_t t_pad;
-
-    uint8_t t_taskid;
-    uint8_t t_prio;
-    uint8_t t_state;
-    uint8_t t_flags;
-
-    const char *t_name;
-    os_task_func_t t_func;
-    void *t_arg;
-
-    void *t_obj;
-
-    struct os_sanity_check t_sanity_check;
-
-    os_time_t t_next_wakeup;
-    os_time_t t_run_time;
-    uint32_t t_ctx_sw_cnt;
-
-    /* Global list of all tasks, irrespective of run or sleep lists */
-    STAILQ_ENTRY(os_task) t_os_task_list;
-
-    /* Used to chain task to either the run or sleep list */
-    TAILQ_ENTRY(os_task) t_os_list;
-
-    /* Used to chain task to an object such as a semaphore or mutex */
-    SLIST_ENTRY(os_task) t_obj_list;
-};
-
-int os_task_init(struct os_task *, const char *, os_task_func_t, void *,
-        uint8_t, os_time_t, os_stack_t *, uint16_t);
-
-uint8_t os_task_count(void);
-
-struct os_task_info {
-    uint8_t oti_prio;
-    uint8_t oti_taskid;
-    uint8_t oti_state;
-    uint8_t oti_flags;
-    uint16_t oti_stkusage;
-    uint16_t oti_stksize;
-    uint32_t oti_cswcnt;
-    uint32_t oti_runtime;
-    os_time_t oti_last_checkin;
-    os_time_t oti_next_checkin;
-
-    char oti_name[OS_TASK_MAX_NAME_LEN];
-};
-struct os_task *os_task_info_get_next(const struct os_task *,
-        struct os_task_info *);
-
-
-#endif /* _OS_TASK_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/include/os/os_test.h
----------------------------------------------------------------------
diff --git a/libs/os/include/os/os_test.h b/libs/os/include/os/os_test.h
deleted file mode 100644
index 6701315..0000000
--- a/libs/os/include/os/os_test.h
+++ /dev/null
@@ -1,25 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 H_OS_TEST_
-#define H_OS_TEST_
-
-int os_test_all(void);
-
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/include/os/os_time.h
----------------------------------------------------------------------
diff --git a/libs/os/include/os/os_time.h b/libs/os/include/os/os_time.h
deleted file mode 100644
index 38b6bd9..0000000
--- a/libs/os/include/os/os_time.h
+++ /dev/null
@@ -1,111 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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.
- */
-
-/*-
- * Copyright (c) 1982, 1986, 1993
- *      The Regents of the University of California.  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.
- * 4. Neither the name of the University 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 REGENTS 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 REGENTS 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.
- *
- *      @(#)time.h      8.5 (Berkeley) 5/4/95
- * $FreeBSD$
- */
-
-#ifndef _OS_TIME_H
-#define _OS_TIME_H
-
-#include <stdbool.h>
-#include <stdint.h>
-
-#ifndef UINT32_MAX
-#define UINT32_MAX  0xFFFFFFFFU
-#endif
-
-typedef uint32_t os_time_t;
-#define OS_TIME_MAX UINT32_MAX
- 
-/* Used to wait forever for events and mutexs */
-#define OS_TIMEOUT_NEVER    (UINT32_MAX)
-
-os_time_t os_time_get(void);
-void os_time_advance(int ticks);
-void os_time_delay(int32_t osticks);
-
-#define OS_TIME_TICK_LT(__t1, __t2) ((int32_t) ((__t1) - (__t2)) < 0)
-#define OS_TIME_TICK_GT(__t1, __t2) ((int32_t) ((__t1) - (__t2)) > 0)
-#define OS_TIME_TICK_GEQ(__t1, __t2) ((int32_t) ((__t1) - (__t2)) >= 0)
-
-struct os_timeval {
-    int64_t tv_sec;         /* seconds since Jan 1 1970 */
-    int32_t tv_usec;        /* microseconds within the second */
-};
-
-struct os_timezone {
-    int16_t tz_minuteswest;     /* with respect to GMT */
-    int16_t tz_dsttime;         /* daylight savings time correction (if any) */
-};
-
-#define os_timeradd(tvp, uvp, vvp)                                      \
-        do {                                                            \
-                (vvp)->tv_sec = (tvp)->tv_sec + (uvp)->tv_sec;          \
-                (vvp)->tv_usec = (tvp)->tv_usec + (uvp)->tv_usec;       \
-                if ((vvp)->tv_usec >= 1000000) {                        \
-                        (vvp)->tv_sec++;                                \
-                        (vvp)->tv_usec -= 1000000;                      \
-                }                                                       \
-        } while (0)
-
-#define os_timersub(tvp, uvp, vvp)                                      \
-        do {                                                            \
-                (vvp)->tv_sec = (tvp)->tv_sec - (uvp)->tv_sec;          \
-                (vvp)->tv_usec = (tvp)->tv_usec - (uvp)->tv_usec;       \
-                if ((vvp)->tv_usec < 0) {                               \
-                        (vvp)->tv_sec--;                                \
-                        (vvp)->tv_usec += 1000000;                      \
-                }                                                       \
-        } while (0)
-
-int os_settimeofday(struct os_timeval *utctime, struct os_timezone *tz);
-int os_gettimeofday(struct os_timeval *utctime, struct os_timezone *tz);
-int64_t os_get_uptime_usec(void);
-int os_time_ms_to_ticks(uint32_t ms, uint32_t *out_ticks);
-
-#endif /* _OS_TIME_H */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/include/os/queue.h
----------------------------------------------------------------------
diff --git a/libs/os/include/os/queue.h b/libs/os/include/os/queue.h
deleted file mode 100755
index 01739af..0000000
--- a/libs/os/include/os/queue.h
+++ /dev/null
@@ -1,514 +0,0 @@
-/*
- * Copyright (c) 1991, 1993
- *	The Regents of the University of California.  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.
- * 4. Neither the name of the University 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 REGENTS 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 REGENTS 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.
- *
- *	@(#)queue.h	8.5 (Berkeley) 8/20/94
- * $FreeBSD: src/sys/sys/queue.h,v 1.32.2.7 2002/04/17 14:21:02 des Exp $
- */
-
-#ifndef _QUEUE_H_
-#define	_QUEUE_H_
-
-/*
- * This file defines five types of data structures: singly-linked lists,
- * singly-linked tail queues, lists, tail queues, and circular queues.
- *
- * A singly-linked list is headed by a single forward pointer. The elements
- * are singly linked for minimum space and pointer manipulation overhead at
- * the expense of O(n) removal for arbitrary elements. New elements can be
- * added to the list after an existing element or at the head of the list.
- * Elements being removed from the head of the list should use the explicit
- * macro for this purpose for optimum efficiency. A singly-linked list may
- * only be traversed in the forward direction.  Singly-linked lists are ideal
- * for applications with large datasets and few or no removals or for
- * implementing a LIFO queue.
- *
- * A singly-linked tail queue is headed by a pair of pointers, one to the
- * head of the list and the other to the tail of the list. The elements are
- * singly linked for minimum space and pointer manipulation overhead at the
- * expense of O(n) removal for arbitrary elements. New elements can be added
- * to the list after an existing element, at the head of the list, or at the
- * end of the list. Elements being removed from the head of the tail queue
- * should use the explicit macro for this purpose for optimum efficiency.
- * A singly-linked tail queue may only be traversed in the forward direction.
- * Singly-linked tail queues are ideal for applications with large datasets
- * and few or no removals or for implementing a FIFO queue.
- *
- * A list is headed by a single forward pointer (or an array of forward
- * pointers for a hash table header). The elements are doubly linked
- * so that an arbitrary element can be removed without a need to
- * traverse the list. New elements can be added to the list before
- * or after an existing element or at the head of the list. A list
- * may only be traversed in the forward direction.
- *
- * A tail queue is headed by a pair of pointers, one to the head of the
- * list and the other to the tail of the list. The elements are doubly
- * linked so that an arbitrary element can be removed without a need to
- * traverse the list. New elements can be added to the list before or
- * after an existing element, at the head of the list, or at the end of
- * the list. A tail queue may be traversed in either direction.
- *
- * A circle queue is headed by a pair of pointers, one to the head of the
- * list and the other to the tail of the list. The elements are doubly
- * linked so that an arbitrary element can be removed without a need to
- * traverse the list. New elements can be added to the list before or after
- * an existing element, at the head of the list, or at the end of the list.
- * A circle queue may be traversed in either direction, but has a more
- * complex end of list detection.
- *
- * For details on the use of these macros, see the queue(3) manual page.
- *
- *
- *                      SLIST   LIST    STAILQ  TAILQ   CIRCLEQ
- * _HEAD                +       +       +       +       +
- * _HEAD_INITIALIZER    +       +       +       +       +
- * _ENTRY               +       +       +       +       +
- * _INIT                +       +       +       +       +
- * _EMPTY               +       +       +       +       +
- * _FIRST               +       +       +       +       +
- * _NEXT                +       +       +       +       +
- * _PREV                -       -       -       +       +
- * _LAST                -       -       +       +       +
- * _FOREACH             +       +       +       +       +
- * _FOREACH_REVERSE     -       -       -       +       +
- * _INSERT_HEAD         +       +       +       +       +
- * _INSERT_BEFORE       -       +       -       +       +
- * _INSERT_AFTER        +       +       +       +       +
- * _INSERT_TAIL         -       -       +       +       +
- * _REMOVE_HEAD         +       -       +       -       -
- * _REMOVE              +       +       +       +       +
- *
- */
-
-/*
- * Singly-linked List declarations.
- */
-#define	SLIST_HEAD(name, type)                          \
-struct name {                                           \
-    struct type *slh_first;	/* first element */         \
-}
-
-#define	SLIST_HEAD_INITIALIZER(head)                    \
-    { NULL }
- 
-#define	SLIST_ENTRY(type)                               \
-struct {                                                \
-    struct type *sle_next;  /* next element */          \
-}
- 
-/*
- * Singly-linked List functions.
- */
-#define SLIST_EMPTY(head)   ((head)->slh_first == NULL)
-
-#define SLIST_FIRST(head)   ((head)->slh_first)
-
-#define SLIST_FOREACH(var, head, field)                 \
-    for ((var) = SLIST_FIRST((head));                   \
-        (var);                                          \
-        (var) = SLIST_NEXT((var), field))
-
-#define SLIST_INIT(head) do {                           \
-        SLIST_FIRST((head)) = NULL;                     \
-} while (0)
-
-#define SLIST_INSERT_AFTER(slistelm, elm, field) do {           \
-    SLIST_NEXT((elm), field) = SLIST_NEXT((slistelm), field);   \
-    SLIST_NEXT((slistelm), field) = (elm);                      \
-} while (0)
-
-#define SLIST_INSERT_HEAD(head, elm, field) do {            \
-    SLIST_NEXT((elm), field) = SLIST_FIRST((head));         \
-    SLIST_FIRST((head)) = (elm);                            \
-} while (0)
-
-#define SLIST_NEXT(elm, field)	((elm)->field.sle_next)
-
-#define SLIST_REMOVE(head, elm, type, field) do {           \
-    if (SLIST_FIRST((head)) == (elm)) {                     \
-        SLIST_REMOVE_HEAD((head), field);                   \
-    }                                                       \
-    else {                                                  \
-        struct type *curelm = SLIST_FIRST((head));          \
-        while (SLIST_NEXT(curelm, field) != (elm))          \
-            curelm = SLIST_NEXT(curelm, field);             \
-        SLIST_NEXT(curelm, field) =                         \
-            SLIST_NEXT(SLIST_NEXT(curelm, field), field);   \
-    }                                                       \
-} while (0)
-
-#define SLIST_REMOVE_HEAD(head, field) do {                         \
-    SLIST_FIRST((head)) = SLIST_NEXT(SLIST_FIRST((head)), field);   \
-} while (0)
-
-/*
- * Singly-linked Tail queue declarations.
- */
-#define	STAILQ_HEAD(name, type)						\
-struct name {								\
-	struct type *stqh_first;/* first element */			\
-	struct type **stqh_last;/* addr of last next element */		\
-}
-
-#define	STAILQ_HEAD_INITIALIZER(head)					\
-	{ NULL, &(head).stqh_first }
-
-#define	STAILQ_ENTRY(type)						\
-struct {								\
-	struct type *stqe_next;	/* next element */			\
-}
-
-/*
- * Singly-linked Tail queue functions.
- */
-#define	STAILQ_EMPTY(head)	((head)->stqh_first == NULL)
-
-#define	STAILQ_FIRST(head)	((head)->stqh_first)
-
-#define	STAILQ_FOREACH(var, head, field)				\
-	for((var) = STAILQ_FIRST((head));				\
-	   (var);							\
-	   (var) = STAILQ_NEXT((var), field))
-
-#define	STAILQ_INIT(head) do {						\
-	STAILQ_FIRST((head)) = NULL;					\
-	(head)->stqh_last = &STAILQ_FIRST((head));			\
-} while (0)
-
-#define	STAILQ_INSERT_AFTER(head, tqelm, elm, field) do {		\
-	if ((STAILQ_NEXT((elm), field) = STAILQ_NEXT((tqelm), field)) == NULL)\
-		(head)->stqh_last = &STAILQ_NEXT((elm), field);		\
-	STAILQ_NEXT((tqelm), field) = (elm);				\
-} while (0)
-
-#define	STAILQ_INSERT_HEAD(head, elm, field) do {			\
-	if ((STAILQ_NEXT((elm), field) = STAILQ_FIRST((head))) == NULL)	\
-		(head)->stqh_last = &STAILQ_NEXT((elm), field);		\
-	STAILQ_FIRST((head)) = (elm);					\
-} while (0)
-
-#define	STAILQ_INSERT_TAIL(head, elm, field) do {			\
-	STAILQ_NEXT((elm), field) = NULL;				\
-	*(head)->stqh_last = (elm);					\
-	(head)->stqh_last = &STAILQ_NEXT((elm), field);			\
-} while (0)
-
-#define	STAILQ_LAST(head, type, field)					\
-	(STAILQ_EMPTY(head) ?						\
-		NULL :							\
-	        ((struct type *)					\
-		((char *)((head)->stqh_last) - offsetof(struct type, field))))
-
-#define	STAILQ_NEXT(elm, field)	((elm)->field.stqe_next)
-
-#define	STAILQ_REMOVE(head, elm, type, field) do {			\
-	if (STAILQ_FIRST((head)) == (elm)) {				\
-		STAILQ_REMOVE_HEAD(head, field);			\
-	}								\
-	else {								\
-		struct type *curelm = STAILQ_FIRST((head));		\
-		while (STAILQ_NEXT(curelm, field) != (elm))		\
-			curelm = STAILQ_NEXT(curelm, field);		\
-		if ((STAILQ_NEXT(curelm, field) =			\
-		     STAILQ_NEXT(STAILQ_NEXT(curelm, field), field)) == NULL)\
-			(head)->stqh_last = &STAILQ_NEXT((curelm), field);\
-	}								\
-} while (0)
-
-#define	STAILQ_REMOVE_HEAD(head, field) do {				\
-	if ((STAILQ_FIRST((head)) =					\
-	     STAILQ_NEXT(STAILQ_FIRST((head)), field)) == NULL)		\
-		(head)->stqh_last = &STAILQ_FIRST((head));		\
-} while (0)
-
-#define	STAILQ_REMOVE_HEAD_UNTIL(head, elm, field) do {			\
-	if ((STAILQ_FIRST((head)) = STAILQ_NEXT((elm), field)) == NULL)	\
-		(head)->stqh_last = &STAILQ_FIRST((head));		\
-} while (0)
-
-#define STAILQ_REMOVE_AFTER(head, elm, field) do {			\
-	if ((STAILQ_NEXT(elm, field) =					\
-	     STAILQ_NEXT(STAILQ_NEXT(elm, field), field)) == NULL)	\
-		(head)->stqh_last = &STAILQ_NEXT((elm), field);		\
-} while (0)
-
-/*
- * List declarations.
- */
-#define	LIST_HEAD(name, type)						\
-struct name {								\
-	struct type *lh_first;	/* first element */			\
-}
-
-#define	LIST_HEAD_INITIALIZER(head)					\
-	{ NULL }
-
-#define	LIST_ENTRY(type)						\
-struct {								\
-	struct type *le_next;	/* next element */			\
-	struct type **le_prev;	/* address of previous next element */	\
-}
-
-/*
- * List functions.
- */
-
-#define	LIST_EMPTY(head)	((head)->lh_first == NULL)
-
-#define	LIST_FIRST(head)	((head)->lh_first)
-
-#define	LIST_FOREACH(var, head, field)					\
-	for ((var) = LIST_FIRST((head));				\
-	    (var);							\
-	    (var) = LIST_NEXT((var), field))
-
-#define	LIST_INIT(head) do {						\
-	LIST_FIRST((head)) = NULL;					\
-} while (0)
-
-#define	LIST_INSERT_AFTER(listelm, elm, field) do {			\
-	if ((LIST_NEXT((elm), field) = LIST_NEXT((listelm), field)) != NULL)\
-		LIST_NEXT((listelm), field)->field.le_prev =		\
-		    &LIST_NEXT((elm), field);				\
-	LIST_NEXT((listelm), field) = (elm);				\
-	(elm)->field.le_prev = &LIST_NEXT((listelm), field);		\
-} while (0)
-
-#define	LIST_INSERT_BEFORE(listelm, elm, field) do {			\
-	(elm)->field.le_prev = (listelm)->field.le_prev;		\
-	LIST_NEXT((elm), field) = (listelm);				\
-	*(listelm)->field.le_prev = (elm);				\
-	(listelm)->field.le_prev = &LIST_NEXT((elm), field);		\
-} while (0)
-
-#define	LIST_INSERT_HEAD(head, elm, field) do {				\
-	if ((LIST_NEXT((elm), field) = LIST_FIRST((head))) != NULL)	\
-		LIST_FIRST((head))->field.le_prev = &LIST_NEXT((elm), field);\
-	LIST_FIRST((head)) = (elm);					\
-	(elm)->field.le_prev = &LIST_FIRST((head));			\
-} while (0)
-
-#define	LIST_NEXT(elm, field)	((elm)->field.le_next)
-
-#define	LIST_REMOVE(elm, field) do {					\
-	if (LIST_NEXT((elm), field) != NULL)				\
-		LIST_NEXT((elm), field)->field.le_prev = 		\
-		    (elm)->field.le_prev;				\
-	*(elm)->field.le_prev = LIST_NEXT((elm), field);		\
-} while (0)
-
-/*
- * Tail queue declarations.
- */
-#define	TAILQ_HEAD(name, type)						\
-struct name {								\
-	struct type *tqh_first;	/* first element */			\
-	struct type **tqh_last;	/* addr of last next element */		\
-}
-
-#define	TAILQ_HEAD_INITIALIZER(head)					\
-	{ NULL, &(head).tqh_first }
-
-#define	TAILQ_ENTRY(type)						\
-struct {								\
-	struct type *tqe_next;	/* next element */			\
-	struct type **tqe_prev;	/* address of previous next element */	\
-}
-
-/*
- * Tail queue functions.
- */
-#define	TAILQ_EMPTY(head)	((head)->tqh_first == NULL)
-
-#define	TAILQ_FIRST(head)	((head)->tqh_first)
-
-#define	TAILQ_FOREACH(var, head, field)					\
-	for ((var) = TAILQ_FIRST((head));				\
-	    (var);							\
-	    (var) = TAILQ_NEXT((var), field))
-
-#define	TAILQ_FOREACH_REVERSE(var, head, headname, field)		\
-	for ((var) = TAILQ_LAST((head), headname);			\
-	    (var);							\
-	    (var) = TAILQ_PREV((var), headname, field))
-
-#define	TAILQ_INIT(head) do {						\
-	TAILQ_FIRST((head)) = NULL;					\
-	(head)->tqh_last = &TAILQ_FIRST((head));			\
-} while (0)
-
-#define	TAILQ_INSERT_AFTER(head, listelm, elm, field) do {		\
-	if ((TAILQ_NEXT((elm), field) = TAILQ_NEXT((listelm), field)) != NULL)\
-		TAILQ_NEXT((elm), field)->field.tqe_prev = 		\
-		    &TAILQ_NEXT((elm), field);				\
-	else								\
-		(head)->tqh_last = &TAILQ_NEXT((elm), field);		\
-	TAILQ_NEXT((listelm), field) = (elm);				\
-	(elm)->field.tqe_prev = &TAILQ_NEXT((listelm), field);		\
-} while (0)
-
-#define	TAILQ_INSERT_BEFORE(listelm, elm, field) do {			\
-	(elm)->field.tqe_prev = (listelm)->field.tqe_prev;		\
-	TAILQ_NEXT((elm), field) = (listelm);				\
-	*(listelm)->field.tqe_prev = (elm);				\
-	(listelm)->field.tqe_prev = &TAILQ_NEXT((elm), field);		\
-} while (0)
-
-#define	TAILQ_INSERT_HEAD(head, elm, field) do {			\
-	if ((TAILQ_NEXT((elm), field) = TAILQ_FIRST((head))) != NULL)	\
-		TAILQ_FIRST((head))->field.tqe_prev =			\
-		    &TAILQ_NEXT((elm), field);				\
-	else								\
-		(head)->tqh_last = &TAILQ_NEXT((elm), field);		\
-	TAILQ_FIRST((head)) = (elm);					\
-	(elm)->field.tqe_prev = &TAILQ_FIRST((head));			\
-} while (0)
-
-#define	TAILQ_INSERT_TAIL(head, elm, field) do {			\
-	TAILQ_NEXT((elm), field) = NULL;				\
-	(elm)->field.tqe_prev = (head)->tqh_last;			\
-	*(head)->tqh_last = (elm);					\
-	(head)->tqh_last = &TAILQ_NEXT((elm), field);			\
-} while (0)
-
-#define	TAILQ_LAST(head, headname)					\
-	(*(((struct headname *)((head)->tqh_last))->tqh_last))
-
-#define	TAILQ_NEXT(elm, field) ((elm)->field.tqe_next)
-
-#define	TAILQ_PREV(elm, headname, field)				\
-	(*(((struct headname *)((elm)->field.tqe_prev))->tqh_last))
-
-#define	TAILQ_REMOVE(head, elm, field) do {				\
-	if ((TAILQ_NEXT((elm), field)) != NULL)				\
-		TAILQ_NEXT((elm), field)->field.tqe_prev = 		\
-		    (elm)->field.tqe_prev;				\
-	else								\
-		(head)->tqh_last = (elm)->field.tqe_prev;		\
-	*(elm)->field.tqe_prev = TAILQ_NEXT((elm), field);		\
-} while (0)
-
-/*
- * Circular queue declarations.
- */
-#define	CIRCLEQ_HEAD(name, type)					\
-struct name {								\
-	struct type *cqh_first;		/* first element */		\
-	struct type *cqh_last;		/* last element */		\
-}
-
-#define	CIRCLEQ_HEAD_INITIALIZER(head)					\
-	{ (void *)&(head), (void *)&(head) }
-
-#define	CIRCLEQ_ENTRY(type)						\
-struct {								\
-	struct type *cqe_next;		/* next element */		\
-	struct type *cqe_prev;		/* previous element */		\
-}
-
-/*
- * Circular queue functions.
- */
-#define	CIRCLEQ_EMPTY(head)	((head)->cqh_first == (void *)(head))
-
-#define	CIRCLEQ_FIRST(head)	((head)->cqh_first)
-
-#define	CIRCLEQ_FOREACH(var, head, field)				\
-	for ((var) = CIRCLEQ_FIRST((head));				\
-	    (var) != (void *)(head) || ((var) = NULL);			\
-	    (var) = CIRCLEQ_NEXT((var), field))
-
-#define	CIRCLEQ_FOREACH_REVERSE(var, head, field)			\
-	for ((var) = CIRCLEQ_LAST((head));				\
-	    (var) != (void *)(head) || ((var) = NULL);			\
-	    (var) = CIRCLEQ_PREV((var), field))
-
-#define	CIRCLEQ_INIT(head) do {						\
-	CIRCLEQ_FIRST((head)) = (void *)(head);				\
-	CIRCLEQ_LAST((head)) = (void *)(head);				\
-} while (0)
-
-#define	CIRCLEQ_INSERT_AFTER(head, listelm, elm, field) do {		\
-	CIRCLEQ_NEXT((elm), field) = CIRCLEQ_NEXT((listelm), field);	\
-	CIRCLEQ_PREV((elm), field) = (listelm);				\
-	if (CIRCLEQ_NEXT((listelm), field) == (void *)(head))		\
-		CIRCLEQ_LAST((head)) = (elm);				\
-	else								\
-		CIRCLEQ_PREV(CIRCLEQ_NEXT((listelm), field), field) = (elm);\
-	CIRCLEQ_NEXT((listelm), field) = (elm);				\
-} while (0)
-
-#define	CIRCLEQ_INSERT_BEFORE(head, listelm, elm, field) do {		\
-	CIRCLEQ_NEXT((elm), field) = (listelm);				\
-	CIRCLEQ_PREV((elm), field) = CIRCLEQ_PREV((listelm), field);	\
-	if (CIRCLEQ_PREV((listelm), field) == (void *)(head))		\
-		CIRCLEQ_FIRST((head)) = (elm);				\
-	else								\
-		CIRCLEQ_NEXT(CIRCLEQ_PREV((listelm), field), field) = (elm);\
-	CIRCLEQ_PREV((listelm), field) = (elm);				\
-} while (0)
-
-#define	CIRCLEQ_INSERT_HEAD(head, elm, field) do {			\
-	CIRCLEQ_NEXT((elm), field) = CIRCLEQ_FIRST((head));		\
-	CIRCLEQ_PREV((elm), field) = (void *)(head);			\
-	if (CIRCLEQ_LAST((head)) == (void *)(head))			\
-		CIRCLEQ_LAST((head)) = (elm);				\
-	else								\
-		CIRCLEQ_PREV(CIRCLEQ_FIRST((head)), field) = (elm);	\
-	CIRCLEQ_FIRST((head)) = (elm);					\
-} while (0)
-
-#define	CIRCLEQ_INSERT_TAIL(head, elm, field) do {			\
-	CIRCLEQ_NEXT((elm), field) = (void *)(head);			\
-	CIRCLEQ_PREV((elm), field) = CIRCLEQ_LAST((head));		\
-	if (CIRCLEQ_FIRST((head)) == (void *)(head))			\
-		CIRCLEQ_FIRST((head)) = (elm);				\
-	else								\
-		CIRCLEQ_NEXT(CIRCLEQ_LAST((head)), field) = (elm);	\
-	CIRCLEQ_LAST((head)) = (elm);					\
-} while (0)
-
-#define	CIRCLEQ_LAST(head)	((head)->cqh_last)
-
-#define	CIRCLEQ_NEXT(elm,field)	((elm)->field.cqe_next)
-
-#define	CIRCLEQ_PREV(elm,field)	((elm)->field.cqe_prev)
-
-#define	CIRCLEQ_REMOVE(head, elm, field) do {				\
-	if (CIRCLEQ_NEXT((elm), field) == (void *)(head))		\
-		CIRCLEQ_LAST((head)) = CIRCLEQ_PREV((elm), field);	\
-	else								\
-		CIRCLEQ_PREV(CIRCLEQ_NEXT((elm), field), field) =	\
-		    CIRCLEQ_PREV((elm), field);				\
-	if (CIRCLEQ_PREV((elm), field) == (void *)(head))		\
-		CIRCLEQ_FIRST((head)) = CIRCLEQ_NEXT((elm), field);	\
-	else								\
-		CIRCLEQ_NEXT(CIRCLEQ_PREV((elm), field), field) =	\
-		    CIRCLEQ_NEXT((elm), field);				\
-} while (0)
-
-#endif /* !_QUEUE_H_ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/pkg.yml
----------------------------------------------------------------------
diff --git a/libs/os/pkg.yml b/libs/os/pkg.yml
deleted file mode 100644
index fa847a5..0000000
--- a/libs/os/pkg.yml
+++ /dev/null
@@ -1,84 +0,0 @@
-#
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements.  See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership.  The ASF licenses this file
-# to you 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.
-#
-
-pkg.name: libs/os
-pkg.description: Mynewt operating system core.
-pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
-pkg.homepage: "http://mynewt.apache.org/"
-pkg.keywords:
-
-pkg.deps:
-    - sys/sysinit
-    - libs/util
-
-pkg.req_apis:
-    - console
-
-pkg.deps.OS_CLI:
-    - libs/shell
-
-pkg.deps.OS_COREDUMP:
-    - sys/coredump
-
-pkg.init_function: os_pkg_init
-pkg.init_stage: 0
-
-pkg.syscfg_defs:
-    OS_CLI:
-        description: 'TBD'
-        value: 'MYNEWT_PKG_LIBS_SHELL'
-    OS_COREDUMP:
-        description: 'TBD'
-        value: 'MYNEWT_PKG_SYS_COREDUMP'
-    SANITY_INTERVAL:
-        description: 'The interval (in milliseconds) at which the sanity checks should run, should be at least 200ms prior to watchdog'
-        value: 59500
-    WATCHDOG_INTERVAL:
-        description: 'The interval (in milliseconds) at which the watchdog should reset if not tickled, in ms'
-        value: 60000
-    MSYS_1_BLOCK_COUNT:
-        description: 'TBD'
-        value: 12
-    MSYS_1_BLOCK_SIZE:
-        description: 'TBD'
-        value: 260
-    MSYS_2_BLOCK_COUNT:
-        description: 'TBD'
-        value: 0
-    MSYS_2_BLOCK_SIZE:
-        description: 'TBD'
-        value: 0
-    MSYS_3_BLOCK_COUNT:
-        description: 'TBD'
-        value: 0
-    MSYS_3_BLOCK_SIZE:
-        description: 'TBD'
-        value: 0
-    MSYS_4_BLOCK_COUNT:
-        description: 'TBD'
-        value: 0
-    MSYS_4_BLOCK_SIZE:
-        description: 'TBD'
-        value: 0
-    MSYS_5_BLOCK_COUNT:
-        description: 'TBD'
-        value: 0
-    MSYS_5_BLOCK_SIZE:
-        description: 'TBD'
-        value: 0

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/src/arch/cortex_m0/m0/HAL_CM0.s
----------------------------------------------------------------------
diff --git a/libs/os/src/arch/cortex_m0/m0/HAL_CM0.s b/libs/os/src/arch/cortex_m0/m0/HAL_CM0.s
deleted file mode 100644
index de7d46c..0000000
--- a/libs/os/src/arch/cortex_m0/m0/HAL_CM0.s
+++ /dev/null
@@ -1,277 +0,0 @@
-/*----------------------------------------------------------------------------
- * Copyright (c) 1999-2009 KEIL, 2009-2013 ARM Germany GmbH
- * 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 ARM  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 COPYRIGHT HOLDERS AND CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- *---------------------------------------------------------------------------*/
-
-        .file   "HAL_CM0.S"
-        .syntax unified
-
-/*----------------------------------------------------------------------------
- *      Functions
- *---------------------------------------------------------------------------*/
-
-        .thumb
-
-        .section ".text"
-        .align  2
-
-/*--------------------------- os_set_env ------------------------------------*/
-#       void os_set_env (void);
-#
-#   Called to switch to privileged or unprivileged thread mode. The variable
-#   'os_flags' contains the CONTROL bit LSB to set the device into the
-#   proper mode. We also use PSP so we set bit 1 (the SPSEL bit) to 1.
-#
-
-        .thumb_func
-        .type   os_set_env, %function
-        .global os_set_env
-os_set_env:
-        .fnstart
-        .cantunwind
-
-        MSR     PSP,R0
-        LDR     R0,=os_flags
-        LDRB    R0,[R0]
-        ADDS    R0, R0, #2
-        MSR     CONTROL,R0
-        ISB
-        BX      LR
-
-        .fnend
-        .size   os_set_env, .-os_set_env
-/*--------------------------- os_set_env ------------------------------------*/
-
-
-/*--------------------------- os_arch_init_task_stack------------------------*/
-#       void os_arch_init_task_stack(os_stack_t *sf);
-# NOTE: This function only stores R4 through R11 on stack. The reason we do 
-# this is that the application may have stored some values in some of the
-# registers and we want to preserve those values (position independent code
-# is a good example). The other registers are handled in the C startup code.
-        .thumb_func
-        .type   os_arch_init_task_stack, %function
-        .global os_arch_init_task_stack
-os_arch_init_task_stack:
-        .fnstart
-
-        MOV     R3,R0
-        STMIA   R0!,{R4-R7}
-        MOV     R4,R8
-        MOV     R5,R9
-        MOV     R6,R10
-        MOV     R7,R11
-        STMIA   R0!,{R4-R7}
-        LDM     R3!,{R4-R7}
-        BX      LR
-
-        .fnend
-        .size   os_arch_init_task_stack, .-os_arch_init_task_stack
-/*--------------------------- os_set_env ------------------------------------*/
-
-
-/*-------------------------- SVC_Handler ------------------------------------*/
-#       void SVC_Handler (void);
-        .thumb_func
-        .type   SVC_Handler, %function
-        .global SVC_Handler
-SVC_Handler:
-        .fnstart
-        .cantunwind
-        MRS     R0,PSP                  /* Read PSP */
-        LDR     R1,[R0,#24]             /* Read Saved PC from Stack */
-        SUBS    R1,R1,#2                /* Point to SVC Instruction */
-        LDRB    R1,[R1]                 /* Load SVC Number */
-        CMP     R1,#0
-        BNE     SVC_User                /* User SVC Number > 0 */
-        LDR     R1,[R0,#16]             /* Read saved R12 from Stack */
-        MOV     R12, R1                 /* Store in R12 */
-        LDMIA   R0,{R0-R3}              /* Read R0-R3 from stack */
-        PUSH    {LR}                    /* Save LR */
-        BLX     R12                     /* Call SVC Function */
-        MRS     R3,PSP                  /* Read PSP */
-        STMIA   R3!,{R0-R2}             /* Store return values */
-        POP     {PC}                    /* RETI */
-
-        /*------------------- User SVC ------------------------------*/
-SVC_User:
-        PUSH    {R4,LR}                 /* Save Registers */
-        LDR     R2,=SVC_Count
-        LDR     R2,[R2]
-        CMP     R1,R2
-        BHI     SVC_Done                /* Overflow */
-        LDR     R4,=SVC_Table-4
-        LSLS    R1,R1,#2
-        LDR     R4,[R4,R1]              /* Load SVC Function Address */
-        MOV     LR,R4
-        LDMIA   R0,{R0-R3,R4}           /* Read R0-R3,R12 from stack */
-        MOV     R12,R4
-        BLX     LR                      /* Call SVC Function */
-        MRS     R4,PSP                  /* Read PSP */
-        STMIA   R4!,{R0-R3}             /* Function return values */
-SVC_Done:
-        POP     {R4,PC}                 /* RETI */
-        .fnend
-        .size   SVC_Handler, .-SVC_Handler
-/*-------------------------- PendSV_Handler ---------------------------------*/
-#       void PendSV_Handler (void);
-        .thumb_func
-        .type   PendSV_Handler, %function
-        .global PendSV_Handler
-PendSV_Handler:
-        .fnstart
-        .cantunwind
-
-        LDR     R3,=g_os_run_list   /* Get highest priority task ready to run */
-        LDR     R2,[R3]             /* Store in R2 */
-        LDR     R3,=g_current_task  /* Get current task */
-        LDR     R1,[R3]             /* Current task in R1 */
-        CMP     R1,R2
-        BNE     context_switch
-        BX      LR                  /* RETI, no task switch */
-context_switch:
-        MRS     R0,PSP              /* Read PSP */
-        SUBS    R0,R0,#32
-        STMIA   R0!,{R4-R7}         /* Save Old context */
-        MOV     R4,R8
-        MOV     R5,R9
-        MOV     R6,R10
-        MOV     R7,R11
-        STMIA   R0!,{R4-R7}         /* Save Old context */
-        SUBS    R0,R0,#32
-
-        STR     R0,[R1,#0]          /* Update stack pointer in current task */
-        STR     R2,[R3]             /* g_current_task = highest ready */
-
-        LDR     R0,[R2,#0]          /* get stack pointer of task we will start */
-        ADDS    R0,R0, #16
-        LDMIA   R0!,{R4-R7}         /* Restore New Context */
-        MOV     R8,R4
-        MOV     R9,R5
-        MOV     R10,R6
-        MOV     R11,R7
-        MSR     PSP,R0              /* Write PSP */
-        SUBS    R0,R0,#32
-        LDMIA   R0!,{R4-R7}         /* Restore New Context */
-        BX      LR                  /* Return to Thread Mode */
-
-        .fnend
-        .size   PendSV_Handler, .-PendSV_Handler
-
-
-
-/*-------------------------- SysTick_Handler --------------------------------*/
-
-#       void SysTick_Handler (void);
-        .thumb_func
-        .type   SysTick_Handler, %function
-        .global SysTick_Handler
-SysTick_Handler:
-        .fnstart
-        .cantunwind
-
-        PUSH    {R4,LR}                 /* Save EXC_RETURN */
-        BL      timer_handler
-        POP     {R4,PC}                 /* Restore EXC_RETURN */
-
-        .fnend
-        .size   SysTick_Handler, .-SysTick_Handler
-
-/* divide-by-zero */
-        .thumb_func
-	.type __aeabi_idiv0, %function
-	.global __aeabi_idiv0
-	.global __aeabi_ldiv0
-__aeabi_idiv0:
-__aeabi_ldiv0:
-        .fnstart
-        .cantunwind
-	push {r0,r1,r5}
-	ldr r0, =file_name
-	ldr r1, =__LINE__
-	ldr r5, =__assert_func
-	bx r5
-        .fnend
-        .size   __aeabi_idiv0, .-__aeabi_idiv0
-
-/*-------------------------- Defalt IRQ --------------------------------*/
-        .thumb_func
-        .type   os_default_irq_asm, %function
-        .global os_default_irq_asm
-os_default_irq_asm:
-        .fnstart
-        .cantunwind
-
-        /*
-         * LR = 0xfffffff9 if we were using MSP as SP
-         * LR = 0xfffffffd if we were using PSP as SP
-         */
-        MOV     R0,LR
-        MOVS    R1,#4
-        TST     R0,R1
-        MRS     R12,MSP
-        BEQ     using_msp_as_sp
-        MRS     R12,PSP
-using_msp_as_sp:
-        /*
-         * Push the "trap frame" structure onto stack by moving R8-R11 into 
-         * R0-R3 and then pushing R0-R3. LR gets pushed as well with LR 
-         * residing at higher memory, R8 at the lower memory address.
-         */
-        MOV     R0,R8
-        MOV     R1,R9
-        MOV     R2,R10
-        MOV     R3,R11
-        PUSH    {R0-R3, LR}
-        /* Now push r3 - r7. R3 is the lowest memory address. */
-        MOV     R3,R12
-        PUSH    {R3-R7}
-        MOV     R0, SP
-        BL      os_default_irq
-        POP     {R3-R7}
-        POP     {R0-R3}
-        MOV     R8,R0
-        MOV     R9,R1
-        MOV     R10,R2
-        MOV     R11,R3
-        POP     {PC}                 /* Restore EXC_RETURN */
-
-        .fnend
-        .size   os_default_irq_asm, .-os_default_irq_asm
-
-        /*
-         * Prevent libgcc unwind stuff from getting pulled in.
-         */
-        .section ".data"
-        .global __aeabi_unwind_cpp_pr0
-__aeabi_unwind_cpp_pr0:
-	.section ".rodata"
-file_name:
-	.asciz __FILE__
-        .end
-
-/*----------------------------------------------------------------------------
- * end of file
- *---------------------------------------------------------------------------*/

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/src/arch/cortex_m0/m0/SVC_Table.s
----------------------------------------------------------------------
diff --git a/libs/os/src/arch/cortex_m0/m0/SVC_Table.s b/libs/os/src/arch/cortex_m0/m0/SVC_Table.s
deleted file mode 100755
index 2b99321..0000000
--- a/libs/os/src/arch/cortex_m0/m0/SVC_Table.s
+++ /dev/null
@@ -1,56 +0,0 @@
-;/*----------------------------------------------------------------------------
-; *      RL-ARM - RTX
-; *----------------------------------------------------------------------------
-; *      Name:    SVC_TABLE.S
-; *      Purpose: Pre-defined SVC Table for Cortex-M
-; *      Rev.:    V4.70
-; *----------------------------------------------------------------------------
-; *
-; * Copyright (c) 1999-2009 KEIL, 2009-2013 ARM Germany GmbH
-; * 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 ARM  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 COPYRIGHT HOLDERS AND CONTRIBUTORS BE
-; * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-; * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-; * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-; * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-; * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-; * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-; * POSSIBILITY OF SUCH DAMAGE.
-; *---------------------------------------------------------------------------*/
-
-
-        .file   "SVC_Table.S"
-
-
-        .section ".svc_table"
-
-        .global  SVC_Table
-SVC_Table:
-/* Insert user SVC functions here. SVC 0 used by RTL Kernel. */
-#       .long   __SVC_1                 /* user SVC function */
-SVC_End:
-
-        .global  SVC_Count
-SVC_Count:
-        .long   (SVC_End-SVC_Table)/4
-
-
-        .end
-
-/*----------------------------------------------------------------------------
- * end of file
- *---------------------------------------------------------------------------*/

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/os/src/arch/cortex_m0/os_arch_arm.c
----------------------------------------------------------------------
diff --git a/libs/os/src/arch/cortex_m0/os_arch_arm.c b/libs/os/src/arch/cortex_m0/os_arch_arm.c
deleted file mode 100755
index 65adc28..0000000
--- a/libs/os/src/arch/cortex_m0/os_arch_arm.c
+++ /dev/null
@@ -1,333 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include "os/os.h"
-#include "os/os_arch.h"
-#include <hal/hal_bsp.h>
-#include <hal/hal_os_tick.h>
-#include <bsp/cmsis_nvic.h>
-
-#include "os_priv.h"
-
-/*
- * From HAL_CM0.s
- */
-extern void SVC_Handler(void);
-extern void PendSV_Handler(void);
-extern void SysTick_Handler(void);
-/* XXX */
-
-/* Initial program status register */
-#define INITIAL_xPSR    0x01000000
-
-/*
- * Exception priorities. The higher the number, the lower the priority. A
- * higher priority exception will interrupt a lower priority exception.
- */
-#define PEND_SV_PRIO    ((1 << __NVIC_PRIO_BITS) - 1)
-#define OS_TICK_PRIO    (PEND_SV_PRIO - 1)
-
-/* Make the SVC instruction highest priority */
-#define SVC_PRIO        (1)
-
-/* Stack frame structure */
-struct stack_frame {
-    uint32_t    r4;
-    uint32_t    r5;
-    uint32_t    r6;
-    uint32_t    r7;
-    uint32_t    r8;
-    uint32_t    r9;
-    uint32_t    r10;
-    uint32_t    r11;
-    uint32_t    r0;
-    uint32_t    r1;
-    uint32_t    r2;
-    uint32_t    r3;
-    uint32_t    r12;
-    uint32_t    lr;
-    uint32_t    pc;
-    uint32_t    xpsr;
-};
-
-#define SVC_ArgN(n) \
-  register int __r##n __asm("r"#n);
-
-#define SVC_Arg0()  \
-  SVC_ArgN(0)       \
-  SVC_ArgN(1)       \
-  SVC_ArgN(2)       \
-  SVC_ArgN(3)
-
-#if (defined (__MCU_CORTEX_M0_H__)) || defined (__CORTEX_M0PLUS)
-#define SVC_Call(f)                                                     \
-  __asm volatile                                                        \
-  (                                                                     \
-    "ldr r7,="#f"\n\t"                                                  \
-    "mov r12,r7\n\t"                                                    \
-    "svc 0"                                                             \
-    :               "=r" (__r0), "=r" (__r1), "=r" (__r2), "=r" (__r3)  \
-    :                "r" (__r0),  "r" (__r1),  "r" (__r2),  "r" (__r3)  \
-    : "r7", "r12", "lr", "cc"                                           \
-  );
-#else
-#define SVC_Call(f)                                                     \
-  __asm volatile                                                        \
-  (                                                                     \
-    "ldr r12,="#f"\n\t"                                                 \
-    "svc 0"                                                             \
-    :               "=r" (__r0), "=r" (__r1), "=r" (__r2), "=r" (__r3)  \
-    :                "r" (__r0),  "r" (__r1),  "r" (__r2),  "r" (__r3)  \
-    : "r12", "lr", "cc"                                                 \
-  );
-#endif
-
-/* XXX: determine how we will deal with running un-privileged */
-uint32_t os_flags = OS_RUN_PRIV;
-
-void
-timer_handler(void)
-{
-    os_time_advance(1);
-}
-
-void
-os_arch_ctx_sw(struct os_task *t)
-{
-    os_sched_ctx_sw_hook(t);
-
-    /* Set PendSV interrupt pending bit to force context switch */
-    SCB->ICSR = SCB_ICSR_PENDSVSET_Msk;
-}
-
-os_sr_t
-os_arch_save_sr(void)
-{
-    uint32_t isr_ctx;
-
-    isr_ctx = __get_PRIMASK();
-    __disable_irq();
-    return (isr_ctx & 1);
-}
-
-void
-os_arch_restore_sr(os_sr_t isr_ctx)
-{
-    if (!isr_ctx) {
-        __enable_irq();
-    }
-}
-
-int
-os_arch_in_critical(void)
-{
-    uint32_t isr_ctx;
-
-    isr_ctx = __get_PRIMASK();
-    return (isr_ctx & 1);
-}
-
-os_stack_t *
-os_arch_task_stack_init(struct os_task *t, os_stack_t *stack_top, int size)
-{
-    int i;
-    os_stack_t *s;
-    struct stack_frame *sf;
-
-    /* Get stack frame pointer */
-    s = (os_stack_t *) ((uint8_t *) stack_top - sizeof(*sf));
-
-    /* Zero out R1-R3, R12, LR */
-    for (i = 9; i < 14; ++i) {
-        s[i] = 0;
-    }
-
-    /* Set registers R4 - R11 on stack. */
-    os_arch_init_task_stack(s);
-
-    /* Set remaining portions of stack frame */
-    sf = (struct stack_frame *) s;
-    sf->xpsr = INITIAL_xPSR;
-    sf->pc = (uint32_t)t->t_func;
-    sf->r0 = (uint32_t)t->t_arg;
-
-    return (s);
-}
-
-void
-os_arch_init(void)
-{
-    os_init_idle_task();
-}
-
-__attribute__((always_inline))
-static inline void
-svc_os_arch_init(void)
-{
-    SVC_Arg0();
-    SVC_Call(os_arch_init);
-}
-
-os_error_t
-os_arch_os_init(void)
-{
-    os_error_t err;
-    int i;
-
-    /* Cannot be called within an ISR */
-    err = OS_ERR_IN_ISR;
-    if (__get_IPSR() == 0) {
-        err = OS_OK;
-
-        /* Drop priority for all interrupts */
-        for (i = 0; i < sizeof(NVIC->IP); i++) {
-            NVIC->IP[i] = 0xff;
-        }
-
-        NVIC_SetVector(SVCall_IRQn, (uint32_t)SVC_Handler);
-        NVIC_SetVector(PendSV_IRQn, (uint32_t)PendSV_Handler);
-        NVIC_SetVector(SysTick_IRQn, (uint32_t)SysTick_Handler);
-
-        /*
-         * Install default interrupt handler, which'll print out system
-         * state at the time of the interrupt, and few other regs which
-         * should help in trying to figure out what went wrong.
-         */
-        NVIC_SetVector(NonMaskableInt_IRQn, (uint32_t)os_default_irq_asm);
-        NVIC_SetVector(HardFault_IRQn, (uint32_t)os_default_irq_asm);
-        NVIC_SetVector(-13, (uint32_t)os_default_irq_asm); /* Hardfault */
-        for (i = 0; i < NVIC_NUM_VECTORS - NVIC_USER_IRQ_OFFSET; i++) {
-            NVIC_SetVector(i, (uint32_t)os_default_irq_asm);
-        }
-
-        /* Set the PendSV interrupt exception priority to the lowest priority */
-        NVIC_SetPriority(PendSV_IRQn, PEND_SV_PRIO);
-
-        /* Set the SVC interrupt to priority 0 (highest configurable) */
-        NVIC_SetPriority(SVCall_IRQn, SVC_PRIO);
-
-        /* Check if privileged or not */
-        if ((__get_CONTROL() & 1) == 0) {
-            os_arch_init();
-        } else {
-            svc_os_arch_init();
-        }
-    }
-
-    return err;
-}
-
-uint32_t
-os_arch_start(void)
-{
-    struct os_task *t;
-
-    /* Get the highest priority ready to run to set the current task */
-    t = os_sched_next_task();
-    os_sched_set_current_task(t);
-
-    /* Adjust PSP so it looks like this task just took an exception */
-    __set_PSP((uint32_t)t->t_stackptr + offsetof(struct stack_frame, r0));
-
-    /* Intitialize and start system clock timer */
-    os_tick_init(OS_TICKS_PER_SEC, OS_TICK_PRIO);
-
-    /* Mark the OS as started, right before we run our first task */
-    g_os_started = 1;
-
-    /* Perform context switch */
-    os_arch_ctx_sw(t);
-
-    return (uint32_t)(t->t_arg);
-}
-
-__attribute__((always_inline))
-static inline void svc_os_arch_start(void)
-{
-    SVC_Arg0();
-    SVC_Call(os_arch_start);
-}
-
-/**
- * Start the OS. First check to see if we are running with the correct stack
- * pointer set (PSP) and privilege mode (PRIV).
- *
- * @return os_error_t
- */
-os_error_t
-os_arch_os_start(void)
-{
-    os_error_t err;
-
-    /*
-     * Set the os environment. This will set stack pointers and, based
-     * on the contents of os_flags, will determine if the tasks run in
-     * priviliged or un-privileged mode.
-     *
-     * We switch to using "empty" part of idle task's stack until
-     * the svc_os_arch_start() executes SVC, and we will never return.
-     */
-    os_set_env(g_idle_task.t_stackptr - 1);
-
-    err = OS_ERR_IN_ISR;
-    if (__get_IPSR() == 0) {
-        /*
-         * The following switch statement is really just a sanity check to
-         * insure that the os initialization routine was called prior to the
-         * os start routine.
-         */
-        err = OS_OK;
-        switch (__get_CONTROL() & 0x03) {
-        /*
-         * These two cases are for completeness. Thread mode should be set
-         * to use PSP already.
-         *
-         * Fall-through intentional!
-         */
-        case 0x00:
-        case 0x01:
-            err = OS_ERR_PRIV;
-            break;
-        case 0x02:
-            /*
-             * We are running in Privileged Thread mode w/SP = PSP but we
-             * are supposed to be un-privileged.
-             */
-            if ((os_flags & 1) == OS_RUN_UNPRIV) {
-                err = OS_ERR_PRIV;
-            }
-            break;
-        case 0x03:
-            /*
-             * We are running in Unprivileged Thread mode w/SP = PSP but we
-             * are supposed to be privileged.
-             */
-            if  ((os_flags & 1) == OS_RUN_PRIV) {
-                err = OS_ERR_PRIV;
-            }
-            break;
-        }
-        if (err == OS_OK) {
-            /* Always start OS through SVC call */
-            svc_os_arch_start();
-        }
-    }
-
-    return err;
-}


[08/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/tinycbor/src/cbortojson.c
----------------------------------------------------------------------
diff --git a/libs/tinycbor/src/cbortojson.c b/libs/tinycbor/src/cbortojson.c
deleted file mode 100644
index 953f2aa..0000000
--- a/libs/tinycbor/src/cbortojson.c
+++ /dev/null
@@ -1,686 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2016 Intel Corporation
-**
-** Permission is hereby granted, free of charge, to any person obtaining a copy
-** of this software and associated documentation files (the "Software"), to deal
-** in the Software without restriction, including without limitation the rights
-** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-** copies of the Software, and to permit persons to whom the Software is
-** furnished to do so, subject to the following conditions:
-**
-** The above copyright notice and this permission notice shall be included in
-** all copies or substantial portions of the Software.
-**
-** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-** THE SOFTWARE.
-**
-****************************************************************************/
-
-#define _BSD_SOURCE 1
-#define _DEFAULT_SOURCE 1
-#define _GNU_SOURCE 1
-#define _POSIX_C_SOURCE 200809L
-#ifndef __STDC_LIMIT_MACROS
-#  define __STDC_LIMIT_MACROS 1
-#endif
-
-#include "cbor.h"
-#include "cborjson.h"
-#include "compilersupport_p.h"
-#include "math_support_p.h"
-
-#include <float.h>
-#include <inttypes.h>
-#include <math.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-
-/**
- * \defgroup CborToJson Converting CBOR to JSON
- * \brief Group of functions used to convert CBOR to JSON.
- *
- * This group contains two functions that are can be used to convert one
- * CborValue object to an equivalent JSON representation. This module attempts
- * to follow the recommendations from RFC 7049 section 4.1 "Converting from
- * CBOR to JSON", though it has a few differences. They are noted below.
- *
- * These functions produce a "minified" JSON output, with no spacing,
- * indentation or line breaks. If those are necessary, they need to be applied
- * in a post-processing phase.
- *
- * Note that JSON cannot support all CBOR types with fidelity, so the
- * conversion is usually lossy. For that reason, TinyCBOR supports adding a set
- * of metadata JSON values that can be used by a JSON-to-CBOR converter to
- * restore the original data types.
- *
- * The TinyCBOR library does not provide a way to convert from JSON
- * representation back to encoded form. However, it provides a tool called
- * \c json2cbor which can be used for that purpose. That tool supports the
- * metadata format that these functions may produce.
- *
- * Either of the functions in this section will attempt to convert exactly one
- * CborValue object to JSON. Those functions may return any error documented
- * for the functions for CborParsing. In addition, if the C standard library
- * stream functions return with error, the text conversion will return with
- * error CborErrorIO.
- *
- * These functions also perform UTF-8 validation in CBOR text strings. If they
- * encounter a sequence of bytes that not permitted in UTF-8, they will return
- * CborErrorInvalidUtf8TextString. That includes encoding of surrogate points
- * in UTF-8.
- *
- * \warning The metadata produced by these functions is not guaranteed to
- * remain stable. A future update of TinyCBOR may produce different output for
- * the same input and parsers may be unable to handle them.
- *
- * \sa CborParsing, CborPretty, cbor_parser_init()
- */
-
-/**
- * \addtogroup CborToJson
- * @{
- * <h2 class="groupheader">Conversion limitations</h2>
- *
- * When converting from CBOR to JSON, there may be information loss. This
- * section lists the possible scenarios.
- *
- * \par Number precision:
- * ALL JSON numbers, due to its JavaScript heritage, are IEEE 754
- * double-precision floating point. This means JSON is not capable of
- * representing integers numbers outside the range [-(2<sup>53</sup>)+1,
- * 2<sup>53</sup>-1] and is not capable of representing NaN or infinite. If the
- * CBOR data contains a number outside the valid range, the conversion will
- * lose precision. If the input was NaN or infinite, the result of the
- * conversion will be "null". In addition, the distinction between half-,
- * single- and double-precision is lost.
- *
- * \par
- * If enabled, the original value and original type are stored in the metadata.
- *
- * \par Non-native types:
- * CBOR's type system is richer than JSON's, which means some data values
- * cannot be represented when converted to JSON. The conversion silently turns
- * them into strings: CBOR simple types become "simple(nn)" where \c nn is the
- * simple type's value, with the exception of CBOR undefined, which becomes
- * "undefined", while CBOR byte strings are converted to an Base16, Base64, or
- * Base64url encoding
- *
- * \par
- * If enabled, the original type is stored in the metadata.
- *
- * \par Presence of tags:
- * JSON has no support for tagged values, so by default tags are dropped when
- * converting to JSON. However, if the CborConvertObeyByteStringTags option is
- * active (default), then certain known tags are honored and are used to format
- * the conversion of the tagged byte string to JSON.
- *
- * \par
- * If the CborConvertTagsToObjects option is active, then the tag and the
- * tagged value are converted to to a JSON object. Otherwise, if enabled, the
- * last (innermost) tag is stored in the metadata.
- *
- * \par Non-string keys in maps:
- * JSON requires all Object keys to be strings, while CBOR does not. By
- * default, if a non-string key is found, the conversion fails with error
- * CborErrorJsonObjectKeyNotString. If the CborConvertStringifyMapKeys option
- * is active, then the conversion attempts to create a string representation
- * using CborPretty. Note that the \c json2cbor tool is not able to parse this
- * back to the original form.
- *
- * \par Duplicate keys in maps:
- * Neither JSON nor CBOR allow duplicated keys, but current TinyCBOR does not
- * validate that this is the case. If there are duplicated keys in the input,
- * they will be repeated in the output, which may JSON tools may flag as
- * invalid. In addition to that, if the CborConvertStringifyMapKeys option is
- * active, it is possible that a non-string key in a CBOR map will be converted
- * to a string form that is identical to another key.
- *
- * \par
- * When metadata support is active, the conversion will add extra key-value
- * pairs to the JSON output so it can store the metadata. It is possible that
- * the keys for the metadata clash with existing keys in the JSON map.
- */
-
-extern FILE *open_memstream(char **bufptr, size_t *sizeptr);
-
-enum ConversionStatusFlags {
-    TypeWasNotNative            = 0x100,    /* anything but strings, boolean, null, arrays and maps */
-    TypeWasTagged               = 0x200,
-    NumberPrecisionWasLost      = 0x400,
-    NumberWasNaN                = 0x800,
-    NumberWasInfinite           = 0x1000,
-    NumberWasNegative           = 0x2000,   /* always used with NumberWasInifite or NumberWasTooBig */
-
-    FinalTypeMask               = 0xff
-};
-
-typedef struct ConversionStatus {
-    CborTag lastTag;
-    uint64_t originalNumber;
-    int flags;
-} ConversionStatus;
-
-static CborError value_to_json(FILE *out, CborValue *it, int flags, CborType type, ConversionStatus *status);
-
-static CborError dump_bytestring_base16(char **result, CborValue *it)
-{
-    static const char characters[] = "0123456789abcdef";
-    size_t i;
-    size_t n = 0;
-    uint8_t *buffer;
-    CborError err = cbor_value_calculate_string_length(it, &n);
-    if (err)
-        return err;
-
-    /* a Base16 (hex) output is twice as big as our buffer */
-    buffer = (uint8_t *)malloc(n * 2 + 1);
-    *result = (char *)buffer;
-
-    /* let cbor_value_copy_byte_string know we have an extra byte for the terminating NUL */
-    ++n;
-    err = cbor_value_copy_byte_string(it, buffer + n - 1, &n, it);
-    assert(err == CborNoError);
-
-    for (i = 0; i < n; ++i) {
-        uint8_t byte = buffer[n + i];
-        buffer[2*i]     = characters[byte >> 4];
-        buffer[2*i + 1] = characters[byte & 0xf];
-    }
-    return CborNoError;
-}
-
-static CborError generic_dump_base64(char **result, CborValue *it, const char alphabet[65])
-{
-    size_t n = 0, i;
-    uint8_t *buffer, *out, *in;
-    CborError err = cbor_value_calculate_string_length(it, &n);
-    if (err)
-        return err;
-
-    /* a Base64 output (untruncated) has 4 bytes for every 3 in the input */
-    size_t len = (n + 5) / 3 * 4;
-    out = buffer = (uint8_t *)malloc(len + 1);
-    *result = (char *)buffer;
-
-    /* we read our byte string at the tail end of the buffer
-     * so we can do an in-place conversion while iterating forwards */
-    in = buffer + len - n;
-
-    /* let cbor_value_copy_byte_string know we have an extra byte for the terminating NUL */
-    ++n;
-    err = cbor_value_copy_byte_string(it, in, &n, it);
-    assert(err == CborNoError);
-
-    uint_least32_t val = 0;
-    for (i = 0; n - i >= 3; i += 3) {
-        /* read 3 bytes x 8 bits = 24 bits */
-        if (false) {
-#ifdef __GNUC__
-        } else if (i) {
-            __builtin_memcpy(&val, in + i - 1, sizeof(val));
-            val = cbor_ntohl(val);
-#endif
-        } else {
-            val = (in[i] << 16) | (in[i + 1] << 8) | in[i + 2];
-        }
-
-        /* write 4 chars x 6 bits = 24 bits */
-        *out++ = alphabet[(val >> 18) & 0x3f];
-        *out++ = alphabet[(val >> 12) & 0x3f];
-        *out++ = alphabet[(val >> 6) & 0x3f];
-        *out++ = alphabet[val & 0x3f];
-    }
-
-    /* maybe 1 or 2 bytes left */
-    if (n - i) {
-        /* we can read in[i + 1] even if it's past the end of the string because
-         * we know (by construction) that it's a NUL byte */
-#ifdef __GNUC__
-        uint16_t val16;
-        __builtin_memcpy(&val16, in + i, sizeof(val16));
-        val = cbor_ntohs(val16);
-#else
-        val = (in[i] << 8) | in[i + 1];
-#endif
-        val <<= 8;
-
-        /* the 65th character in the alphabet is our filler: either '=' or '\0' */
-        out[4] = '\0';
-        out[3] = alphabet[64];
-        if (n - i == 2) {
-            /* write the third char in 3 chars x 6 bits = 18 bits */
-            out[2] = alphabet[(val >> 6) & 0x3f];
-        } else {
-            out[2] = alphabet[64];  /* filler */
-        }
-        out[1] = alphabet[(val >> 12) & 0x3f];
-        out[0] = alphabet[(val >> 18) & 0x3f];
-    } else {
-        out[0] = '\0';
-    }
-
-    return CborNoError;
-}
-
-static CborError dump_bytestring_base64(char **result, CborValue *it)
-{
-    static const char alphabet[] = "ABCDEFGH" "IJKLMNOP" "QRSTUVWX" "YZabcdef"
-                                   "ghijklmn" "opqrstuv" "wxyz0123" "456789+/" "=";
-    return generic_dump_base64(result, it, alphabet);
-}
-
-static CborError dump_bytestring_base64url(char **result, CborValue *it)
-{
-    static const char alphabet[] = "ABCDEFGH" "IJKLMNOP" "QRSTUVWX" "YZabcdef"
-                                   "ghijklmn" "opqrstuv" "wxyz0123" "456789-_";
-    return generic_dump_base64(result, it, alphabet);
-}
-
-static CborError add_value_metadata(FILE *out, CborType type, const ConversionStatus *status)
-{
-    int flags = status->flags;
-    if (flags & TypeWasTagged) {
-        /* extract the tagged type, which may be JSON native */
-        type = flags & FinalTypeMask;
-        flags &= ~(FinalTypeMask | TypeWasTagged);
-
-        if (fprintf(out, "\"tag\":\"%" PRIu64 "\"%s", status->lastTag,
-                    flags & ~TypeWasTagged ? "," : "") < 0)
-            return CborErrorIO;
-    }
-
-    if (!flags)
-        return CborNoError;
-
-    /* print at least the type */
-    if (fprintf(out, "\"t\":%d", type) < 0)
-        return CborErrorIO;
-
-    if (flags & NumberWasNaN)
-        if (fprintf(out, ",\"v\":\"nan\"") < 0)
-            return CborErrorIO;
-    if (flags & NumberWasInfinite)
-        if (fprintf(out, ",\"v\":\"%sinf\"", flags & NumberWasNegative ? "-" : "") < 0)
-            return CborErrorIO;
-    if (flags & NumberPrecisionWasLost)
-        if (fprintf(out, ",\"v\":\"%c%" PRIx64 "\"", flags & NumberWasNegative ? '-' : '+',
-                    status->originalNumber) < 0)
-            return CborErrorIO;
-    if (type == CborSimpleType)
-        if (fprintf(out, ",\"v\":%d", (int)status->originalNumber) < 0)
-            return CborErrorIO;
-    return CborNoError;
-}
-
-static CborError find_tagged_type(CborValue *it, CborTag *tag, CborType *type)
-{
-    CborError err = CborNoError;
-    *type = cbor_value_get_type(it);
-    while (*type == CborTagType) {
-        cbor_value_get_tag(it, tag);    /* can't fail */
-        err = cbor_value_advance_fixed(it);
-        if (err)
-            return err;
-
-        *type = cbor_value_get_type(it);
-    }
-    return err;
-}
-
-static CborError tagged_value_to_json(FILE *out, CborValue *it, int flags, ConversionStatus *status)
-{
-    CborTag tag;
-    CborError err;
-
-    if (flags & CborConvertTagsToObjects) {
-        cbor_value_get_tag(it, &tag);       /* can't fail */
-        err = cbor_value_advance_fixed(it);
-        if (err)
-            return err;
-
-        if (fprintf(out, "{\"tag%" PRIu64 "\":", tag) < 0)
-            return CborErrorIO;
-
-        CborType type = cbor_value_get_type(it);
-        err = value_to_json(out, it, flags, type, status);
-        if (err)
-            return err;
-        if (flags & CborConvertAddMetadata && status->flags) {
-            if (fprintf(out, ",\"tag%" PRIu64 "$cbor\":{", tag) < 0 ||
-                    add_value_metadata(out, type, status) != CborNoError ||
-                    fputc('}', out) < 0)
-                return CborErrorIO;
-        }
-        if (fputc('}', out) < 0)
-            return CborErrorIO;
-        status->flags = TypeWasNotNative | CborTagType;
-        return CborNoError;
-    }
-
-    CborType type;
-    err = find_tagged_type(it, &status->lastTag, &type);
-    if (err)
-        return err;
-    tag = status->lastTag;
-
-    /* special handling of byte strings? */
-    if (type == CborByteStringType && (flags & CborConvertByteStringsToBase64Url) == 0 &&
-            (tag == CborNegativeBignumTag || tag == CborExpectedBase16Tag || tag == CborExpectedBase64Tag)) {
-        char *str;
-        char *pre = "";
-
-        if (tag == CborNegativeBignumTag) {
-            pre = "~";
-            err = dump_bytestring_base64url(&str, it);
-        } else if (tag == CborExpectedBase64Tag) {
-            err = dump_bytestring_base64(&str, it);
-        } else { /* tag == CborExpectedBase16Tag */
-            err = dump_bytestring_base16(&str, it);
-        }
-        if (err)
-            return err;
-        err = fprintf(out, "\"%s%s\"", pre, str) < 0 ? CborErrorIO : CborNoError;
-        free(str);
-        status->flags = TypeWasNotNative | TypeWasTagged | CborByteStringType;
-        return err;
-    }
-
-    /* no special handling */
-    err = value_to_json(out, it, flags, type, status);
-    status->flags |= TypeWasTagged | type;
-    return err;
-}
-
-static CborError stringify_map_key(char **key, CborValue *it, int flags, CborType type)
-{
-    (void)flags;    /* unused */
-    (void)type;     /* unused */
-#ifdef WITHOUT_OPEN_MEMSTREAM
-    (void)key;      /* unused */
-    (void)it;       /* unused */
-    return CborErrorJsonNotImplemented;
-#else
-    size_t size;
-
-    FILE *memstream = open_memstream(key, &size);
-    if (memstream == NULL)
-        return CborErrorOutOfMemory;        /* could also be EMFILE, but it's unlikely */
-    CborError err = cbor_value_to_pretty_advance(memstream, it);
-
-    if (unlikely(fclose(memstream) < 0 || *key == NULL))
-        return CborErrorInternalError;
-    return err;
-#endif
-}
-
-static CborError array_to_json(FILE *out, CborValue *it, int flags, ConversionStatus *status)
-{
-    const char *comma = "";
-    while (!cbor_value_at_end(it)) {
-        if (fprintf(out, "%s", comma) < 0)
-            return CborErrorIO;
-        comma = ",";
-
-        CborError err = value_to_json(out, it, flags, cbor_value_get_type(it), status);
-        if (err)
-            return err;
-    }
-    return CborNoError;
-}
-
-static CborError map_to_json(FILE *out, CborValue *it, int flags, ConversionStatus *status)
-{
-    const char *comma = "";
-    CborError err;
-    while (!cbor_value_at_end(it)) {
-        char *key;
-        if (fprintf(out, "%s", comma) < 0)
-            return CborErrorIO;
-        comma = ",";
-
-        CborType keyType = cbor_value_get_type(it);
-        if (likely(keyType == CborTextStringType)) {
-            size_t n = 0;
-            err = cbor_value_dup_text_string(it, &key, &n, it);
-        } else if (flags & CborConvertStringifyMapKeys) {
-            err = stringify_map_key(&key, it, flags, keyType);
-        } else {
-            return CborErrorJsonObjectKeyNotString;
-        }
-        if (err)
-            return err;
-
-        /* first, print the key */
-        if (fprintf(out, "\"%s\":", key) < 0)
-            return CborErrorIO;
-
-        /* then, print the value */
-        CborType valueType = cbor_value_get_type(it);
-        err = value_to_json(out, it, flags, valueType, status);
-
-        /* finally, print any metadata we may have */
-        if (flags & CborConvertAddMetadata) {
-            if (!err && keyType != CborTextStringType) {
-                if (fprintf(out, ",\"%s$keycbordump\":true", key) < 0)
-                    err = CborErrorIO;
-            }
-            if (!err && status->flags) {
-                if (fprintf(out, ",\"%s$cbor\":{", key) < 0 ||
-                        add_value_metadata(out, valueType, status) != CborNoError ||
-                        fputc('}', out) < 0)
-                    err = CborErrorIO;
-            }
-        }
-
-        free(key);
-        if (err)
-            return err;
-    }
-    return CborNoError;
-}
-
-static CborError value_to_json(FILE *out, CborValue *it, int flags, CborType type, ConversionStatus *status)
-{
-    CborError err;
-    status->flags = 0;
-
-    switch (type) {
-    case CborArrayType:
-    case CborMapType: {
-        /* recursive type */
-        CborValue recursed;
-        err = cbor_value_enter_container(it, &recursed);
-        if (err) {
-            it->ptr = recursed.ptr;
-            return err;       /* parse error */
-        }
-        if (fputc(type == CborArrayType ? '[' : '{', out) < 0)
-            return CborErrorIO;
-
-        err = (type == CborArrayType) ?
-                  array_to_json(out, &recursed, flags, status) :
-                  map_to_json(out, &recursed, flags, status);
-        if (err) {
-            it->ptr = recursed.ptr;
-            return err;       /* parse error */
-        }
-
-        if (fputc(type == CborArrayType ? ']' : '}', out) < 0)
-            return CborErrorIO;
-        err = cbor_value_leave_container(it, &recursed);
-        if (err)
-            return err;       /* parse error */
-
-        status->flags = 0;    /* reset, there are never conversion errors for us */
-        return CborNoError;
-    }
-
-    case CborIntegerType: {
-        double num;     /* JS numbers are IEEE double precision */
-        uint64_t val;
-        cbor_value_get_raw_integer(it, &val);    /* can't fail */
-        num = (double)val;
-
-        if (cbor_value_is_negative_integer(it)) {
-            num = -num - 1;                     /* convert to negative */
-            if ((uint64_t)(-num - 1) != val) {
-                status->flags = NumberPrecisionWasLost | NumberWasNegative;
-                status->originalNumber = val;
-            }
-        } else {
-            if ((uint64_t)num != val) {
-                status->flags = NumberPrecisionWasLost;
-                status->originalNumber = val;
-            }
-        }
-        if (fprintf(out, "%.0f", num) < 0)  /* this number has no fraction, so no decimal points please */
-            return CborErrorIO;
-        break;
-    }
-
-    case CborByteStringType:
-    case CborTextStringType: {
-        char *str;
-        if (type == CborByteStringType) {
-            err = dump_bytestring_base64url(&str, it);
-            status->flags = TypeWasNotNative;
-        } else {
-            size_t n = 0;
-            err = cbor_value_dup_text_string(it, &str, &n, it);
-        }
-        if (err)
-            return err;
-        err = (fprintf(out, "\"%s\"", str) < 0) ? CborErrorIO : CborNoError;
-        free(str);
-        return err;
-    }
-
-    case CborTagType:
-        return tagged_value_to_json(out, it, flags, status);
-
-    case CborSimpleType: {
-        uint8_t simple_type;
-        cbor_value_get_simple_type(it, &simple_type);  /* can't fail */
-        status->flags = TypeWasNotNative;
-        status->originalNumber = simple_type;
-        if (fprintf(out, "\"simple(%" PRIu8 ")\"", simple_type) < 0)
-            return CborErrorIO;
-        break;
-    }
-
-    case CborNullType:
-        if (fprintf(out, "null") < 0)
-            return CborErrorIO;
-        break;
-
-    case CborUndefinedType:
-        status->flags = TypeWasNotNative;
-        if (fprintf(out, "\"undefined\"") < 0)
-            return CborErrorIO;
-        break;
-
-    case CborBooleanType: {
-        bool val;
-        cbor_value_get_boolean(it, &val);       /* can't fail */
-        if (fprintf(out, val ? "true" : "false") < 0)
-            return CborErrorIO;
-        break;
-    }
-
-    case CborDoubleType: {
-        double val;
-        if (false) {
-            float f;
-    case CborFloatType:
-            status->flags = TypeWasNotNative;
-            cbor_value_get_float(it, &f);
-            val = f;
-        } else if (false) {
-            uint16_t f16;
-    case CborHalfFloatType:
-            status->flags = TypeWasNotNative;
-            cbor_value_get_half_float(it, &f16);
-            val = decode_half(f16);
-        } else {
-            cbor_value_get_double(it, &val);
-        }
-
-        int r = fpclassify(val);
-        if (r == FP_NAN || r == FP_INFINITE) {
-            if (fprintf(out, "null") < 0)
-                return CborErrorIO;
-            status->flags |= r == FP_NAN ? NumberWasNaN :
-                                           NumberWasInfinite | (val < 0 ? NumberWasNegative : 0);
-        } else {
-            uint64_t ival = (uint64_t)fabs(val);
-            if ((double)ival == fabs(val)) {
-                /* print as integer so we get the full precision */
-                r = fprintf(out, "%s%" PRIu64, val < 0 ? "-" : "", ival);
-                status->flags |= TypeWasNotNative;   /* mark this integer number as a double */
-            } else {
-                /* this number is definitely not a 64-bit integer */
-                r = fprintf(out, "%." DBL_DECIMAL_DIG_STR "g", val);
-            }
-            if (r < 0)
-                return CborErrorIO;
-        }
-        break;
-    }
-
-    case CborInvalidType:
-        return CborErrorUnknownType;
-    }
-
-    return cbor_value_advance_fixed(it);
-}
-
-/**
- * \enum CborToJsonFlags
- * The CborToJsonFlags enum contains flags that control the conversion of CBOR to JSON.
- *
- * \value CborConvertAddMetadata        Adds metadata to facilitate restoration of the original CBOR data.
- * \value CborConvertTagsToObjects      Converts CBOR tags to JSON objects
- * \value CborConvertIgnoreTags         (default) Ignore CBOR tags, except for byte strings
- * \value CborConvertObeyByteStringTags (default) Honor formatting of CBOR byte strings if so tagged
- * \value CborConvertByteStringsToBase64Url Force the conversion of all CBOR byte strings to Base64url encoding, despite any tags
- * \value CborConvertRequireMapStringKeys (default) Require CBOR map keys to be strings, failing the conversion if they are not
- * \value CborConvertStringifyMapKeys   Convert non-string keys in CBOR maps to a string form
- * \value CborConvertDefaultFlags       Default conversion flags.
- */
-
-/**
- * \fn CborError cbor_value_to_json(FILE *out, const CborValue *value, int flags)
- *
- * Converts the current CBOR type pointed by \a value to JSON and writes that
- * to the \a out stream. If an error occurs, this function returns an error
- * code similar to CborParsing. The \a flags parameter indicates one of the
- * flags from CborToJsonFlags that control the conversion.
- *
- * \sa cbor_value_to_json_advance(), cbor_value_to_pretty()
- */
-
-/**
- * Converts the current CBOR type pointed by \a value to JSON and writes that
- * to the \a out stream. If an error occurs, this function returns an error
- * code similar to CborParsing. The \a flags parameter indicates one of the
- * flags from CborToJsonFlags that control the conversion.
- *
- * If no error ocurred, this function advances \a value to the next element.
- *
- * \sa cbor_value_to_json(), cbor_value_to_pretty_advance()
- */
-CborError cbor_value_to_json_advance(FILE *out, CborValue *value, int flags)
-{
-    ConversionStatus status;
-    return value_to_json(out, value, flags, cbor_value_get_type(value), &status);
-}
-
-/** @} */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/tinycbor/src/open_memstream.c
----------------------------------------------------------------------
diff --git a/libs/tinycbor/src/open_memstream.c b/libs/tinycbor/src/open_memstream.c
deleted file mode 100644
index eaa53e5..0000000
--- a/libs/tinycbor/src/open_memstream.c
+++ /dev/null
@@ -1,117 +0,0 @@
-/****************************************************************************
-**
-** Copyright (C) 2015 Intel Corporation
-**
-** Permission is hereby granted, free of charge, to any person obtaining a copy
-** of this software and associated documentation files (the "Software"), to deal
-** in the Software without restriction, including without limitation the rights
-** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-** copies of the Software, and to permit persons to whom the Software is
-** furnished to do so, subject to the following conditions:
-**
-** The above copyright notice and this permission notice shall be included in
-** all copies or substantial portions of the Software.
-**
-** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-** THE SOFTWARE.
-**
-****************************************************************************/
-
-#define _BSD_SOURCE 1
-#define _DEFAULT_SOURCE 1
-#define _GNU_SOURCE 1
-
-#ifndef WITHOUT_OPEN_MEMSTREAM
-
-#include <sys/types.h>
-#include <errno.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#if defined(__unix__) || defined(__APPLE__)
-#  include <unistd.h>
-#endif
-#ifdef __APPLE__
-typedef int RetType;
-typedef int LenType;
-#elif __GLIBC__
-typedef ssize_t RetType;
-typedef size_t LenType;
-#else
-#  error "Cannot implement open_memstream!"
-#endif
-
-#include "compilersupport_p.h"
-
-struct Buffer
-{
-    char **ptr;
-    size_t *len;
-    size_t alloc;
-};
-
-static RetType write_to_buffer(void *cookie, const char *data, LenType len)
-{
-    struct Buffer *b = (struct Buffer *)cookie;
-    char *ptr = *b->ptr;
-    size_t newsize;
-
-    errno = EFBIG;
-    if (unlikely(add_check_overflow(*b->len, len, &newsize)))
-        return -1;
-
-    if (newsize > b->alloc) {
-        // make room
-        size_t newalloc = newsize + newsize / 2 + 1;    // give 50% more room
-        ptr = realloc(ptr, newalloc);
-        if (ptr == NULL)
-            return -1;
-        b->alloc = newalloc;
-        *b->ptr = ptr;
-    }
-
-    memcpy(ptr + *b->len, data, len);
-    *b->len = newsize;
-    return len;
-}
-
-static int close_buffer(void *cookie)
-{
-    struct Buffer *b = (struct Buffer *)cookie;
-    if (*b->ptr)
-        (*b->ptr)[*b->len] = '\0';
-    free(b);
-    return 0;
-}
-
-FILE *open_memstream(char **bufptr, size_t *lenptr)
-{
-    struct Buffer *b = (struct Buffer *)malloc(sizeof(struct Buffer));
-    if (b == NULL)
-        return NULL;
-    b->alloc = 0;
-    b->len = lenptr;
-    b->ptr = bufptr;
-    *bufptr = NULL;
-    *lenptr = 0;
-
-#ifdef __APPLE__
-    return funopen(b, NULL, write_to_buffer, NULL, close_buffer);
-#elif __GLIBC__
-    static const cookie_io_functions_t vtable = {
-        NULL,
-        write_to_buffer,
-        NULL,
-        close_buffer
-    };
-    return fopencookie(b, "w", vtable);
-#endif
-}
-
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/util/include/util/base64.h
----------------------------------------------------------------------
diff --git a/libs/util/include/util/base64.h b/libs/util/include/util/base64.h
deleted file mode 100644
index 8e0c045..0000000
--- a/libs/util/include/util/base64.h
+++ /dev/null
@@ -1,32 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 __UTIL_BASE64_H
-#define __UTIL_BASE64_H
-
-#include <stdint.h>
-#include <string.h>
-
-int base64_encode(const void *, int, char *, uint8_t);
-int base64_decode(const char *, void *buf);
-int base64_pad(char *, int);
-int base64_decode_len(const char *str);
-
-#define BASE64_ENCODE_SIZE(__size) ((((__size) * 4) / 3) + 4)
-
-#endif /* __UTIL_BASE64_H__ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/util/include/util/crc16.h
----------------------------------------------------------------------
diff --git a/libs/util/include/util/crc16.h b/libs/util/include/util/crc16.h
deleted file mode 100644
index b9b965f..0000000
--- a/libs/util/include/util/crc16.h
+++ /dev/null
@@ -1,36 +0,0 @@
-/*	
- * Copyright 2001-2010 Georges Menie (www.menie.org)
- * 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 the University of California, Berkeley 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 REGENTS 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 REGENTS AND 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.
- */
-
-#ifndef _CRC16_H_
-#define _CRC16_H_
-
-#include <inttypes.h>
-
-#define CRC16_INITIAL_CRC       0       /* what to seed crc16 with */
-unsigned short crc16_ccitt(uint16_t initial_crc, const void *buf, int len);
-
-#endif /* _CRC16_H_ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/util/include/util/crc8.h
----------------------------------------------------------------------
diff --git a/libs/util/include/util/crc8.h b/libs/util/include/util/crc8.h
deleted file mode 100644
index 336acca..0000000
--- a/libs/util/include/util/crc8.h
+++ /dev/null
@@ -1,32 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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.
- */
-
-/*
- * CRC8-CCITT, with normal polynomial; 0x07.
- */
-
-#ifndef _UTIL_CRC8_H_
-#define _UTIL_CRC8_H_
-
-#include <inttypes.h>
-
-uint8_t crc8_init(void);
-uint8_t crc8_calc(uint8_t val, void *buf, int cnt);
-
-#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/util/include/util/hex.h
----------------------------------------------------------------------
diff --git a/libs/util/include/util/hex.h b/libs/util/include/util/hex.h
deleted file mode 100644
index 1e9d8c8..0000000
--- a/libs/util/include/util/hex.h
+++ /dev/null
@@ -1,25 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 _UTIL_HEX_H_
-#define _UTIL_HEX_H_
-
-char *hex_format(void *src_v, int src_len, char *dst, int dst_len);
-int hex_parse(char *src, int src_len, void *dst_v, int dst_len);
-
-#endif /* _UTIL_HEX_H_ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/util/include/util/tpq.h
----------------------------------------------------------------------
diff --git a/libs/util/include/util/tpq.h b/libs/util/include/util/tpq.h
deleted file mode 100644
index 9e2b8a5..0000000
--- a/libs/util/include/util/tpq.h
+++ /dev/null
@@ -1,67 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 __UTIL_TPQ_H__ 
-#define __UTIL_TPQ_H__
-
-#include <os/queue.h>
-#include <os/os_eventq.h>
-
-/* A task packet queue element */
-struct tpq_elem {
-    STAILQ_ENTRY(tpq_elem) tpq_next;
-};
-
-/* The task packet queue object */
-struct tpq
-{
-    STAILQ_HEAD(, tpq_elem) tpq_head;
-    struct os_event tpq_ev;
-};
-
-/**
- * Put an element on a task packet queue and post an event to an event queue. 
- * 
- * @param evq   Pointer to event queue
- * @param tpq   Pointer to task packet queue
- * @param elem  Pointer to element to enqueue
- */
-void tpq_put(struct os_eventq *evq, struct tpq *tpq, struct tpq_elem *elem);
-
-/**
- * Retrieve an element from a task packet queue. This removes the element at 
- * the head of the queue. 
- * 
- * @param head 
- * 
- * @return struct tpq_elem* 
- */
-struct tpq_elem *tpq_get(struct tpq *tpq);
-
-/**
- * Initialize a task packet queue 
- * 
- * @param tpq Pointer to task packet queue
- * @param ev_type Type of event.
- * @param ev_arg Argument of event
- * 
- * @return int 
- */
-void tpq_init(struct tpq *tpq, uint8_t ev_type, void *ev_arg);
-
-#endif /* __UTIL_TPQ_H__ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/util/pkg.yml
----------------------------------------------------------------------
diff --git a/libs/util/pkg.yml b/libs/util/pkg.yml
index b922830..9957805 100644
--- a/libs/util/pkg.yml
+++ b/libs/util/pkg.yml
@@ -27,4 +27,4 @@ pkg.keywords:
 
 pkg.deps:
     - hw/hal
-    - libs/os
+    - kernel/os

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/util/src/base64.c
----------------------------------------------------------------------
diff --git a/libs/util/src/base64.c b/libs/util/src/base64.c
deleted file mode 100644
index 685135e..0000000
--- a/libs/util/src/base64.c
+++ /dev/null
@@ -1,181 +0,0 @@
-/* 
- * This file is based on roken from the FreeBSD source.  It has been modified
- * to not use malloc() and instead expect static buffers, and tabs have been 
- * replaced with spaces.  Also, instead of strlen() on the resulting string, 
- * pointer arithmitic is done, as p represents the end of the buffer.
- */
-
-/* 
- * Copyright (c) 1995-2001 Kungliga Tekniska H�gskolan
- * (Royal Institute of Technology, Stockholm, Sweden).
- * 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.
- *
- * 3. Neither the name of the Institute 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 INSTITUTE 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 INSTITUTE 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 <stdlib.h>
-#include <string.h>
-
-#include <stdio.h>
-
-#include <util/base64.h>
-
-static const char base64_chars[] = 
-    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
-
-static int 
-pos(char c)
-{
-    const char *p;
-    for (p = base64_chars; *p; p++)
-        if (*p == c)
-            return p - base64_chars;
-    return -1;
-}
-
-int 
-base64_encode(const void *data, int size, char *s, uint8_t should_pad)
-{
-    char *p;
-    int i;
-    int c;
-    const unsigned char *q;
-    char *last;
-    int diff;
-
-    p = s;
-
-    q = (const unsigned char *) data;
-    last = NULL;
-    i = 0;
-    while (i < size) {
-        c = q[i++];
-        c *= 256;
-        if (i < size)
-            c += q[i];
-        i++;
-        c *= 256;
-        if (i < size)
-            c += q[i];
-        i++;
-        p[0] = base64_chars[(c & 0x00fc0000) >> 18];
-        p[1] = base64_chars[(c & 0x0003f000) >> 12];
-        p[2] = base64_chars[(c & 0x00000fc0) >> 6];
-        p[3] = base64_chars[(c & 0x0000003f) >> 0];
-        last = p;
-        p += 4;
-    }
-
-    if (last) {
-        diff = i - size;
-        if (diff > 0) {
-            if (should_pad) {
-                memset(last + (4 - diff), '=', diff);
-            } else {
-                p = last + (4 - diff);
-            }
-        }
-    } 
-
-    *p = 0;
-
-    return (p - s);
-}
-
-int 
-base64_pad(char *buf, int len)
-{
-    int remainder;
-
-    remainder = len % 4;
-    if (remainder == 0) {
-        return (0);
-    }
-
-    memset(buf, '=', 4 - remainder);
-
-    return (4 - remainder);
-}
-
-#define DECODE_ERROR -1
-
-static unsigned int
-token_decode(const char *token)
-{
-    int i;
-    unsigned int val = 0;
-    int marker = 0;
-    if (strlen(token) < 4)
-        return DECODE_ERROR;
-    for (i = 0; i < 4; i++) {
-        val *= 64;
-        if (token[i] == '=')
-            marker++;
-        else if (marker > 0)
-            return DECODE_ERROR;
-        else
-            val += pos(token[i]);
-    }
-    if (marker > 2)
-        return DECODE_ERROR;
-    return (marker << 24) | val;
-}
-
-int 
-base64_decode(const char *str, void *data)
-{
-    const char *p;
-    unsigned char *q;
-
-    q = data;
-    for (p = str; *p && (*p == '=' || strchr(base64_chars, *p)); p += 4) {
-        unsigned int val = token_decode(p);
-        unsigned int marker = (val >> 24) & 0xff;
-        if (val == DECODE_ERROR)
-            return -1;
-        *q++ = (val >> 16) & 0xff;
-        if (marker < 2)
-            *q++ = (val >> 8) & 0xff;
-        if (marker < 1)
-            *q++ = val & 0xff;
-    }
-    return q - (unsigned char *) data;
-}
-
-
-int
-base64_decode_len(const char *str)
-{
-    int len;
-
-    len = strlen(str);
-    while (len && str[len - 1] == '=') {
-        len--;
-    }
-    return len * 3 / 4;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/util/src/crc16.c
----------------------------------------------------------------------
diff --git a/libs/util/src/crc16.c b/libs/util/src/crc16.c
deleted file mode 100644
index 625d690..0000000
--- a/libs/util/src/crc16.c
+++ /dev/null
@@ -1,83 +0,0 @@
-/*    
- * Copyright 2001-2010 Georges Menie (www.menie.org)
- * 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 the University of California, Berkeley 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 REGENTS 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 REGENTS AND 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 <inttypes.h>
-#include "util/crc16.h"
-
-/* CRC16 implementation acording to CCITT standards */
-
-static const uint16_t crc16tab[256]= {
-    0x0000,0x1021,0x2042,0x3063,0x4084,0x50a5,0x60c6,0x70e7,
-    0x8108,0x9129,0xa14a,0xb16b,0xc18c,0xd1ad,0xe1ce,0xf1ef,
-    0x1231,0x0210,0x3273,0x2252,0x52b5,0x4294,0x72f7,0x62d6,
-    0x9339,0x8318,0xb37b,0xa35a,0xd3bd,0xc39c,0xf3ff,0xe3de,
-    0x2462,0x3443,0x0420,0x1401,0x64e6,0x74c7,0x44a4,0x5485,
-    0xa56a,0xb54b,0x8528,0x9509,0xe5ee,0xf5cf,0xc5ac,0xd58d,
-    0x3653,0x2672,0x1611,0x0630,0x76d7,0x66f6,0x5695,0x46b4,
-    0xb75b,0xa77a,0x9719,0x8738,0xf7df,0xe7fe,0xd79d,0xc7bc,
-    0x48c4,0x58e5,0x6886,0x78a7,0x0840,0x1861,0x2802,0x3823,
-    0xc9cc,0xd9ed,0xe98e,0xf9af,0x8948,0x9969,0xa90a,0xb92b,
-    0x5af5,0x4ad4,0x7ab7,0x6a96,0x1a71,0x0a50,0x3a33,0x2a12,
-    0xdbfd,0xcbdc,0xfbbf,0xeb9e,0x9b79,0x8b58,0xbb3b,0xab1a,
-    0x6ca6,0x7c87,0x4ce4,0x5cc5,0x2c22,0x3c03,0x0c60,0x1c41,
-    0xedae,0xfd8f,0xcdec,0xddcd,0xad2a,0xbd0b,0x8d68,0x9d49,
-    0x7e97,0x6eb6,0x5ed5,0x4ef4,0x3e13,0x2e32,0x1e51,0x0e70,
-    0xff9f,0xefbe,0xdfdd,0xcffc,0xbf1b,0xaf3a,0x9f59,0x8f78,
-    0x9188,0x81a9,0xb1ca,0xa1eb,0xd10c,0xc12d,0xf14e,0xe16f,
-    0x1080,0x00a1,0x30c2,0x20e3,0x5004,0x4025,0x7046,0x6067,
-    0x83b9,0x9398,0xa3fb,0xb3da,0xc33d,0xd31c,0xe37f,0xf35e,
-    0x02b1,0x1290,0x22f3,0x32d2,0x4235,0x5214,0x6277,0x7256,
-    0xb5ea,0xa5cb,0x95a8,0x8589,0xf56e,0xe54f,0xd52c,0xc50d,
-    0x34e2,0x24c3,0x14a0,0x0481,0x7466,0x6447,0x5424,0x4405,
-    0xa7db,0xb7fa,0x8799,0x97b8,0xe75f,0xf77e,0xc71d,0xd73c,
-    0x26d3,0x36f2,0x0691,0x16b0,0x6657,0x7676,0x4615,0x5634,
-    0xd94c,0xc96d,0xf90e,0xe92f,0x99c8,0x89e9,0xb98a,0xa9ab,
-    0x5844,0x4865,0x7806,0x6827,0x18c0,0x08e1,0x3882,0x28a3,
-    0xcb7d,0xdb5c,0xeb3f,0xfb1e,0x8bf9,0x9bd8,0xabbb,0xbb9a,
-    0x4a75,0x5a54,0x6a37,0x7a16,0x0af1,0x1ad0,0x2ab3,0x3a92,
-    0xfd2e,0xed0f,0xdd6c,0xcd4d,0xbdaa,0xad8b,0x9de8,0x8dc9,
-    0x7c26,0x6c07,0x5c64,0x4c45,0x3ca2,0x2c83,0x1ce0,0x0cc1,
-    0xef1f,0xff3e,0xcf5d,0xdf7c,0xaf9b,0xbfba,0x8fd9,0x9ff8,
-    0x6e17,0x7e36,0x4e55,0x5e74,0x2e93,0x3eb2,0x0ed1,0x1ef0
-};
-  
-uint16_t
-crc16_ccitt(uint16_t initial_crc, const void *buf, int len)
-{
-    const uint8_t *ptr;
-    uint16_t crc;
-    int counter;
-
-    crc = initial_crc;
-    ptr = buf;
-
-    for (counter = 0; counter < len; counter++) {
-        crc = (crc<<8) ^ crc16tab[((crc>>8) ^ *ptr++)&0x00FF];
-    }
-
-    return crc;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/util/src/crc8.c
----------------------------------------------------------------------
diff --git a/libs/util/src/crc8.c b/libs/util/src/crc8.c
deleted file mode 100644
index 389e43a..0000000
--- a/libs/util/src/crc8.c
+++ /dev/null
@@ -1,74 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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.
- */
-
-/*
- * Table computation:
- *
- * void
- * gen_small_table(uint8_t poly)
- * {
- *      int i;
- *	int j;
- *	uint8_t curr;
- *
- *	for (i = 0; i < 16; i++) {
- *		curr = i;
- *
- *		for (j = 0; j < 8; j++)  {
- *			if ((curr & 0x80) != 0) {
- *				curr = (curr << 1) ^ poly;
- *			} else {
- *				curr <<= 1;
- *			}
- *		}
- *
- *		small_table[i] = curr;
- *
- *		printf("0x%x, ", small_table[i]);
- *	}
- *	printf("\n");
- *}
- */
-
-#include "util/crc8.h"
-
-static uint8_t crc8_small_table[16] = {
-    0x00, 0x07, 0x0e, 0x09, 0x1c, 0x1b, 0x12, 0x15,
-    0x38, 0x3f, 0x36, 0x31, 0x24, 0x23, 0x2a, 0x2d
-};
-
-uint8_t
-crc8_init(void)
-{
-    return 0xff;
-}
-
-uint8_t
-crc8_calc(uint8_t val, void *buf, int cnt)
-{
-	int i;
-	uint8_t *p = buf;
-
-	for (i = 0; i < cnt; i++) {
-		val ^= p[i];
-		val = (val << 4) ^ crc8_small_table[val >> 4];
-		val = (val << 4) ^ crc8_small_table[val >> 4];
-	}
-	return val;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/util/src/hex.c
----------------------------------------------------------------------
diff --git a/libs/util/src/hex.c b/libs/util/src/hex.c
deleted file mode 100644
index 153f974..0000000
--- a/libs/util/src/hex.c
+++ /dev/null
@@ -1,101 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include <inttypes.h>
-#include <ctype.h>
-#include <stddef.h>
-
-#include "util/hex.h"
-
-static const char hex_bytes[] = "0123456789abcdef";
-
-/*
- * Turn byte array into a printable array. I.e. "\x01" -> "01"
- *
- * @param src_v		Data to convert
- * @param src_len	Number of bytes of input
- * @param dst		String where to place the results
- * @param dst_len	Size of the target string
- *
- * @return		Pointer to 'dst' if successful; NULL on failure
- */
-char *
-hex_format(void *src_v, int src_len, char *dst, int dst_len)
-{
-    int i;
-    uint8_t *src = (uint8_t *)src_v;
-    char *tgt = dst;
-
-    if (dst_len <= src_len * 2) {
-        return NULL;
-    }
-    for (i = 0; i < src_len; i++) {
-        tgt[0] = hex_bytes[(src[i] >> 4) & 0xf];
-        tgt[1] = hex_bytes[src[i] & 0xf];
-        tgt += 2;
-        dst_len -= 2;
-    }
-    *tgt = '\0';
-    return dst;
-}
-
-/*
- * Turn string of hex decimals into a byte array. I.e. "01" -> "\x01
- *
- * @param src		String to convert
- * @param src_len	Number of bytes in input string
- * @param dst_v		Memory location to place the result
- * @param dst_len	Amount of space for the result
- *
- * @return		-1 on failure; number of bytes of input
- */
-int
-hex_parse(char *src, int src_len, void *dst_v, int dst_len)
-{
-    int i;
-    uint8_t *dst = (uint8_t *)dst_v;
-    char c;
-
-    if (src_len & 0x1) {
-        return -1;
-    }
-    if (dst_len * 2 < src_len) {
-        return -1;
-    }
-    for (i = 0; i < src_len; i++, src++) {
-        c = *src;
-        if (isdigit(c)) {
-            c -= '0';
-        } else if (c >= 'a' && c <= 'f') {
-            c -= ('a' - 10);
-        } else if (c >= 'A' && c <= 'F') {
-            c -= ('A' - 10);
-        } else {
-            return -1;
-        }
-        if (i & 1) {
-            *dst |= c;
-            dst++;
-            dst_len--;
-        } else {
-            *dst = c << 4;
-        }
-    }
-    return src_len >> 1;
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/libs/util/src/tpq.c
----------------------------------------------------------------------
diff --git a/libs/util/src/tpq.c b/libs/util/src/tpq.c
deleted file mode 100644
index 71c35b6..0000000
--- a/libs/util/src/tpq.c
+++ /dev/null
@@ -1,88 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-#include "os/os.h"
-#include "util/tpq.h"
-
-/**
- * Put an element on a task packet queue and post an event to an event queue. 
- * 
- * @param evq   Pointer to event queue
- * @param tpq   Pointer to task packet queue
- * @param elem  Pointer to element to enqueue
- */
-void
-tpq_put(struct os_eventq *evq, struct tpq *tpq, struct tpq_elem *elem)
-{
-    os_sr_t sr;
-
-    OS_ENTER_CRITICAL(sr);
-    STAILQ_INSERT_TAIL(&tpq->tpq_head, elem, tpq_next);
-    OS_EXIT_CRITICAL(sr);
-    os_eventq_put(evq, &tpq->tpq_ev);
-}
-
-/**
- * Retrieve an element from a task packet queue. This removes the element at 
- * the head of the queue. 
- * 
- * @param head 
- * 
- * @return struct tpq_elem* 
- */
-struct tpq_elem *
-tpq_get(struct tpq *tpq)
-{
-    os_sr_t sr;
-    struct tpq_elem *elem;
-
-    OS_ENTER_CRITICAL(sr);
-    elem = STAILQ_FIRST(&tpq->tpq_head);
-    if (elem) {
-        STAILQ_REMOVE_HEAD(&tpq->tpq_head, tpq_next);
-    }
-    OS_EXIT_CRITICAL(sr);
-
-    return elem;
-}
-
-/**
- * Initialize a task packet queue 
- * 
- * @param tpq Pointer to task packet queue
- * @param ev_type Type of event.
- * @param ev_arg Argument of event
- * 
- * @return int 
- */
-void
-tpq_init(struct tpq *tpq, uint8_t ev_type, void *ev_arg)
-{
-    struct os_event *ev;
-
-    /* Initialize the task packet queue */
-    STAILQ_INIT(&tpq->tpq_head);
-
-    /* Initial task packet queue event */
-    ev = &tpq->tpq_ev;
-    ev->ev_arg = ev_arg;
-    ev->ev_type = ev_type;
-    ev->ev_queued = 0;
-    STAILQ_NEXT(ev, ev_next) = NULL;
-}
-

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/net/ip/inet_def_service/pkg.yml
----------------------------------------------------------------------
diff --git a/net/ip/inet_def_service/pkg.yml b/net/ip/inet_def_service/pkg.yml
index 061d0cb..2780694 100644
--- a/net/ip/inet_def_service/pkg.yml
+++ b/net/ip/inet_def_service/pkg.yml
@@ -27,8 +27,8 @@ pkg.keywords:
     - test
 
 pkg.deps:
-    - sys/mn_socket
-    - libs/os
+    - net/ip/mn_socket
+    - kernel/os
     - libs/util
 
 pkg.reqs:

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/net/ip/mn_socket/include/mn_socket/arch/sim/native_sock.h
----------------------------------------------------------------------
diff --git a/net/ip/mn_socket/include/mn_socket/arch/sim/native_sock.h b/net/ip/mn_socket/include/mn_socket/arch/sim/native_sock.h
new file mode 100644
index 0000000..66e8016
--- /dev/null
+++ b/net/ip/mn_socket/include/mn_socket/arch/sim/native_sock.h
@@ -0,0 +1,25 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 __NATIVE_SOCK_H_
+#define __NATIVE_SOCK_H_
+
+int native_sock_init(void);
+
+#endif /* __NATIVE_SOCK_H_ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/net/ip/mn_socket/include/mn_socket/mn_socket.h
----------------------------------------------------------------------
diff --git a/net/ip/mn_socket/include/mn_socket/mn_socket.h b/net/ip/mn_socket/include/mn_socket/mn_socket.h
new file mode 100644
index 0000000..47c54fb
--- /dev/null
+++ b/net/ip/mn_socket/include/mn_socket/mn_socket.h
@@ -0,0 +1,218 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 __SYS_MN_SOCKET_H_
+#define __SYS_MN_SOCKET_H_
+
+#include <inttypes.h>
+
+/*
+ * Address/protocol family.
+ */
+#define MN_AF_INET              4
+#define MN_PF_INET              MN_AF_INET
+#define MN_AF_INET6             6
+#define MN_PF_INET6             MN_AF_INET6
+
+/*
+ * Socket types
+ */
+#define MN_SOCK_STREAM          1
+#define MN_SOCK_DGRAM           2
+
+/*
+ * Error codes from mn_socket interface.
+ */
+#define MN_EAFNOSUPPORT         1
+#define MN_EPROTONOSUPPORT      2
+#define MN_ENOBUFS              3
+#define MN_EINVAL               4
+#define MN_ENOTCONN             5
+#define MN_ECONNABORTED         6
+#define MN_EDESTADDRREQ         7
+#define MN_EADDRINUSE           8
+#define MN_ETIMEDOUT            9
+#define MN_EAGAIN               10
+#define MN_EUNKNOWN             11
+#define MN_EADDRNOTAVAIL        12
+
+/*
+ * Multicast macros
+ */
+#define MN_IN_MULTICAST(a)                                              \
+    ((((uint32_t)(a)) & 0xf0000000) == 0xe0000000)
+
+#define MN_IN6_IS_ADDR_MULTICAST(a)                                     \
+    ((a)->s_addr[0] == 0xff)
+
+struct mn_socket;
+struct mn_socket_ops;
+struct mn_sock_cb;
+struct os_mbuf;
+
+struct mn_socket {
+    const union mn_socket_cb *ms_cbs;          /* filled in by user */
+    void *ms_cb_arg;                           /* filled in by user */
+    const struct mn_socket_ops *ms_ops;        /* filled in by mn_socket */
+};
+
+/*
+ * Callbacks. Socket callbacks are for sockets which exchange
+ * data. Listen callback is for TCP listen sockets.
+ */
+union mn_socket_cb {
+    struct {
+        void (*readable)(void *cb_arg, int err);
+        void (*writable)(void *cb_arg, int err);
+    } socket;
+    struct {
+        int (*newconn)(void *cb_arg, struct mn_socket *new);
+    } listen;
+};
+
+struct mn_sockaddr {
+    uint8_t msa_len;
+    uint8_t msa_family;
+    char    msa_data[2];
+};
+
+struct mn_in_addr {
+    uint32_t s_addr;
+};
+
+struct mn_sockaddr_in {
+    uint8_t msin_len;
+    uint8_t msin_family;
+    uint16_t msin_port;
+    struct mn_in_addr msin_addr;
+};
+
+struct mn_in6_addr {
+    uint8_t s_addr[16];
+};
+
+struct mn_sockaddr_in6 {
+    uint8_t msin6_len;
+    uint8_t msin6_family;
+    uint16_t msin6_port;
+    uint32_t msin6_flowinfo;
+    struct mn_in6_addr msin6_addr;
+    uint32_t msin6_scope_id;
+};
+
+extern const uint32_t nm_in6addr_any[4];
+
+/*
+ * Structure for multicast join/leave
+ */
+struct mn_mreq {
+    uint8_t mm_idx;			/* interface index */
+    uint8_t mm_family;			/* address family */
+    union {
+        struct mn_in_addr v4;
+        struct mn_in6_addr v6;
+    } mm_addr;
+};
+
+#define MN_SO_LEVEL                     0xfe
+
+#define MN_MCAST_JOIN_GROUP             1
+#define MN_MCAST_LEAVE_GROUP            2
+#define MN_MCAST_IF                     3
+
+/*
+ * Socket calls.
+ *
+ * mn_connect() for TCP is asynchronous. Once connection has been established,
+ * socket callback (*writable) will be called.
+ *
+ * mn_sendto() is asynchronous as well. If it fails due to buffer shortage,
+ * socket provider should call (*writable) when more data can be sent.
+ *
+ * mn_recvfrom() returns immediatelly if no data is available. If data arrives,
+ * the callback (*readable) will be called. Once that happens, owner of the
+ * socket should keep calling mn_recvfrom() until it has drained all the
+ * data from the socket.
+ *
+ * If remote end closes the socket, socket callback (*readable) will be
+ * called.
+ */
+int mn_socket(struct mn_socket **, uint8_t domain, uint8_t type, uint8_t proto);
+int mn_bind(struct mn_socket *, struct mn_sockaddr *);
+int mn_connect(struct mn_socket *, struct mn_sockaddr *);
+int mn_listen(struct mn_socket *, uint8_t qlen);
+
+int mn_recvfrom(struct mn_socket *, struct os_mbuf **,
+  struct mn_sockaddr *from);
+int mn_sendto(struct mn_socket *, struct os_mbuf *, struct mn_sockaddr *to);
+
+int mn_getsockopt(struct mn_socket *, uint8_t level, uint8_t optname,
+  void *optval);
+int mn_setsockopt(struct mn_socket *, uint8_t level, uint8_t optname,
+  void *optval);
+
+int mn_getsockname(struct mn_socket *, struct mn_sockaddr *);
+int mn_getpeername(struct mn_socket *, struct mn_sockaddr *);
+
+int mn_close(struct mn_socket *);
+
+#define mn_socket_set_cbs(sock, cb_arg, cbs)                            \
+    do {                                                                \
+        (sock)->ms_cbs = (cbs);                                         \
+        (sock)->ms_cb_arg = (cb_arg);                                   \
+    } while (0)
+
+/*
+ * Address conversion
+ */
+int mn_inet_pton(int af, const char *src, void *dst);
+const char *mn_inet_ntop(int af, const void *src, void *dst, int len);
+
+/*
+ * Info about interfaces.
+ */
+#define MN_ITF_NAME_MAX    8
+
+/*
+ * Interface flags
+ */
+#define MN_ITF_F_UP        1
+#define MN_ITF_F_MULTICAST 2
+
+struct mn_itf {
+    char mif_name[MN_ITF_NAME_MAX];
+    uint8_t mif_idx;
+    uint8_t mif_flags;
+};
+
+struct mn_itf_addr {
+    uint8_t mifa_family;
+    uint8_t mifa_plen;
+    union {
+        struct mn_in_addr v4;
+        struct mn_in6_addr v6;
+    } mifa_addr;
+};
+
+/*
+ * Iterate through interfaces, and their addresses
+ */
+int mn_itf_getnext(struct mn_itf *);
+int mn_itf_addr_getnext(struct mn_itf *, struct mn_itf_addr *);
+
+#endif /* __SYS_MN_SOCKET_H_ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/net/ip/mn_socket/include/mn_socket/mn_socket_ops.h
----------------------------------------------------------------------
diff --git a/net/ip/mn_socket/include/mn_socket/mn_socket_ops.h b/net/ip/mn_socket/include/mn_socket/mn_socket_ops.h
new file mode 100644
index 0000000..39f11c1
--- /dev/null
+++ b/net/ip/mn_socket/include/mn_socket/mn_socket_ops.h
@@ -0,0 +1,85 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 __SYS_MN_SOCKET_OPS_H_
+#define __SYS_MN_SOCKET_OPS_H_
+
+#include <inttypes.h>
+
+/*
+ * Interface for socket providers.
+ * - mso_create() creates a socket, memory allocation has to be done by
+ *   the socket provider.
+ * - mso_close() closes the socket, memory should be freed. User should not
+ *   be using the socket pointer once it has been closed.
+ */
+struct mn_socket_ops {
+    int (*mso_create)(struct mn_socket **, uint8_t domain, uint8_t type,
+      uint8_t protocol);
+    int (*mso_close)(struct mn_socket *);
+
+    int (*mso_bind)(struct mn_socket *, struct mn_sockaddr *);
+    int (*mso_connect)(struct mn_socket *, struct mn_sockaddr *);
+    int (*mso_listen)(struct mn_socket *, uint8_t qlen);
+
+    int (*mso_sendto)(struct mn_socket *, struct os_mbuf *,
+      struct mn_sockaddr *to);
+    int (*mso_recvfrom)(struct mn_socket *, struct os_mbuf **,
+      struct mn_sockaddr *from);
+
+    int (*mso_getsockopt)(struct mn_socket *, uint8_t level, uint8_t name,
+      void *val);
+    int (*mso_setsockopt)(struct mn_socket *, uint8_t level, uint8_t name,
+      void *val);
+
+    int (*mso_getsockname)(struct mn_socket *, struct mn_sockaddr *);
+    int (*mso_getpeername)(struct mn_socket *, struct mn_sockaddr *);
+
+    int (*mso_itf_getnext)(struct mn_itf *);
+    int (*mso_itf_addr_getnext)(struct mn_itf *, struct mn_itf_addr *);
+};
+
+int mn_socket_ops_reg(const struct mn_socket_ops *ops);
+
+static inline void
+mn_socket_writable(struct mn_socket *s, int error)
+{
+    if (s->ms_cbs && s->ms_cbs->socket.writable) {
+        s->ms_cbs->socket.writable(s->ms_cb_arg, error);
+    }
+}
+
+static inline void
+mn_socket_readable(struct mn_socket *s, int error)
+{
+    if (s->ms_cbs && s->ms_cbs->socket.readable) {
+        s->ms_cbs->socket.readable(s->ms_cb_arg, error);
+    }
+}
+
+static inline int
+mn_socket_newconn(struct mn_socket *s, struct mn_socket *new)
+{
+    if (s->ms_cbs && s->ms_cbs->listen.newconn) {
+        return s->ms_cbs->listen.newconn(s->ms_cb_arg, new);
+    } else {
+        return -1;
+    }
+}
+
+#endif /* __SYS_MN_SOCKET_OPS_H_ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/net/ip/mn_socket/pkg.yml
----------------------------------------------------------------------
diff --git a/net/ip/mn_socket/pkg.yml b/net/ip/mn_socket/pkg.yml
new file mode 100644
index 0000000..ca4ee99
--- /dev/null
+++ b/net/ip/mn_socket/pkg.yml
@@ -0,0 +1,30 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+#
+
+pkg.name: net/ip/mn_socket
+pkg.description: Socket interface for Mynewt.
+pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
+pkg.homepage: "http://mynewt.apache.org/"
+pkg.keywords:
+    - socket
+    - IP
+
+pkg.deps:
+    - kernel/os
+    - libs/util

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/net/ip/mn_socket/src/arch/sim/native_itf.c
----------------------------------------------------------------------
diff --git a/net/ip/mn_socket/src/arch/sim/native_itf.c b/net/ip/mn_socket/src/arch/sim/native_itf.c
new file mode 100644
index 0000000..78607e7
--- /dev/null
+++ b/net/ip/mn_socket/src/arch/sim/native_itf.c
@@ -0,0 +1,212 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+#include <ifaddrs.h>
+#include <net/if.h>
+#include <string.h>
+#include <errno.h>
+#include <limits.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+
+#include "mn_socket/mn_socket.h"
+#include "native_sock_priv.h"
+
+static uint8_t
+itf_flags(int if_flags)
+{
+    uint8_t flags;
+
+    flags = 0;
+
+    if ((if_flags & (IFF_UP | IFF_RUNNING)) == (IFF_UP | IFF_RUNNING)) {
+        flags |= MN_ITF_F_UP;
+    }
+    if (if_flags & IFF_MULTICAST) {
+        flags |= MN_ITF_F_MULTICAST;
+    }
+    return flags;
+}
+
+int
+native_sock_itf_getnext(struct mn_itf *mi)
+{
+    int prev_idx, cur_idx;
+    struct ifaddrs *ifap;
+    struct ifaddrs *ifa;
+    int rc;
+
+    if (mi->mif_name[0] == '\0') {
+        prev_idx = 0;
+    } else {
+        prev_idx = mi->mif_idx;
+    }
+    mi->mif_idx = UCHAR_MAX;
+    rc = getifaddrs(&ifap);
+    if (rc < 0) {
+        rc = native_sock_err_to_mn_err(errno);
+        return rc;
+    }
+
+    rc = MN_ENOBUFS;
+    for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
+        cur_idx = if_nametoindex(ifa->ifa_name);
+        if (cur_idx <= prev_idx || cur_idx >= mi->mif_idx) {
+            continue;
+        }
+        strncpy(mi->mif_name, ifa->ifa_name, sizeof(mi->mif_name));
+        mi->mif_idx = cur_idx;
+        mi->mif_flags = itf_flags(ifa->ifa_flags);
+        rc = 0;
+    }
+    freeifaddrs(ifap);
+    return rc;
+}
+
+static int
+addrcmp(uint8_t fam1, void *addr1, uint8_t fam2, void *addr2, int alen)
+{
+    if (fam1 != fam2) {
+        return fam1 - fam2;
+    }
+    return memcmp(addr1, addr2, alen);
+}
+
+static int
+plen(void *addr, int alen)
+{
+    int i;
+    int j;
+    uint8_t b;
+
+    for (i = 0; i < alen; i++) {
+        b = ((uint8_t *)addr)[i];
+        if (b == 0xff) {
+            continue;
+        }
+        for (j = 0; j < 7; j++) {
+            if ((b & (0x80 >> j)) == 0) {
+                return i * 8 + j;
+            }
+        }
+    }
+    return alen * 8;
+}
+
+int
+native_sock_itf_addr(int idx, uint32_t *addr)
+{
+    struct ifaddrs *ifap;
+    struct ifaddrs *ifa;
+    struct sockaddr_in *sin;
+    int rc;
+
+    rc = getifaddrs(&ifap);
+    if (rc < 0) {
+        rc = native_sock_err_to_mn_err(errno);
+        return rc;
+    }
+
+    rc = MN_EADDRNOTAVAIL;
+    for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
+        if (if_nametoindex(ifa->ifa_name) != idx) {
+            continue;
+        }
+        if (ifa->ifa_addr->sa_family == AF_INET) {
+            sin = (struct sockaddr_in *)ifa->ifa_addr;
+            *addr = sin->sin_addr.s_addr;
+            rc = 0;
+            break;
+        }
+    }
+    freeifaddrs(ifap);
+    return rc;
+}
+
+int
+native_sock_itf_addr_getnext(struct mn_itf *mi, struct mn_itf_addr *mia)
+{
+    struct ifaddrs *ifap;
+    struct ifaddrs *ifa;
+    struct sockaddr_in *sin;
+    struct sockaddr_in6 *sin6;
+    int rc;
+    uint8_t prev_family;
+    uint8_t prev_addr[16];
+
+    rc = getifaddrs(&ifap);
+    if (rc < 0) {
+        rc = native_sock_err_to_mn_err(errno);
+        return rc;
+    }
+
+    prev_family = mia->mifa_family;
+    memcpy(prev_addr, &mia->mifa_addr, sizeof(mia->mifa_addr));
+    mia->mifa_family = UCHAR_MAX;
+    memset(&mia->mifa_addr, 0xff, sizeof(mia->mifa_addr));
+
+    rc = MN_ENOBUFS;
+
+    for (ifa = ifap; ifa; ifa = ifa->ifa_next) {
+        if (if_nametoindex(ifa->ifa_name) != mi->mif_idx) {
+            continue;
+        }
+        if (ifa->ifa_addr->sa_family == AF_INET) {
+            sin = (struct sockaddr_in *)ifa->ifa_addr;
+            if (addrcmp(MN_AF_INET, &sin->sin_addr,
+                prev_family, prev_addr,
+                sizeof(struct in_addr)) <= 0) {
+                continue;
+            }
+            if (addrcmp(MN_AF_INET, &sin->sin_addr,
+                mia->mifa_family, &mia->mifa_addr,
+                sizeof(struct in_addr)) >= 0) {
+                continue;
+            }
+            mia->mifa_family = MN_AF_INET;
+            memcpy(&mia->mifa_addr, &sin->sin_addr, sizeof(struct in_addr));
+
+            sin = (struct sockaddr_in *)ifa->ifa_netmask;
+            mia->mifa_plen = plen(&sin->sin_addr, sizeof(struct in_addr));
+        } else if (ifa->ifa_addr->sa_family == AF_INET6) {
+            sin6 = (struct sockaddr_in6 *)ifa->ifa_addr;
+            if (addrcmp(MN_AF_INET6, &sin6->sin6_addr,
+                prev_family, prev_addr,
+                sizeof(struct in6_addr)) <= 0) {
+                continue;
+            }
+            if (addrcmp(MN_AF_INET6, &sin6->sin6_addr,
+                mia->mifa_family, &mia->mifa_addr,
+                sizeof(struct in6_addr)) >= 0) {
+                continue;
+            }
+            mia->mifa_family = MN_AF_INET6;
+            memcpy(&mia->mifa_addr, &sin6->sin6_addr, sizeof(struct in6_addr));
+
+            sin6 = (struct sockaddr_in6 *)ifa->ifa_netmask;
+            mia->mifa_plen = plen(&sin6->sin6_addr, sizeof(struct in6_addr));
+        } else {
+            continue;
+        }
+        rc = 0;
+    }
+    freeifaddrs(ifap);
+    return rc;
+}
+
+


[04/49] incubator-mynewt-core git commit: directory re-org

Posted by st...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/stats/pkg.yml
----------------------------------------------------------------------
diff --git a/sys/stats/pkg.yml b/sys/stats/pkg.yml
index bde92c8..67c95fd 100644
--- a/sys/stats/pkg.yml
+++ b/sys/stats/pkg.yml
@@ -25,10 +25,10 @@ pkg.keywords:
     - statistics
 
 pkg.deps:
-    - libs/os
+    - kernel/os
     - libs/util
 pkg.deps.STATS_CLI:
-    - libs/shell
+    - sys/shell
 pkg.req_apis.STATS_NEWTMGR:
     - newtmgr
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/sys/sysinit/pkg.yml
----------------------------------------------------------------------
diff --git a/sys/sysinit/pkg.yml b/sys/sysinit/pkg.yml
index e728ccf..e6f8225 100644
--- a/sys/sysinit/pkg.yml
+++ b/sys/sysinit/pkg.yml
@@ -25,7 +25,7 @@ pkg.keywords:
     - init
 
 pkg.deps:
-    - libs/os
+    - kernel/os
     - libs/util
 
 pkg.syscfg_defs:

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/test/crash_test/include/crash_test/crash_test.h
----------------------------------------------------------------------
diff --git a/test/crash_test/include/crash_test/crash_test.h b/test/crash_test/include/crash_test/crash_test.h
new file mode 100644
index 0000000..73135fd
--- /dev/null
+++ b/test/crash_test/include/crash_test/crash_test.h
@@ -0,0 +1,27 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 __CRASH_TEST_H__
+#define __CRASH_TEST_H__
+
+/*
+ * Adds the crash commands to your shell/newtmgr.
+ */
+int crash_test_init(void);
+
+#endif /* __CRASH_TEST_H__ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/test/crash_test/pkg.yml
----------------------------------------------------------------------
diff --git a/test/crash_test/pkg.yml b/test/crash_test/pkg.yml
new file mode 100644
index 0000000..75afa8c
--- /dev/null
+++ b/test/crash_test/pkg.yml
@@ -0,0 +1,42 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+#
+
+pkg.name: test/crash_test
+pkg.description: Generate different kinds of faults
+pkg.homepage: "http://mynewt.apache.org/"
+pkg.keywords:
+
+pkg.deps.CRASH_TEST_CLI:
+    - sys/shell
+pkg.req_apis.CRASH_TEST_CLI:
+    - console
+pkg.req_apis.CRASH_TEST_NEWTMGR:
+    - newtmgr
+
+pkg.deps.CRASH_TEST_NEWTMGR:
+    - libs/newtmgr
+    - encoding/json
+
+pkg.syscfg_defs:
+    CRASH_TEST_CLI:
+        description: 'TBD'
+        value: 1
+    CRASH_TEST_NEWTMGR:
+        description: 'TBD'
+        value: 1

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/test/crash_test/src/crash_cli.c
----------------------------------------------------------------------
diff --git a/test/crash_test/src/crash_cli.c b/test/crash_test/src/crash_cli.c
new file mode 100644
index 0000000..4d49bef
--- /dev/null
+++ b/test/crash_test/src/crash_cli.c
@@ -0,0 +1,49 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include "syscfg/syscfg.h"
+
+#if MYNEWT_VAL(CRASH_TEST_CLI)
+#include <inttypes.h>
+#include <os/os.h>
+#include <console/console.h>
+#include <shell/shell.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "crash_test/crash_test.h"
+#include "crash_test_priv.h"
+
+static int crash_cli_cmd(int argc, char **argv);
+struct shell_cmd crash_cmd_struct = {
+    .sc_cmd = "crash",
+    .sc_cmd_func = crash_cli_cmd
+};
+
+static int
+crash_cli_cmd(int argc, char **argv)
+{
+    if (argc >= 2 && crash_device(argv[1]) == 0) {
+        return 0;
+    }
+    console_printf("Usage crash [div0|jump0|ref0|assert]\n");
+    return 0;
+}
+
+#endif /* MYNEWT_VAL(CRASH_TEST_CLI) */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/test/crash_test/src/crash_nmgr.c
----------------------------------------------------------------------
diff --git a/test/crash_test/src/crash_nmgr.c b/test/crash_test/src/crash_nmgr.c
new file mode 100644
index 0000000..d9bf4b0
--- /dev/null
+++ b/test/crash_test/src/crash_nmgr.c
@@ -0,0 +1,75 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include "syscfg/syscfg.h"
+
+#if MYNEWT_VAL(CRASH_TEST_NEWTMGR)
+
+#include <string.h>
+
+#include "newtmgr/newtmgr.h"
+#include "json/json.h"
+#include "console/console.h"
+
+#include "crash_test/crash_test.h"
+#include "crash_test_priv.h"
+
+static int crash_test_nmgr_write(struct nmgr_jbuf *);
+
+static const struct nmgr_handler crash_test_nmgr_handler[] = {
+    [0] = { crash_test_nmgr_write, crash_test_nmgr_write }
+};
+
+struct nmgr_group crash_test_nmgr_group = {
+    .ng_handlers = (struct nmgr_handler *)crash_test_nmgr_handler,
+    .ng_handlers_count = 1,
+    .ng_group_id = NMGR_GROUP_ID_CRASH
+};
+
+static int
+crash_test_nmgr_write(struct nmgr_jbuf *njb)
+{
+    char tmp_str[64];
+    const struct json_attr_t attr[2] = {
+        [0] = {
+            .attribute = "t",
+            .type = t_string,
+            .addr.string = tmp_str,
+            .len = sizeof(tmp_str)
+        },
+        [1] = {
+            .attribute = NULL
+        }
+    };
+    int rc;
+
+    rc = json_read_object(&njb->njb_buf, attr);
+    if (rc) {
+        rc = NMGR_ERR_EINVAL;
+    } else {
+        rc = crash_device(tmp_str);
+        if (rc) {
+            rc = NMGR_ERR_EINVAL;
+        }
+    }
+    nmgr_jbuf_setoerr(njb, rc);
+    return 0;
+}
+
+#endif /* MYNEWT_VAL(CRASH_TEST_NEWTMGR) */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/test/crash_test/src/crash_test.c
----------------------------------------------------------------------
diff --git a/test/crash_test/src/crash_test.c b/test/crash_test/src/crash_test.c
new file mode 100644
index 0000000..a6e2ea2
--- /dev/null
+++ b/test/crash_test/src/crash_test.c
@@ -0,0 +1,72 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+#include <inttypes.h>
+#include <stdio.h>
+#include <string.h>
+#include <assert.h>
+
+#include "syscfg/syscfg.h"
+#include "os/os.h"
+#include "console/console.h"
+
+#include "crash_test/crash_test.h"
+#include "crash_test_priv.h"
+
+#if MYNEWT_VAL(CRASH_TEST_CLI)
+#include "shell/shell.h"
+#endif
+#if MYNEWT_VAL(CRASH_TEST_NEWTMGR)
+#include "newtmgr/newtmgr.h"
+#endif
+
+int
+crash_device(char *how)
+{
+    volatile int val1, val2, val3;
+
+    if (!strcmp(how, "div0")) {
+
+        val1 = 42;
+        val2 = 0;
+
+        val3 = val1 / val2;
+        console_printf("42/0 = %d\n", val3);
+    } else if (!strcmp(how, "jump0")) {
+        ((void (*)(void))0)();
+    } else if (!strcmp(how, "ref0")) {
+        val1 = *(int *)0;
+    } else if (!strcmp(how, "assert")) {
+        assert(0);
+    } else {
+        return -1;
+    }
+    return 0;
+}
+
+int
+crash_test_init(void)
+{
+#if MYNEWT_VAL(CRASH_TEST_CLI)
+    shell_cmd_register(&crash_cmd_struct);
+#endif
+#if MYNEWT_VAL(CRASH_TEST_NEWTMGR)
+    nmgr_group_register(&crash_test_nmgr_group);
+#endif
+    return 0;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/test/crash_test/src/crash_test_priv.h
----------------------------------------------------------------------
diff --git a/test/crash_test/src/crash_test_priv.h b/test/crash_test/src/crash_test_priv.h
new file mode 100644
index 0000000..09dc5a3
--- /dev/null
+++ b/test/crash_test/src/crash_test_priv.h
@@ -0,0 +1,31 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 __CRASH_TEST_PRIV_H__
+#define __CRASH_TEST_PRIV_H__
+
+#if MYNEWT_VAL(CRASH_TEST_CLI)
+extern struct shell_cmd crash_cmd_struct;
+#endif
+#if MYNEWT_VAL(CRASH_TEST_NEWTMGR)
+extern struct nmgr_group crash_test_nmgr_group;
+#endif
+
+int crash_device(char *how);
+
+#endif /* __CRASH_TEST_PRIV_H__ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/test/flash_test/include/flash_test/flash_test.h
----------------------------------------------------------------------
diff --git a/test/flash_test/include/flash_test/flash_test.h b/test/flash_test/include/flash_test/flash_test.h
new file mode 100644
index 0000000..f38f48c
--- /dev/null
+++ b/test/flash_test/include/flash_test/flash_test.h
@@ -0,0 +1,27 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 __FLASH_TEST_H__ 
+#define __FLASH_TEST_H__
+
+/**
+ * adds the flash test commands to your shell */
+int
+flash_test_init(void);
+
+#endif /* __FLASH_TEST_H__ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/test/flash_test/pkg.yml
----------------------------------------------------------------------
diff --git a/test/flash_test/pkg.yml b/test/flash_test/pkg.yml
new file mode 100644
index 0000000..365705c
--- /dev/null
+++ b/test/flash_test/pkg.yml
@@ -0,0 +1,30 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+#
+
+pkg.name: test/flash_test
+pkg.description: flash HAL tester
+pkg.homepage: "http://mynewt.apache.org/"
+pkg.keywords:
+
+pkg.deps:
+    - kernel/os
+    - libs/util
+    - hw/hal
+pkg.req_apis:
+    - console

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/test/flash_test/src/flash_test/flash_test.c
----------------------------------------------------------------------
diff --git a/test/flash_test/src/flash_test/flash_test.c b/test/flash_test/src/flash_test/flash_test.c
new file mode 100644
index 0000000..980cbba
--- /dev/null
+++ b/test/flash_test/src/flash_test/flash_test.c
@@ -0,0 +1,155 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+#include <inttypes.h>
+#include <os/os.h>
+#include <console/console.h>
+#include <flash_test/flash_test.h>
+#include <hal/hal_bsp.h>
+#include <hal/hal_flash.h>
+#include <hal/hal_flash_int.h>
+#include <shell/shell.h>
+#include <stdio.h>
+#include <string.h>
+
+static int flash_cli_cmd(int argc, char **argv);
+static struct shell_cmd flash_cmd_struct = {
+    .sc_cmd = "flash",
+    .sc_cmd_func = flash_cli_cmd
+};
+
+static int
+flash_cli_cmd(int argc, char **argv)
+{
+    const struct hal_flash *hf;
+    uint32_t off = 0;
+    uint32_t sz = 1;
+    int sec_cnt;
+    int i;
+    int soff;
+    char *eptr;
+    char tmp_buf[8];
+    char pr_str[80];
+
+    hf = bsp_flash_dev(0);
+    if (!hf) {
+        console_printf("No flash device present\n");
+        return 0;
+    }
+    if (argc == 1) {
+        /*
+         * print status
+         */
+        console_printf("Flash at 0x%lx size 0x%lx with %d sectors,"
+          "alignment req %d bytes\n", 
+                (long unsigned int) hf->hf_base_addr, 
+                (long unsigned int) hf->hf_size,
+                hf->hf_sector_cnt, 
+                hf->hf_align);
+        sec_cnt = hf->hf_sector_cnt;
+        if (sec_cnt > 32) {
+            sec_cnt = 32;
+        }
+        for (i = 0; i < sec_cnt; i++) {
+            console_printf("  %d: %lx\n", i, 
+                    (long unsigned int) hal_flash_sector_size(hf, i));
+        }
+        if (sec_cnt != hf->hf_sector_cnt) {
+            console_printf("...  %d: %lx\n", hf->hf_sector_cnt - 1,
+              (long unsigned int) hal_flash_sector_size(hf, hf->hf_sector_cnt - 1));
+        }
+        return 0;
+    }
+    if (argc > 2) {
+        off = strtoul(argv[2], &eptr, 0);
+        if (*eptr != '\0') {
+            console_printf("Invalid offset %s\n", argv[2]);
+            goto err;
+        }
+    }
+    if (argc > 3) {
+        sz = strtoul(argv[3], &eptr, 0);
+        if (*eptr != '\0') {
+            console_printf("Invalid size %s\n", argv[3]);
+            goto err;
+        }
+    }
+    if (!strcmp(argv[1], "erase")) {
+        console_printf("Erase 0x%lx + %lx\n", 
+                (long unsigned int) off, (long unsigned int) sz);
+
+        if (hal_flash_erase(0, off, sz)) {
+            console_printf("Flash erase failed\n");
+        }
+        console_printf("Done!\n");
+    } else if (!strcmp(argv[1], "read")) {
+        console_printf("Read 0x%lx + %lx\n", 
+                (long unsigned int) off, (long unsigned int) sz);
+        sz += off;
+        while (off < sz) {
+            sec_cnt = min(sizeof(tmp_buf), sz - off);
+            if (hal_flash_read(0, off, tmp_buf, sec_cnt)) {
+                console_printf("flash read failure at %lx\n", 
+                        (long unsigned int) off);
+                break;
+            }
+            for (i = 0, soff = 0; i < sec_cnt; i++) {
+                soff += snprintf(pr_str + soff, sizeof(pr_str) - soff,
+                  "0x%02x ", tmp_buf[i] & 0xff);
+            }
+            console_printf("  0x%lx: %s\n", 
+                    (long unsigned int) off, pr_str);
+            off += sec_cnt;
+        }
+    } else if (!strcmp(argv[1], "write")) {
+        console_printf("Write 0x%lx + %lx\n", 
+                (long unsigned int) off, (long unsigned int) sz);
+
+        sz += off;
+        for (i = 0; i < sizeof(tmp_buf); i++) {
+            tmp_buf[i] = i + 1;
+        }
+
+        while (off < sz) {
+            sec_cnt = min(sizeof(tmp_buf), sz - off);
+            if (hal_flash_write(0, off, tmp_buf, sec_cnt)) {
+                console_printf("flash write failure at %lx\n", 
+                        (long unsigned int) off);
+            }
+            off += sec_cnt;
+        }
+        console_printf("Done!\n");
+    } else if ( !strcmp(argv[1], "?") || !strcmp(argv[1], "help"))
+    {
+        console_printf("Commands Available\n");
+        console_printf("flash -- dumps sector map \n");
+        console_printf("flash read <offset> <size> -- reads bytes from flash \n");
+        console_printf("flash write <offset>  <size>  -- writes incrementing data pattern 0-8 to flash \n");
+        console_printf("flash erase <offset> <size> -- erases flash \n");
+    }
+    return 0;
+err:
+    return -1;
+}
+
+
+int
+flash_test_init(void) {
+    shell_cmd_register(&flash_cmd_struct);
+    return 0;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/test/testreport/include/testreport/testreport.h
----------------------------------------------------------------------
diff --git a/test/testreport/include/testreport/testreport.h b/test/testreport/include/testreport/testreport.h
new file mode 100644
index 0000000..7a0d3e4
--- /dev/null
+++ b/test/testreport/include/testreport/testreport.h
@@ -0,0 +1,34 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 H_TESTREPORT_
+#define H_TESTREPORT_
+
+struct nffs_area_desc;
+
+struct tr_config {
+    const char *tc_base_path;
+    const struct nffs_area_desc *tc_area_descs;
+};
+
+extern struct tr_config tr_config;
+
+int tr_init(void);
+
+#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/test/testreport/pkg.yml
----------------------------------------------------------------------
diff --git a/test/testreport/pkg.yml b/test/testreport/pkg.yml
new file mode 100644
index 0000000..42e8482
--- /dev/null
+++ b/test/testreport/pkg.yml
@@ -0,0 +1,30 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+#
+
+pkg.name: test/testreport
+pkg.description: Library for recording unit test results to flash.
+pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
+pkg.homepage: "http://mynewt.apache.org/"
+pkg.keywords:
+    - unit
+    - test
+
+pkg.deps:
+    - fs/nffs
+    - test/testutil

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/test/testreport/src/arch/cortex_m4/io.c
----------------------------------------------------------------------
diff --git a/test/testreport/src/arch/cortex_m4/io.c b/test/testreport/src/arch/cortex_m4/io.c
new file mode 100644
index 0000000..fd27585
--- /dev/null
+++ b/test/testreport/src/arch/cortex_m4/io.c
@@ -0,0 +1,91 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include <stddef.h>
+#include "nffs/nffs.h"
+#include "nffs/nffsutil.h"
+#include "testreport_priv.h"
+
+int
+tr_io_write(const char *path, const void *contents, size_t len)
+{
+    int rc;
+
+    rc = nffsutil_write_file(path, contents, len);
+    if (rc != 0) {
+        return -1;
+    }
+
+    return 0;
+}
+
+int
+tr_io_mkdir(const char *path)
+{
+    int rc;
+
+    rc = nffs_mkdir(path);
+    if (rc != 0 && rc != NFFS_EEXIST) {
+        return -1;
+    }
+
+    return 0;
+}
+
+int
+tr_io_rmdir(const char *path)
+{
+    int rc;
+
+    rc = nffs_unlink(path);
+    if (rc != 0 && rc != NFFS_ENOENT) {
+        return -1;
+    }
+
+    return 0;
+}
+
+int
+tr_io_read(const char *path, void *out_data, size_t len, size_t *out_len)
+{
+    uint32_t u32;
+    int rc;
+
+    rc = nffsutil_read_file(path, 0, len, out_data, &u32);
+    if (rc != 0) {
+        return -1;
+    }
+
+    *out_len = u32;
+
+    return 0;
+}
+
+int
+tr_io_delete(const char *path)
+{
+    int rc;
+
+    rc = nffs_unlink(path);
+    if (rc != 0 && rc != NFFS_ENOENT) {
+        return -1;
+    }
+
+    return 0;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/test/testreport/src/arch/sim/io.c
----------------------------------------------------------------------
diff --git a/test/testreport/src/arch/sim/io.c b/test/testreport/src/arch/sim/io.c
new file mode 100644
index 0000000..a5233e5
--- /dev/null
+++ b/test/testreport/src/arch/sim/io.c
@@ -0,0 +1,140 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <errno.h>
+#include <unistd.h>
+#include <sys/stat.h>
+#include "testreport_priv.h"
+
+static char tr_io_buf[1024];
+
+int
+tr_io_write(const char *path, const void *contents, size_t len)
+{
+    FILE *fp;
+    int rc;
+
+    fp = NULL;
+
+    fp = fopen(path, "w+");
+    if (fp == NULL) {
+        rc = -1;
+        goto done;
+    }
+
+    if (contents != NULL && len > 0) {
+        rc = fwrite(contents, len, 1, fp);
+        if (rc != 1) {
+            rc = -1;
+            goto done;
+        }
+    }
+
+    rc = 0;
+
+done:
+    if (fp != NULL) {
+        fclose(fp);
+    }
+
+    return rc;
+}
+
+int
+tr_io_mkdir(const char *path)
+{
+    int rc;
+
+    rc = mkdir(path, 0755);
+    if (rc == -1 && errno != EEXIST) {
+        return -1;
+    }
+
+    return 0;
+}
+
+/* XXX security risk, not portable, blah blah blah */
+int
+tr_io_rmdir(const char *path)
+{
+    int rc; 
+
+    rc = snprintf(tr_io_buf, sizeof tr_io_buf,
+                  "rm -rf '%s'", path);
+    if (rc >= sizeof tr_io_buf) {
+        return -1;
+    }
+
+    rc = system(tr_io_buf);
+    if (rc != 0) {
+        return rc;
+    }
+
+    return 0;
+}
+
+int
+tr_io_read(const char *path, void *out_data, size_t len, size_t *out_len)
+{
+    FILE *fp;
+    uint8_t *dst;
+    int rc;
+    int i;
+
+    fp = NULL;
+
+    fp = fopen(path, "rb");
+    if (fp == NULL) {
+        rc = -1;
+        goto done;
+    }
+
+    dst = out_data;
+    for (i = 0; i < len; i++) {
+        rc = getc(fp);
+        if (rc == EOF) {
+            rc = -1;
+            goto done;
+        }
+
+        dst[i] = rc;
+    }
+
+    *out_len = i;
+    rc = 0;
+
+done:
+    if (fp != NULL) {
+        fclose(fp);
+    }
+
+    return rc;
+}
+
+int
+tr_io_delete(const char *path)
+{
+    int rc;
+
+    rc = remove(path);
+
+    return rc;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/test/testreport/src/results.c
----------------------------------------------------------------------
diff --git a/test/testreport/src/results.c b/test/testreport/src/results.c
new file mode 100644
index 0000000..77b26c2
--- /dev/null
+++ b/test/testreport/src/results.c
@@ -0,0 +1,190 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include <stdio.h>
+#include "testutil/testutil.h"
+#include "testreport/testreport.h"
+#include "testreport_priv.h"
+
+#define TU_REPORT_META_DIR          ".meta"
+#define TU_REPORT_STATUS_FILENAME   "status"
+
+static char tr_report_buf[1024];
+
+int
+tr_report_rmdir_results(void)
+{
+    if (tr_config.tc_base_path == NULL) {
+        return 0;
+    }
+
+    return tr_io_rmdir(tr_config.tc_base_path);
+}
+
+int
+tr_report_mkdir_results(void)
+{
+    int rc;
+
+    if (tr_config.tc_base_path == NULL) {
+        return 0;
+    }
+
+    rc = snprintf(tr_report_buf, sizeof tr_report_buf,
+                  "%s", tr_config.tc_base_path);
+    if (rc >= sizeof tr_report_buf) {
+        return -1;
+    }
+    return tr_io_mkdir(tr_report_buf);
+}
+
+int
+tr_report_mkdir_meta(void)
+{
+    int rc;
+
+    if (tr_config.tc_base_path == NULL) {
+        return 0;
+    }
+
+    rc = snprintf(tr_report_buf, sizeof tr_report_buf,
+                  "%s/" TU_REPORT_META_DIR, tr_config.tc_base_path);
+    if (rc >= sizeof tr_report_buf) {
+        return -1;
+    }
+    return tr_io_mkdir(tr_report_buf);
+}
+
+int
+tr_report_mkdir_suite(void)
+{
+    int rc;
+
+    if (tr_config.tc_base_path == NULL) {
+        return 0;
+    }
+
+    rc = snprintf(tr_report_buf, sizeof tr_report_buf,
+                  "%s/%s", tr_config.tc_base_path,
+                  tu_suite_name);
+    if (rc >= sizeof tr_report_buf) {
+        return -1;
+    }
+
+    rc = tr_io_mkdir(tr_report_buf);
+    if (rc != 0) {
+        return rc;
+    }
+
+    return 0;
+}
+
+int
+tr_report_mkdir_case(void)
+{
+    int rc;
+
+    if (tr_config.tc_base_path == NULL) {
+        return 0;
+    }
+
+    rc = snprintf(tr_report_buf, sizeof tr_report_buf,
+                  "%s/%s/%s", tr_config.tc_base_path,
+                  tu_suite_name, tu_case_name);
+    if (rc >= sizeof tr_report_buf) {
+        return -1;
+    }
+
+    rc = tr_io_mkdir(tr_report_buf);
+    if (rc != 0) {
+        return rc;
+    }
+
+    return 0;
+}
+
+int
+tr_report_write_file(const char *filename, const uint8_t *data,
+                     size_t data_len)
+{
+    int rc;
+
+    if (tr_config.tc_base_path == NULL) {
+        return 0;
+    }
+
+    rc = snprintf(tr_report_buf, sizeof tr_report_buf,
+                  "%s/%s/%s/%s", tr_config.tc_base_path,
+                  tu_suite_name, tu_case_name, filename);
+    if (rc >= sizeof tr_report_buf) {
+        return -1;
+    }
+
+    rc = tr_io_write(tr_report_buf, data, data_len);
+    if (rc != 0) {
+        return rc;
+    }
+
+    return 0;
+}
+
+int
+tr_report_read_status(void)
+{
+    size_t bytes_read;
+    int rc;
+
+    rc = snprintf(tr_report_buf, sizeof tr_report_buf,
+                  "%s/%s/%s", tr_config.tc_base_path,
+                  TU_REPORT_META_DIR, TU_REPORT_STATUS_FILENAME);
+    if (rc >= sizeof tr_report_buf) {
+        return -1;
+    }
+
+    rc = tr_io_read(tr_report_buf, &tu_first_idx, sizeof tu_first_idx,
+                    &bytes_read);
+    if (rc != 0 || bytes_read != sizeof tu_first_idx) {
+        return -1;
+    }
+
+    tr_io_delete(tr_report_buf);
+
+    return 0;
+}
+
+int
+tr_report_write_status(void)
+{
+    int rc;
+
+    rc = snprintf(tr_report_buf, sizeof tr_report_buf,
+                  "%s/%s/%s", tr_config.tc_base_path,
+                  TU_REPORT_META_DIR, TU_REPORT_STATUS_FILENAME);
+    if (rc >= sizeof tr_report_buf) {
+        return -1;
+    }
+
+    rc = tr_io_write(tr_report_buf, &tu_first_idx, sizeof tu_first_idx);
+    if (rc != 0) {
+        return -1;
+    }
+
+    return 0;
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/test/testreport/src/testreport.c
----------------------------------------------------------------------
diff --git a/test/testreport/src/testreport.c b/test/testreport/src/testreport.c
new file mode 100644
index 0000000..c29221b
--- /dev/null
+++ b/test/testreport/src/testreport.c
@@ -0,0 +1,131 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include <assert.h>
+#include <stdio.h>
+#include "hal/hal_flash.h"
+#include "fs/fs.h"
+#include "nffs/nffs.h"
+#include "testutil/testutil.h"
+#include "testreport/testreport.h"
+#include "testreport_priv.h"
+
+struct tr_config tr_config;
+
+static int tr_case_fail_idx;
+
+static void
+tr_case_init(void *unused)
+{
+    int rc;
+
+    rc = tr_results_mkdir_case();
+    assert(rc == 0);
+}
+
+static void
+tr_case_fail(char *msg, int msg_len, void *unused)
+{
+    char filename[14];
+    int rc;
+
+    rc = snprintf(filename, sizeof filename, "fail-%04d.txt",
+                  tr_case_fail_idx);
+    assert(rc < sizeof filename);
+
+    rc = tr_results_write_file(filename, (uint8_t *)msg, msg_len);
+    assert(rc == 0);
+
+    tr_case_fail_idx++;
+}
+
+static void
+tr_case_pass(char *msg, int msg_len, void *unused)
+{
+    int rc;
+
+    rc = tr_results_write_file("pass.txt", (uint8_t *)msg, msg_len);
+    assert(rc == 0);
+}
+
+static void
+tr_suite_init(void *unused)
+{
+    int rc;
+
+    rc = tr_results_mkdir_suite();
+    assert(rc == 0);
+}
+
+static void
+tr_restart(void *unused)
+{
+    tr_results_write_status();
+}
+
+int
+tr_init(void)
+{
+    int rc;
+
+    if (tr_config.tc_base_path != NULL) {
+        if (tr_config.tc_area_descs != NULL) {
+            rc = hal_flash_init();
+            if (rc != 0) {
+                return -1;
+            }
+
+            rc = nffs_init();
+            if (rc != 0) {
+                return -1;
+            }
+
+            rc = nffs_detect(tr_config.tc_area_descs);
+            if (rc == FS_ECORRUPT) {
+                rc = nffs_format(tr_config.tc_area_descs);
+            }
+            if (rc != 0) {
+                return -1;
+            }
+        }
+
+        rc = tr_results_read_status();
+        if (rc != 0) {
+            tr_results_rmdir_results();
+        }
+
+        rc = tr_results_mkdir_results();
+        if (rc != 0) {
+            return -1;
+        }
+
+        rc = tr_results_mkdir_meta();
+        if (rc != 0) {
+            return -1;
+        }
+    }
+
+    tu_config.tc_case_init_cb = tr_case_init;
+    tu_config.tc_case_fail_cb = tr_case_fail;
+    tu_config.tc_case_pass_cb = tr_case_pass;
+    tu_config.tc_suite_init_cb = tr_suite_init;
+    tu_config.tc_restart_cb = tr_restart;
+
+    return 0;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/test/testreport/src/testreport_priv.h
----------------------------------------------------------------------
diff --git a/test/testreport/src/testreport_priv.h b/test/testreport/src/testreport_priv.h
new file mode 100644
index 0000000..88576b6
--- /dev/null
+++ b/test/testreport/src/testreport_priv.h
@@ -0,0 +1,48 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 H_TESTREPORT_PRIV_
+#define H_TESTREPORT_PRIV_
+
+#include <stddef.h>
+#include <inttypes.h>
+
+int tr_results_mkdir_results(void);
+int tr_results_rmdir_results(void);
+
+int tr_results_mkdir_meta(void);
+
+int tr_results_mkdir_suite(void);
+int tr_results_mkdir_case(void);
+
+int tr_results_write_file(const char *filename, const uint8_t *data,
+                          size_t data_len);
+
+int tr_results_read_status(void);
+int tr_results_write_status(void);
+
+int tr_io_read(const char *path, void *out_data, size_t len, size_t *out_len);
+int tr_io_write(const char *path, const void *contents, size_t len);
+
+int tr_io_delete(const char *path);
+
+int tr_io_mkdir(const char *path);
+int tr_io_rmdir(const char *path);
+
+#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/test/testutil/design.txt
----------------------------------------------------------------------
diff --git a/test/testutil/design.txt b/test/testutil/design.txt
new file mode 100644
index 0000000..a1dfd9b
--- /dev/null
+++ b/test/testutil/design.txt
@@ -0,0 +1,476 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+#
+
+****** TEST AUTOMATION
+
+*** HISTORY
+Rev.    Date            Changes
+2       2015/09/07      Addition of tu_restart(); clarification of exported
+                            preprocessor symbols.
+1       2015/08/28
+
+
+*** SUMMARY
+
+Automated testing can be done in either of two ways:
+    1. Testing a set of packages on embedded hardware or a simulated
+       environment.
+    2. Testing an individual package in a simulated environment.
+
+
+***** PACKAGE SET TESTING
+
+Automated testing of package sets consists of two components:
+    1. "PC software" which administers tests and manages results.
+    2. Test images which run on the units under test (UUTs).
+
+
+**** PC SOFTWARE
+
+The PC software will need to perform the following tasks:
+    1. Connect to UUT (e.g., via JTAG and OpenOCD) (if embedded).
+    2. Upload test image (if embedded).
+    3. Run test image.
+    4. Read test results from UUT.
+    5. Generate test report.
+
+If any of these tasks fail, a fatal error would need to be logged to the test
+report.
+
+The details of the PC software are TBD, and are not discussed further here.
+
+
+**** TEST IMAGES
+
+Test images are build using the stack tool.  The user will need to create a
+separate stack tool target for each platform under test.  In addition, there
+will be a single stack tool project which contains code to call the appropriate
+test code.  Each test image typically consists of the following:
+    1. The test cases from all relevant packages.
+    2. Some "glue code" from a special test project.
+
+
+*** PACKAGE TEST CASES
+
+A package may optionally contain a set of test cases.  Test cases are not
+normally compiled and linked when a package is built; they are only included
+when the "test" identity is specified.  All of a
+package's test code goes in its 'src/test' directory.  For example, the ffs
+package's test code is located in the following directory:
+
+    libs/ffs/src/test/
+
+This directory contains the source and header files that implement the ffs test
+code.
+
+The test code has access to all the header files in the following directories:
+    * src
+    * src/arch/<target-arch>
+    * include
+    * src/test
+    * src/test/arch/<target-arch>
+    * include directories of all package dependencies
+
+Package test code typically depends on the testutil package, described later in
+this document.  If a package's test code uses testutil, then the package itself
+needs to have testutil in its dependency list.
+
+Some test cases or test initialization code may be platform-specific.  In such
+cases, the platform-specific function definitions are placed in arch
+subdirectories within the package test directory.
+
+When test code is built (i.e., when the "test" identity is specified), the
+stack tool defines the "TEST" macro.  This macro is defined during complilation
+of all C source files in all projects and packages..
+
+
+***** TESTUTIL
+
+The testutil package is a test framework that provides facilities for
+specifying test cases and recording test results.  
+
+
+*** TEST STRUCTURE
+
+Tests are structures according to the following hierarchy:
+
+                [test]
+               /      \
+        [suite]        [suite]
+       /       \      /       \
+     [case] [case]  [case] [case]
+
+
+I.e., a test consists of test suites, and a test suite consits of test cases.
+
+The test code uses testutil to define test suites and test cases.
+
+
+*** TESTUTIL EXAMPLE
+
+The following example demonstrates how to create a simple test suite.
+
+    TEST_CASE(test_addition)
+    {
+        int sum;
+
+        sum = 5 + 10;
+        TEST_ASSERT(sum == 15, "actual value: %d", sum);
+    }
+
+    TEST_CASE(test_times_0)
+    {
+        TEST_ASSERT(3 * 0 == 0);
+        TEST_ASSERT(4 * 0 == 0);
+        TEST_ASSERT(712 * 0 == 0);
+    }
+
+    TEST_SUITE(test_suite_arithmetic)
+    {
+        test_addition();
+        test_times_0();
+    }
+
+The test suite would then be executed via a call to test_suite_arithmetic().
+
+
+*** TEST RESULTS
+
+The testutil package optionally writes test results to a file system residing
+on the UUT.  The contents of the file system can then be retrieved from the UUT
+by the PC software.  When run in an embedded environment, the results are
+written to an ffs file system.  When run in a simulated environment, the
+results are written to the native file system.
+
+Results directory structure:
+    /
+    \u2514\u2500\u2500 test-results
+        \u251c\u2500\u2500 <test-suite-1>
+        |   \u251c\u2500\u2500 <test-case-1>
+        |   \u2502�� \u251c\u2500\u2500 <result-1>.txt
+        |   \u2502�� \u251c\u2500\u2500 [<result-2>.txt]
+        |   \u2502�� \u251c\u2500\u2500 [...]
+        |   \u2502�� \u2514\u2500\u2500 [other-data-files]
+        |   \u251c\u2500\u2500 <test-case-2>
+        |   \u2502�� \u251c\u2500\u2500 <result-1>.txt
+        |   \u2502�� \u251c\u2500\u2500 [<result-2>.txt]
+        |   \u2502�� \u251c\u2500\u2500 [...]
+        |   \u2502�� \u2514\u2500\u2500 [other-data-files]
+        |   \u2514\u2500\u2500 [...]
+        \u251c\u2500\u2500 <test-suite-2>
+        |   \u2514\u2500\u2500 [...]
+        \u2514\u2500\u2500 [...]
+
+The name of the top-level directory is configurable.  This document uses
+'test-results' in its examples.
+
+Each test case directory contains a set of result files, and optionally
+contains data files containing information collected during the test.  Result
+files are named according to one of the following templates:
+
+    * pass.txt
+    * fail-xxxx.txt
+
+Where "xxxx" is a numeric index automatically generated by testutil.  If a test
+passes, its results directory is populated with a single 'pass' file and no
+'fail' files.  If a test fails, its results directory is populated with one or
+more 'fail' files and no 'pass' files.  A result file (pass or fail) optionally
+contains a text string.
+
+In addition, a results directory can contains data files containing information
+collected during the test.  For example, a test case may record timing
+information or statistics.  Test case code specifies the name and contents of a
+data file when it writes one.  Data files can be written during a test case
+regardless of the test outcome.  There are no restrictions on the size or
+contents of data files, but their filenames should be distinct from the test
+result naming scheme described above.  There is no limit to the number of data
+files that a particular test case can write.
+
+Returning to the earlier arithmetic test suite example, suppose the test suite
+completed with the following results:
+
+    * test_addition: 1 assertion success, 0 assertion failures
+    * test_times_0:  1 assertion success, 2 assertion failures
+
+Such a test run would produce the following directory tree:
+
+    /
+    \u2514\u2500\u2500 test-results
+        \u2514\u2500\u2500 test_suite_arithmetic
+            \u251c\u2500\u2500 test_addition
+            \u2502�� \u2514\u2500\u2500 pass.txt
+            \u2514\u2500\u2500 test_times_0
+                \u251c\u2500\u2500 fail-0000.txt
+                \u2514\u2500\u2500 fail-0001.txt
+
+Each 'fail' file would contain a string describing the failure.
+
+
+*** TESTUTIL API
+
+struct tu_config {
+    /** If nonzero, test results are printed to stdout. */
+    int tc_print_results;
+
+    /**
+     * Name of the base results directory (e.g., "test-results").  If null,
+     * results are not written to disk.
+     */
+    const char *tc_results_path;
+
+    /**
+     * Array of flash areas where an ffs file system should be located.  Unused
+     * if run in a simulated environment.  This array must be terminated with a
+     * zero-length area.
+     */
+    const struct ffs_area_desc *tc_area_descs;
+};
+extern struct tu_config tu_config;
+
+Description:
+    The global tu_config struct contains all the testutil package's settings.
+    The struct must be populated before tu_init() is called.
+
+-
+
+int tu_init(void)
+
+Description:
+    Initializes the test framework according to the contents of the tu_config
+    struct.  If run in an embedded environment and the
+    tu_config.tc_results_path and tu_config.tc_area_descs fields are non-null,
+    this function ensures an ffs file system is present within the specified
+    flash areas.  If testutil is using an ffs file system, and no valid ffs
+    file system is detected in the specified region of flash, the region is
+    formatted with a new file system.  This function must be called before any
+    tests are run.
+
+    If, immediately prior to a call to tu_init(), the UUT was restarted via a
+    call to tu_restart(), this function skips all the test cases that have
+    already been executed.  See tu_restart() for details.
+
+    Returns 0 on success; nonzero on failure.
+
+-
+
+TEST_ASSERT(expression)
+TEST_ASSERT(expression, fail_msg, ...)
+
+Description:
+    Asserts that the specified condition is true.  If the expression is true,
+    nothing gets reported.  The expression argument is mandatory; the rest are
+    optional.  The fail_msg argument is a printf format string which specifies
+    how the remaining arguments are parsed.
+
+    If the expression is false, testutil reports the following message:
+
+        |<file>:<line-number>| failed assertion: <expression>
+        <fail_msg>
+
+    If no fail_msg is specified, only the first line gets reported.
+
+    The test case proceeds as normal after this macro is invoked.
+
+Example:
+    TEST_ASSERT(num_blocks == 1024,
+                "expected: 1024 blocks; got: %d", num_blocks);
+
+    On failure, the above assertion would result in a report like the
+    following:
+
+        |ffs_test.c:426| failed assertion: num_blocks == 1024
+        expected: 1024 blocks; got 12
+
+-
+
+TEST_ASSERT_FATAL(expression)
+TEST_ASSERT_FATAL(expression, fail_msg, ...)
+
+Description:
+    These are identical to their TEST_ASSERT counterparts, except that a
+    failure causes the current test case to be aborted.
+
+-
+
+TEST_PASS(msg, ...)
+
+Description:
+    Reports a success result for the current test.  This function is not
+    normally needed, as all successful tests automatically write an empty pass
+    result at completion.  This function is only needed when the success result
+    report should contain text.  The msg argument is a printf format string
+    which specifies how the remaining arguments are parsed.  The result file
+    produced by this function contains the following text:
+
+        |<file>:<line-number>| manual pass
+        <msg>
+
+    After this function is called, the remainder of the test case is not
+    executed.  If the current test has already failed when this macro is
+    invoked, the macro has no effect.
+
+-
+
+testutil_write_data(const char *filename, const uint8_t *data, size_t data_len)
+
+Description:
+    Writes a data file to the current test results directory.  The file's
+    contents are fully specified by the data and data_len arguments.  If a file
+    with the specified name already exists, it is overwritten.  After this
+    function is called, the test case proceeds as normal.
+
+    Data does not get written to stdout; it only gets written to disk.  This
+    function has no effect if testutil is configured to not write results to
+    disk.
+
+-
+
+TEST_CASE(test_case_name) { /* test case code */ }
+
+Description:
+    Defines a test case function with the following type:
+
+        int test_case_name(void)
+
+    The return value is 0 if the test case passed; nonzero if it failed.
+    Generally, the return code is not used.
+
+
+-
+
+TEST_SUITE(test_suite_name) { /* test suite code */ }
+
+Description:
+    Defines a test suite function with the following type:
+
+        int test_suite_name(void)
+
+    The return value is 0 if the test suite passed; nonzero if it failed.
+    Generally, the return code is not used.
+
+-
+
+void tu_restart(void)
+
+Description:
+    This function is used when a system reset is necessary to proceed with
+    testing.  For example, the OS is designed to run forever once started, so a
+    test which creates several OS tasks and then starts the OS has no means of
+    completing.  This function, when called from such a test, gracefully ends
+    the current test case and proceeds to the next test case.
+
+    The particulars of this function depend on whether it is called from a
+    simulated environment.  In a simulated environment, this function uses a
+    longjmp() call to break out of the current test case.
+
+    In a non-simulated environment, this function performs the following
+    procedure:
+
+        1. Record the current test status to the file system.
+        2. Perform a software reset of the UUT.
+        3. Read test status and delete it from the file system.
+        4. Skip all previously completed test cases.
+
+    If this function is called before any results have been reported for the
+    current test case, a "pass" result gets reported.
+
+    Note: after this function performs a software reset, the UUT may not be
+    fully initialized, depending on the test environment.  For example, if the
+    UUT has been set up to run the test image from RAM via JTAG, variables in
+    the .data section will not get properly initialized by the software reset.
+    Proper initialization in this case would require that data be re-read from
+    the image file via an additional run of the JTAG script.
+
+-
+
+ASSERT_IF_TEST(cond)
+
+Description:
+    The effect of this macro depends on whether the TEST macro is defined:
+
+        If defined:     expands to assert().
+        If not defined: expands to nothing.
+
+    This macro is not intended for use within test cases.  Instead, it should
+    be used in normal non-test code to perform computationally-expensive
+    checks.  In non-test builds, the checks do not get performed.
+
+
+***** INDIVIDUAL PACKAGE TESTING
+
+Testing individual packages is performed via the "target test" stack tool
+command.  When testing is done in this manner, the stack tool automatically
+runs the test code on the host machine.  There is no need for an extra stack
+project for producing a test image.
+
+Testing a package in this manner requires a special target that is specific to
+the package.  The target specifies the package to test via the "pkg"
+configuration variable.  The target must not specify a project, or the test
+command will fail.
+
+Below is an example target called testffs that tests the ffs package:
+
+    testffs
+            compiler: sim
+            compiler_def: debug
+            pkg: libs/ffs
+            bsp: hw/bsp/native
+            arch: sim
+            name: testffs
+
+The target specifies the "native" bsp.  This is necessary so that the ffs test
+code can link with the appropriate implementations of the hal functions that it
+depends on.
+
+The test is run by specifying the following stack arguments:
+
+    target test testffs
+
+When the "target test" command is used, the PKG_TEST macro is defined during
+compilation of the package under test.  This is in addition to the TEST macro,
+which is defined during compilation of all packages.
+
+
+***** ISSUES / QUESTIONS
+
+* For individual package tests, the requirement for a separate target for each
+  package may become unwieldy.  Perhaps the stack tool should be modified to
+  allow arbitrary key-value pairs to be specified on the command line.  That
+  way, the target's "pkg" variable could be unset, and the user would specify
+  the package to test when he executes the test command.  This would allow the
+  same target to be used for all packages, e.g.,
+
+        target test testtarget pkg=libs/ffs
+        target test testtarget pkg=libs/os
+
+* Most test frameworks define a lot of extra assertions (e.g., assert_equal(),
+  assert_not_null(), assert_false(), etc).  These don't seem particularly
+  useful to me, so I did not add them.  Typing TEST_ASSERT(x == 5) is no more
+  difficult than TEST_ASSERT_EQUAL(x, 5).  The benefit of the more specific
+  assertions is that they can automatically produce more helpful failure
+  messages.  For example, if TEST_ASSERT_EQUAL(x, 5) fails, the failure message
+  can contain the actual value of x in most cases, whereas a plain
+  TEST_ASSERT() won't automatically log that information.  This didn't seem
+  useful enough to me to justify growing the interface, but I am interested in
+  hearing what others think.
+
+* During testing on embedded devices, the PC software will need some
+  notification when testing is complete, so that it knows when to retrieve the
+  test results.  The testutil package should expose some state that the PC
+  software can poll for this purpose.

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/test/testutil/include/testutil/testutil.h
----------------------------------------------------------------------
diff --git a/test/testutil/include/testutil/testutil.h b/test/testutil/include/testutil/testutil.h
new file mode 100644
index 0000000..de61394
--- /dev/null
+++ b/test/testutil/include/testutil/testutil.h
@@ -0,0 +1,174 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 H_TESTUTIL_
+#define H_TESTUTIL_
+
+#include <inttypes.h>
+#include <setjmp.h>
+
+#include "syscfg/syscfg.h"
+
+/*****************************************************************************
+ * Public declarations                                                       *
+ *****************************************************************************/
+
+typedef void tu_case_init_fn_t(void *arg);
+typedef void tu_case_report_fn_t(char *msg, int msg_len, void *arg);
+typedef void tu_suite_init_fn_t(void *arg);
+typedef void tu_restart_fn_t(void *arg);
+
+struct tu_config {
+    int tc_print_results;
+    int tc_system_assert;
+
+    tu_case_init_fn_t *tc_case_init_cb;
+    void *tc_case_init_arg;
+
+    tu_case_report_fn_t *tc_case_fail_cb;
+    void *tc_case_fail_arg;
+
+    tu_case_report_fn_t *tc_case_pass_cb;
+    void *tc_case_pass_arg;
+
+    tu_suite_init_fn_t *tc_suite_init_cb;
+    void *tc_suite_init_arg;
+
+    tu_restart_fn_t *tc_restart_cb;
+    void *tc_restart_arg;
+};
+
+extern struct tu_config tu_config;
+extern const char *tu_suite_name;
+extern const char *tu_case_name;
+extern int tu_first_idx;
+
+typedef void tu_post_test_fn_t(void *arg);
+
+void tu_suite_set_post_test_cb(tu_post_test_fn_t *cb, void *cb_arg);
+int tu_parse_args(int argc, char **argv);
+int tu_init(void);
+void tu_restart(void);
+
+/*****************************************************************************
+ * Private declarations                                                      *
+ *****************************************************************************/
+
+void tu_suite_complete(void);
+void tu_suite_init(const char *name);
+
+void tu_case_init(const char *name);
+void tu_case_complete(void);
+void tu_case_fail_assert(int fatal, const char *file, int line,
+                         const char *expr, const char *format, ...);
+void tu_case_write_pass_auto(void);
+void tu_case_pass_manual(const char *file, int line,
+                         const char *format, ...);
+void tu_case_post_test(void);
+
+extern int tu_any_failed;
+extern int tu_suite_failed;
+extern int tu_case_reported;
+extern int tu_case_failed;
+extern int tu_case_idx;
+extern jmp_buf tu_case_jb;
+
+#define TEST_SUITE(suite_name)                                                \
+    static void TEST_SUITE_##suite_name(void);                                \
+                                                                              \
+    int                                                                       \
+    suite_name(void)                                                          \
+    {                                                                         \
+        tu_suite_init(#suite_name);                                           \
+        TEST_SUITE_##suite_name();                                            \
+        tu_suite_complete();                                                  \
+                                                                              \
+        return tu_suite_failed;                                               \
+    }                                                                         \
+                                                                              \
+    static void                                                               \
+    TEST_SUITE_##suite_name(void)
+
+/* for creating multiple files with test cases all belonging to the same
+ * suite */
+#define TEST_CASE_DECL(case_name)  int case_name(void);
+
+#define TEST_CASE(case_name)                                                  \
+    static void TEST_CASE_##case_name(void);                                  \
+                                                                              \
+    int                                                                       \
+    case_name(void)                                                           \
+    {                                                                         \
+        if (tu_case_idx >= tu_first_idx) {                                    \
+            tu_case_init(#case_name);                                         \
+                                                                              \
+            if (setjmp(tu_case_jb) == 0) {                                    \
+                TEST_CASE_##case_name();                                      \
+                tu_case_post_test();                                          \
+                tu_case_write_pass_auto();                                    \
+            }                                                                 \
+        }                                                                     \
+                                                                              \
+        tu_case_complete();                                                   \
+                                                                              \
+        return tu_case_failed;                                                \
+    }                                                                         \
+                                                                              \
+    static void                                                               \
+    TEST_CASE_##case_name(void)
+
+#define FIRST_AUX(first, ...) first
+#define FIRST(...) FIRST_AUX(__VA_ARGS__, _)
+
+#define NUM(...) ARG10(__VA_ARGS__, N, N, N, N, N, N, N, N, 1, _)
+#define ARG10(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, ...) a10
+
+#define REST_OR_0(...) REST_OR_0_AUX(NUM(__VA_ARGS__), __VA_ARGS__)
+#define REST_OR_0_AUX(qty, ...) REST_OR_0_AUX_INNER(qty, __VA_ARGS__)
+#define REST_OR_0_AUX_INNER(qty, ...) REST_OR_0_AUX_##qty(__VA_ARGS__)
+#define REST_OR_0_AUX_1(first) 0
+#define REST_OR_0_AUX_N(first, ...) __VA_ARGS__
+
+#define XSTR(s) STR(s)
+#define STR(s) #s
+
+#define TEST_ASSERT_FULL(fatal, expr, ...) do                                 \
+{                                                                             \
+    if (!(expr)) {                                                            \
+        tu_case_fail_assert((fatal), __FILE__, __LINE__, XSTR(expr),          \
+                            __VA_ARGS__);                                     \
+    }                                                                         \
+} while (0)
+
+#define TEST_ASSERT(...)                                                      \
+    TEST_ASSERT_FULL(0, FIRST(__VA_ARGS__), REST_OR_0(__VA_ARGS__))
+
+#define TEST_ASSERT_FATAL(...)                                                \
+    TEST_ASSERT_FULL(1, FIRST(__VA_ARGS__), REST_OR_0(__VA_ARGS__))
+
+#define TEST_PASS(...)                                                        \
+    tu_case_pass_manual(__FILE__, __LINE__, __VA_ARGS__);
+
+#if MYNEWT_VAL(TEST)
+#define ASSERT_IF_TEST(expr) assert(expr)
+#else
+#define ASSERT_IF_TEST(expr)
+#endif
+
+#endif

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/test/testutil/pkg.yml
----------------------------------------------------------------------
diff --git a/test/testutil/pkg.yml b/test/testutil/pkg.yml
new file mode 100644
index 0000000..be8274e
--- /dev/null
+++ b/test/testutil/pkg.yml
@@ -0,0 +1,30 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you 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.
+#
+
+pkg.name: test/testutil
+pkg.description: Support library for implementing unit tests.
+pkg.author: "Apache Mynewt <de...@mynewt.incubator.apache.org>"
+pkg.homepage: "http://mynewt.apache.org/"
+pkg.keywords:
+    - unit
+    - test
+
+pkg.deps:
+    - hw/hal
+    - kernel/os

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/test/testutil/src/arch/cortex_m4/testutil_arch_arm.c
----------------------------------------------------------------------
diff --git a/test/testutil/src/arch/cortex_m4/testutil_arch_arm.c b/test/testutil/src/arch/cortex_m4/testutil_arch_arm.c
new file mode 100644
index 0000000..52ace63
--- /dev/null
+++ b/test/testutil/src/arch/cortex_m4/testutil_arch_arm.c
@@ -0,0 +1,27 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include "hal/hal_system.h"
+#include "testutil_priv.h"
+
+void
+tu_arch_restart(void)
+{
+    system_reset();
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/test/testutil/src/arch/sim/testutil_arch_sim.c
----------------------------------------------------------------------
diff --git a/test/testutil/src/arch/sim/testutil_arch_sim.c b/test/testutil/src/arch/sim/testutil_arch_sim.c
new file mode 100644
index 0000000..2d90501
--- /dev/null
+++ b/test/testutil/src/arch/sim/testutil_arch_sim.c
@@ -0,0 +1,30 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include "os/os.h"
+#include "os/os_arch.h"
+#include "os/os_test.h"
+#include "testutil_priv.h"
+
+void
+tu_arch_restart(void)
+{
+    os_arch_os_stop();
+    tu_case_abort();
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/test/testutil/src/arch/sim/tu_args.c
----------------------------------------------------------------------
diff --git a/test/testutil/src/arch/sim/tu_args.c b/test/testutil/src/arch/sim/tu_args.c
new file mode 100644
index 0000000..75a2900
--- /dev/null
+++ b/test/testutil/src/arch/sim/tu_args.c
@@ -0,0 +1,23 @@
+#include <errno.h>
+#include <unistd.h>
+
+#include "testutil/testutil.h"
+
+int
+tu_parse_args(int argc, char **argv)
+{
+    int ch;
+
+    while ((ch = getopt(argc, argv, "s")) != -1) {
+        switch (ch) {
+        case 's':
+            tu_config.tc_system_assert = 1;
+            break;
+
+        default:
+            return EINVAL;
+        }
+    }
+
+    return 0;
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/test/testutil/src/case.c
----------------------------------------------------------------------
diff --git a/test/testutil/src/case.c b/test/testutil/src/case.c
new file mode 100644
index 0000000..614b142
--- /dev/null
+++ b/test/testutil/src/case.c
@@ -0,0 +1,255 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include <assert.h>
+#include <stdio.h>
+#include <string.h>
+#include <stdarg.h>
+#include "testutil/testutil.h"
+#include "testutil_priv.h"
+
+jmp_buf tu_case_jb;
+int tu_case_reported;
+int tu_case_failed;
+int tu_case_idx;
+
+const char *tu_case_name;
+tu_post_test_fn_t *tu_case_post_test_cb;
+void *tu_case_post_test_cb_arg;
+
+#define TU_CASE_BUF_SZ      1024
+
+static char tu_case_buf[TU_CASE_BUF_SZ];
+static int tu_case_buf_len;
+
+void
+tu_case_abort(void)
+{
+    tu_case_write_pass_auto();
+    longjmp(tu_case_jb, 1);
+}
+
+static int
+tu_case_vappend_buf(const char *format, va_list ap)
+{
+    char *dst;
+    int maxlen;
+    int rc;
+
+    dst = tu_case_buf + tu_case_buf_len;
+    maxlen = TU_CASE_BUF_SZ - tu_case_buf_len;
+
+    rc = vsnprintf(dst, maxlen, format, ap);
+    tu_case_buf_len += rc;
+    if (tu_case_buf_len >= TU_CASE_BUF_SZ) {
+        tu_case_buf_len = TU_CASE_BUF_SZ - 1;
+        return -1;
+    }
+
+    return 0;
+}
+
+static int
+tu_case_append_buf(const char *format, ...)
+{
+    va_list ap;
+    int rc;
+
+    va_start(ap, format);
+    rc = tu_case_vappend_buf(format, ap);
+    va_end(ap);
+
+    return rc;
+}
+
+static void
+tu_case_set_name(const char *name)
+{
+    tu_case_name = name;
+}
+
+void
+tu_case_init(const char *name)
+{
+    tu_case_reported = 0;
+    tu_case_failed = 0;
+
+    tu_case_set_name(name);
+
+    if (tu_config.tc_case_init_cb != NULL) {
+        tu_config.tc_case_init_cb(tu_config.tc_case_init_arg);
+    }
+}
+
+void
+tu_case_complete(void)
+{
+    tu_case_idx++;
+}
+
+void
+tu_case_post_test(void)
+{
+    if (tu_case_post_test_cb != NULL) {
+        tu_case_post_test_cb(tu_case_post_test_cb_arg);
+    }
+}
+
+static void
+tu_case_write_fail_buf(void)
+{
+    tu_case_reported = 1;
+    tu_case_failed = 1;
+    tu_suite_failed = 1;
+    tu_any_failed = 1;
+
+    if (tu_config.tc_print_results) {
+        printf("[FAIL] %s/%s %s", tu_suite_name, tu_case_name, tu_case_buf);
+        fflush(stdout);
+    }
+
+    if (tu_config.tc_case_fail_cb != NULL) {
+        tu_config.tc_case_fail_cb(tu_case_buf, tu_case_buf_len,
+                                  tu_config.tc_case_fail_arg);
+    }
+}
+
+static void
+tu_case_append_file_info(const char *file, int line)
+{
+    int rc;
+
+    rc = tu_case_append_buf("|%s:%d| ", file, line);
+    assert(rc == 0);
+}
+
+static void
+tu_case_append_assert_msg(const char *expr)
+{
+    int rc;
+
+    rc = tu_case_append_buf("failed assertion: %s", expr);
+    assert(rc == 0);
+}
+
+static void
+tu_case_write_pass_buf(void)
+{
+    if (tu_config.tc_print_results) {
+        printf("[pass] %s/%s\n", tu_suite_name, tu_case_name);
+        if (tu_case_buf_len > 0) {
+            printf("%s", tu_case_buf);
+        }
+        fflush(stdout);
+    }
+
+    tu_case_reported = 1;
+
+    if (tu_config.tc_case_pass_cb != NULL) {
+        tu_config.tc_case_pass_cb(tu_case_buf, tu_case_buf_len,
+                                  tu_config.tc_case_pass_arg);
+    }
+}
+
+static void
+tu_case_append_manual_pass_msg(void)
+{
+    int rc;
+
+    rc = tu_case_append_buf("manual pass");
+    assert(rc == 0);
+}
+
+void
+tu_case_write_pass_auto(void)
+{
+    if (!tu_case_reported) {
+        tu_case_buf_len = 0;
+        tu_case_write_pass_buf();
+    }
+}
+
+void
+tu_case_fail_assert(int fatal, const char *file, int line,
+                    const char *expr, const char *format, ...)
+{
+    va_list ap;
+    int rc;
+
+    if (tu_config.tc_system_assert) {
+        assert(0);
+    }
+
+    tu_case_buf_len = 0;
+
+    tu_case_append_file_info(file, line);
+    tu_case_append_assert_msg(expr);
+
+    if (format != NULL) {
+        rc = tu_case_append_buf("\n");
+        assert(rc == 0);
+
+        va_start(ap, format);
+        rc = tu_case_vappend_buf(format, ap);
+        assert(rc == 0);
+        va_end(ap);
+    }
+
+    rc = tu_case_append_buf("\n");
+    assert(rc == 0);
+
+    tu_case_write_fail_buf();
+
+    if (fatal) {
+        tu_case_abort();
+    }
+}
+
+void
+tu_case_pass_manual(const char *file, int line, const char *format, ...)
+{
+    va_list ap;
+    int rc;
+
+    if (tu_case_reported) {
+        return;
+    }
+
+    tu_case_buf_len = 0;
+
+    tu_case_append_file_info(file, line);
+    tu_case_append_manual_pass_msg();
+
+    if (format != NULL) {
+        rc = tu_case_append_buf("\n");
+        assert(rc == 0);
+
+        va_start(ap, format);
+        rc = tu_case_vappend_buf(format, ap);
+        assert(rc == 0);
+        va_end(ap);
+    }
+
+    rc = tu_case_append_buf("\n");
+    assert(rc == 0);
+
+    tu_case_write_pass_buf();
+
+    tu_case_abort();
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/test/testutil/src/suite.c
----------------------------------------------------------------------
diff --git a/test/testutil/src/suite.c b/test/testutil/src/suite.c
new file mode 100644
index 0000000..93ca639
--- /dev/null
+++ b/test/testutil/src/suite.c
@@ -0,0 +1,67 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include <assert.h>
+#include "testutil/testutil.h"
+#include "testutil_priv.h"
+
+const char *tu_suite_name = 0;
+int tu_suite_failed = 0;
+
+static void
+tu_suite_set_name(const char *name)
+{
+    tu_suite_name = name;
+}
+
+/**
+ * Configures a callback that gets executed at the end of each test case in the
+ * current suite.  This is useful when there are some checks that should be
+ * performed at the end of each test (e.g., verify no memory leaks).  This
+ * callback is cleared when the current suite completes.
+ *
+ * @param cb                    The callback to execute at the end of each test
+ *                                  case.
+ * @param cb_arg                An optional argument that gets passed to the
+ *                                  callback.
+ */
+void
+tu_suite_set_post_test_cb(tu_post_test_fn_t *cb, void *cb_arg)
+{
+    tu_case_post_test_cb = cb;
+    tu_case_post_test_cb_arg = cb_arg;
+}
+
+void
+tu_suite_complete(void)
+{
+    tu_suite_set_post_test_cb(NULL, NULL);
+}
+
+void
+tu_suite_init(const char *name)
+{
+    tu_suite_failed = 0;
+
+    tu_suite_set_name(name);
+
+    if (tu_config.tc_suite_init_cb != NULL) {
+        tu_config.tc_suite_init_cb(tu_config.tc_suite_init_arg);
+    }
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/test/testutil/src/testutil.c
----------------------------------------------------------------------
diff --git a/test/testutil/src/testutil.c b/test/testutil/src/testutil.c
new file mode 100644
index 0000000..032a32c
--- /dev/null
+++ b/test/testutil/src/testutil.c
@@ -0,0 +1,50 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ * 
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include <assert.h>
+#include "os/os.h"
+#include "hal/hal_flash.h"
+#include "testutil/testutil.h"
+#include "testutil_priv.h"
+
+struct tu_config tu_config;
+int tu_any_failed;
+int tu_first_idx;
+
+int
+tu_init(void)
+{
+    os_init();
+
+    return 0;
+}
+
+void
+tu_restart(void)
+{
+    tu_case_write_pass_auto();
+
+    tu_first_idx = tu_case_idx + 1;
+
+    if (tu_config.tc_restart_cb != NULL) {
+        tu_config.tc_restart_cb(tu_config.tc_restart_arg);
+    }
+
+    tu_arch_restart();
+}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/6a7432f4/test/testutil/src/testutil_priv.h
----------------------------------------------------------------------
diff --git a/test/testutil/src/testutil_priv.h b/test/testutil/src/testutil_priv.h
new file mode 100644
index 0000000..3f8cb2d
--- /dev/null
+++ b/test/testutil/src/testutil_priv.h
@@ -0,0 +1,34 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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 H_TESTUTIL_PRIV_
+#define H_TESTUTIL_PRIV_
+
+#include <stddef.h>
+#include <inttypes.h>
+
+#include "testutil/testutil.h"
+
+void tu_arch_restart(void);
+void tu_case_abort(void);
+
+extern tu_post_test_fn_t *tu_case_post_test_cb;
+extern void *tu_case_post_test_cb_arg;
+
+#endif


[03/49] incubator-mynewt-core git commit: move cbmem into util/

Posted by st...@apache.org.
move cbmem into util/


Project: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/commit/09aec6cc
Tree: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/tree/09aec6cc
Diff: http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/diff/09aec6cc

Branch: refs/heads/develop
Commit: 09aec6cc8fb99d9feec93b94b8c455d28d27b877
Parents: 54fbe73
Author: Sterling Hughes <st...@apache.org>
Authored: Wed Sep 28 16:56:03 2016 -0700
Committer: Sterling Hughes <st...@apache.org>
Committed: Wed Sep 28 18:32:22 2016 -0700

----------------------------------------------------------------------
 libs/util/include/util/cbmem.h   |  66 --------
 libs/util/src/cbmem.c            | 277 ----------------------------------
 libs/util/test/src/cbmem_test.c  | 176 ---------------------
 sys/log/include/log/log.h        |   2 +-
 sys/log/src/log_cbmem.c          |   2 +-
 sys/log/src/log_console.c        |   2 +-
 sys/log/src/log_shell.c          |  20 +--
 util/cbmem/test/src/cbmem_test.c |  36 ++---
 8 files changed, 31 insertions(+), 550 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/09aec6cc/libs/util/include/util/cbmem.h
----------------------------------------------------------------------
diff --git a/libs/util/include/util/cbmem.h b/libs/util/include/util/cbmem.h
deleted file mode 100644
index 42decfb..0000000
--- a/libs/util/include/util/cbmem.h
+++ /dev/null
@@ -1,66 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you 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 __UTIL_CBMEM_H__ 
-#define __UTIL_CBMEM_H__
-
-#include <os/os.h>
-
-struct cbmem_entry_hdr {
-    uint16_t ceh_len;
-    uint16_t ceh_flags;
-} __attribute__((packed));
-
-struct cbmem {
-    struct os_mutex c_lock;
-
-    struct cbmem_entry_hdr *c_entry_start;
-    struct cbmem_entry_hdr *c_entry_end;
-    uint8_t *c_buf;
-    uint8_t *c_buf_end;
-    uint8_t *c_buf_cur_end;
-};
-
-struct cbmem_iter {
-    struct cbmem_entry_hdr *ci_start;
-    struct cbmem_entry_hdr *ci_cur;
-    struct cbmem_entry_hdr *ci_end;
-};
-
-#define CBMEM_ENTRY_SIZE(__p) (sizeof(struct cbmem_entry_hdr) \
-        + ((struct cbmem_entry_hdr *) (__p))->ceh_len)
-#define CBMEM_ENTRY_NEXT(__p) ((struct cbmem_entry_hdr *) \
-        ((uint8_t *) (__p) + CBMEM_ENTRY_SIZE(__p)))
-
-typedef int (*cbmem_walk_func_t)(struct cbmem *, struct cbmem_entry_hdr *, 
-        void *arg);
-
-int cbmem_lock_acquire(struct cbmem *cbmem);
-int cbmem_lock_release(struct cbmem *cbmem);
-int cbmem_init(struct cbmem *cbmem, void *buf, uint32_t buf_len);
-int cbmem_append(struct cbmem *cbmem, void *data, uint16_t len);
-void cbmem_iter_start(struct cbmem *cbmem, struct cbmem_iter *iter);
-struct cbmem_entry_hdr *cbmem_iter_next(struct cbmem *cbmem, 
-        struct cbmem_iter *iter);
-int cbmem_read(struct cbmem *cbmem, struct cbmem_entry_hdr *hdr, void *buf, 
-        uint16_t off, uint16_t len);
-int cbmem_walk(struct cbmem *cbmem, cbmem_walk_func_t walk_func, void *arg);
-
-int cbmem_flush(struct cbmem *);
-
-#endif /* __UTIL_CBMEM_H__ */

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/09aec6cc/libs/util/src/cbmem.c
----------------------------------------------------------------------
diff --git a/libs/util/src/cbmem.c b/libs/util/src/cbmem.c
deleted file mode 100644
index 05051ae..0000000
--- a/libs/util/src/cbmem.c
+++ /dev/null
@@ -1,277 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-#include <os/os.h>
-#include <string.h>
-
-#include "util/cbmem.h" 
-
-
-int 
-cbmem_init(struct cbmem *cbmem, void *buf, uint32_t buf_len)
-{
-    os_mutex_init(&cbmem->c_lock);
-
-    memset(cbmem, 0, sizeof(*cbmem));
-    cbmem->c_buf = buf;
-    cbmem->c_buf_end = buf + buf_len;
-
-    return (0);
-}
-
-int 
-cbmem_lock_acquire(struct cbmem *cbmem) 
-{
-    int rc;
-
-    if (!os_started()) {
-        return (0);
-    }
-
-    rc = os_mutex_pend(&cbmem->c_lock, OS_WAIT_FOREVER);
-    if (rc != 0) {
-        goto err;
-    }
-
-    return (0);
-err:
-    return (rc);
-}
-
-int 
-cbmem_lock_release(struct cbmem *cbmem)
-{
-    int rc;
-
-    if (!os_started()) {
-        return (0);
-    }
-
-    rc = os_mutex_release(&cbmem->c_lock);
-    if (rc != 0) {
-        goto err;
-    }
-
-    return (0);
-err:
-    return (rc);
-}
-
-
-int 
-cbmem_append(struct cbmem *cbmem, void *data, uint16_t len)
-{
-    struct cbmem_entry_hdr *dst;
-    uint8_t *start;
-    uint8_t *end;
-    int rc;
-
-    rc = cbmem_lock_acquire(cbmem);
-    if (rc != 0) {
-        goto err;
-    }
-
-    if (cbmem->c_entry_end) {
-        dst = CBMEM_ENTRY_NEXT(cbmem->c_entry_end);
-    } else {
-        dst = (struct cbmem_entry_hdr *) cbmem->c_buf;
-    }
-    end = (uint8_t *) dst + len + sizeof(*dst);
-
-    /* If this item would take us past the end of this buffer, then adjust 
-     * the item to the beginning of the buffer.
-     */
-    if (end > cbmem->c_buf_end) {
-        cbmem->c_buf_cur_end = (uint8_t *) dst;
-        dst = (struct cbmem_entry_hdr *) cbmem->c_buf;
-        end = (uint8_t *) dst + len + sizeof(*dst);
-        if ((uint8_t *) cbmem->c_entry_start >= cbmem->c_buf_cur_end) {
-            cbmem->c_entry_start = (struct cbmem_entry_hdr *) cbmem->c_buf;
-        }
-    }
-
-    /* If the destination is prior to the start, and would overrwrite the 
-     * start of the buffer, move start forward until you don't overwrite it
-     * anymore.
-     */
-    start = (uint8_t *) cbmem->c_entry_start;
-    if (start && (uint8_t *) dst < start + CBMEM_ENTRY_SIZE(start) && 
-            end > start) {
-        while (start < end) {
-            start = (uint8_t *) CBMEM_ENTRY_NEXT(start);
-            if (start == cbmem->c_buf_cur_end) {
-                start = cbmem->c_buf;
-                break;
-            }
-        }
-        cbmem->c_entry_start = (struct cbmem_entry_hdr *) start;
-    }
-
-    /* Copy the entry into the log 
-     */
-    dst->ceh_len = len;
-    memcpy((uint8_t *) dst + sizeof(*dst), data, len);
-
-    cbmem->c_entry_end = dst;
-    if (!cbmem->c_entry_start) {
-        cbmem->c_entry_start = dst;
-    }
-
-    rc = cbmem_lock_release(cbmem);
-    if (rc != 0) {
-        goto err;
-    }
-
-    return (0);
-err:
-    return (-1);
-}
-
-void 
-cbmem_iter_start(struct cbmem *cbmem, struct cbmem_iter *iter)
-{
-    iter->ci_start = cbmem->c_entry_start;
-    iter->ci_cur = cbmem->c_entry_start;
-    iter->ci_end = cbmem->c_entry_end;
-}
-
-struct cbmem_entry_hdr *
-cbmem_iter_next(struct cbmem *cbmem, struct cbmem_iter *iter)
-{
-    struct cbmem_entry_hdr *hdr;
-
-    if (iter->ci_start > iter->ci_end) {
-        hdr = iter->ci_cur;
-        iter->ci_cur = CBMEM_ENTRY_NEXT(iter->ci_cur);
-
-        if ((uint8_t *) iter->ci_cur >= cbmem->c_buf_cur_end) {
-            iter->ci_cur = (struct cbmem_entry_hdr *) cbmem->c_buf;
-            iter->ci_start = (struct cbmem_entry_hdr *) cbmem->c_buf;
-        }
-    } else {
-        hdr = iter->ci_cur;
-        if (!iter->ci_cur) {
-            goto err;
-        }
-
-        if (hdr == CBMEM_ENTRY_NEXT(iter->ci_end)) {
-            hdr = NULL;
-        } else {
-            iter->ci_cur = CBMEM_ENTRY_NEXT(iter->ci_cur);
-        }
-    }
-
-err:
-    return (hdr);
-}
-
-int
-cbmem_flush(struct cbmem *cbmem)
-{
-    int rc;
-
-    rc = cbmem_lock_acquire(cbmem);
-    if (rc != 0) {
-        goto err;
-    }
-
-    cbmem->c_entry_start = NULL;
-    cbmem->c_entry_end = NULL;
-    cbmem->c_buf_cur_end = NULL;
-
-    rc = cbmem_lock_release(cbmem);
-    if (rc != 0) {
-        goto err;
-    }
-
-    return (0);
-err:
-    return (rc);
-}
-
-int 
-cbmem_read(struct cbmem *cbmem, struct cbmem_entry_hdr *hdr, void *buf, 
-        uint16_t off, uint16_t len)
-{
-    int rc;
-
-    rc = cbmem_lock_acquire(cbmem);
-    if (rc != 0) {
-        goto err;
-    }
-
-    /* Only read the maximum number of bytes, if we exceed that, 
-     * truncate the read.
-     */
-    if (off + len > hdr->ceh_len) {
-        len = hdr->ceh_len - off;
-    }
-
-    if (off > hdr->ceh_len) {
-        rc = -1;
-        cbmem_lock_release(cbmem);
-        goto err;
-    }
-
-    memcpy(buf, (uint8_t *) hdr + sizeof(*hdr) + off, len);
-
-    rc = cbmem_lock_release(cbmem);
-    if (rc != 0) {
-        goto err;
-    }
-
-    return (len);
-err:
-    return (-1);
-}
-
-int 
-cbmem_walk(struct cbmem *cbmem, cbmem_walk_func_t walk_func, void *arg)
-{
-    struct cbmem_entry_hdr *hdr;
-    struct cbmem_iter iter;
-    int rc;
-
-    rc = cbmem_lock_acquire(cbmem);
-    if (rc != 0) {
-        goto err;
-    }
-
-    cbmem_iter_start(cbmem, &iter);
-    while (1) {
-        hdr = cbmem_iter_next(cbmem, &iter);
-        if (hdr == NULL) {
-            break;
-        }
-
-        rc = walk_func(cbmem, hdr, arg);
-        if (rc == 1) {
-            break;
-        }
-    }
-
-    rc = cbmem_lock_release(cbmem);
-    if (rc != 0) {
-        goto err;
-    }
-
-    return (0);
-err:
-    return (rc);
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/09aec6cc/libs/util/test/src/cbmem_test.c
----------------------------------------------------------------------
diff --git a/libs/util/test/src/cbmem_test.c b/libs/util/test/src/cbmem_test.c
deleted file mode 100644
index b486334..0000000
--- a/libs/util/test/src/cbmem_test.c
+++ /dev/null
@@ -1,176 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- * 
- *  http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-#include <stdio.h>
-#include <string.h>
-
-#include "testutil/testutil.h"
-#include "util/cbmem.h" 
-
-#define CBMEM1_BUF_SIZE (64 * 1024)
-
-struct cbmem cbmem1;
-uint8_t cbmem1_buf[CBMEM1_BUF_SIZE];
-uint8_t cbmem1_entry[1024];
-
-/*
- * Things to test.
- *
- * - Wrap of the circular buffer.  
- * - Reading through all entries.
- */
-
-static void
-setup_cbmem1(void)
-{
-    int i;
-    int rc;
-
-    rc = cbmem_init(&cbmem1, cbmem1_buf, CBMEM1_BUF_SIZE);
-    TEST_ASSERT_FATAL(rc == 0, "cbmem_init() failed, non-zero RC = %d", rc);
-
-    memset(cbmem1_entry, 0xff, sizeof(cbmem1_entry));
-
-    /* Insert 65 1024 entries, and overflow buffer.  
-     * This should overflow two entries, because the buffer is sized for 64 
-     * entries, and then the headers themselves will eat into one of the entries, 
-     * so there should be a total of 63 entries.
-     * Ensure no data corruption.
-     */
-    for (i = 0; i < 65; i++) {
-        cbmem1_entry[0] = i;
-        rc = cbmem_append(&cbmem1, cbmem1_entry, sizeof(cbmem1_entry));
-        TEST_ASSERT_FATAL(rc == 0, "Could not append entry %d, rc = %d", i, rc);
-    }
-}
-
-static int 
-cbmem_test_case_1_walk(struct cbmem *cbmem, struct cbmem_entry_hdr *hdr, 
-        void *arg)
-{
-    uint8_t expected;
-    uint8_t actual;
-    int rc;
-
-    expected = *(uint8_t *) arg;
-
-    rc = cbmem_read(cbmem, hdr, &actual, 0, sizeof(actual));
-    TEST_ASSERT_FATAL(rc == 1, "Couldn't read 1 byte from cbmem");
-    TEST_ASSERT_FATAL(actual == expected, 
-            "Actual doesn't equal expected (%d = %d)", actual, expected);
-
-    *(uint8_t *) arg = ++expected;
-
-    return (0);
-}
-
-TEST_CASE(cbmem_test_case_1) 
-{
-    int i;
-    int rc;
-
-    /* i starts at 2, for the 2 overwritten entries. */
-    i = 2;
-    rc = cbmem_walk(&cbmem1, cbmem_test_case_1_walk, &i);
-    TEST_ASSERT_FATAL(rc == 0, "Could not walk cbmem tree!  rc = %d", rc);
-    TEST_ASSERT_FATAL(i == 65, 
-            "Did not go through every element of walk, %d processed", i - 2);
-
-}
-
-TEST_CASE(cbmem_test_case_2)
-{
-    struct cbmem_entry_hdr *hdr;
-    struct cbmem_iter iter;
-    uint8_t i;
-    uint8_t val;
-    int rc;
-
-    i = 2;
-    cbmem_iter_start(&cbmem1, &iter);
-    while (1) {
-        hdr = cbmem_iter_next(&cbmem1, &iter);
-        if (hdr == NULL) {
-            break;
-        }
-
-        rc = cbmem_read(&cbmem1, hdr, &val, 0, sizeof(val));
-        TEST_ASSERT_FATAL(rc == 1, "Couldn't read 1 byte from cbmem");
-        TEST_ASSERT_FATAL(val == i, "Entry index does not match %d vs %d", 
-                val, i);
-
-        i++;
-    }
-
-    /* i starts at 2, for the 2 overwritten entries */
-    TEST_ASSERT_FATAL(i == 65, 
-            "Did not iterate through all 63 elements of CBMEM1, processed %d", 
-            i - 2);
-}
-
-TEST_CASE(cbmem_test_case_3)
-{
-    struct cbmem_entry_hdr *hdr;
-    struct cbmem_iter iter;
-    uint16_t off;
-    uint16_t len;
-    uint8_t buf[128];
-    int i;
-    int rc;
-
-    i = 0;
-    cbmem_iter_start(&cbmem1, &iter);
-    while (1) {
-        hdr = cbmem_iter_next(&cbmem1, &iter);
-        if (hdr == NULL) {
-            break;
-        }
-        
-        /* first ensure we can read the entire entry */
-        off = 0;
-        len = 0;
-        while (1) {
-            rc = cbmem_read(&cbmem1, hdr, buf, off, sizeof(buf));
-            TEST_ASSERT_FATAL(rc >= 0,
-                    "Error reading from buffer rc=%d, off=%d,len=%d", rc, off, 
-                    sizeof(buf));
-            if (rc == 0) {
-                break;
-            }
-            off += rc;
-            len += rc;
-        }
-        TEST_ASSERT_FATAL(len == 1024, 
-                "Couldn't read full entry, expected %d got %d", 1024, len);
-        i++;
-
-        /* go apesh*t, and read data out of bounds, see what we get. */
-        rc = cbmem_read(&cbmem1, hdr, buf, 2048, sizeof(buf));
-        TEST_ASSERT_FATAL(rc < 0, 
-                "Reading invalid should return error, instead %d returned.",
-                rc);
-    }
-}
-
-TEST_SUITE(cbmem_test_suite)
-{
-    setup_cbmem1();
-    cbmem_test_case_1();
-    cbmem_test_case_2();
-    cbmem_test_case_3();
-}

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/09aec6cc/sys/log/include/log/log.h
----------------------------------------------------------------------
diff --git a/sys/log/include/log/log.h b/sys/log/include/log/log.h
index 48deb0b..d02c44d 100644
--- a/sys/log/include/log/log.h
+++ b/sys/log/include/log/log.h
@@ -21,7 +21,7 @@
 
 #include "syscfg/syscfg.h"
 #include "log/ignore.h"
-#include "util/cbmem.h"
+#include "cbmem/cbmem.h"
 
 #include <os/queue.h>
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/09aec6cc/sys/log/src/log_cbmem.c
----------------------------------------------------------------------
diff --git a/sys/log/src/log_cbmem.c b/sys/log/src/log_cbmem.c
index 0caa17b..4efafc8 100644
--- a/sys/log/src/log_cbmem.c
+++ b/sys/log/src/log_cbmem.c
@@ -17,7 +17,7 @@
  * under the License.
  */
 #include <os/os.h>
-#include <util/cbmem.h>
+#include <cbmem/cbmem.h>
 #include "log/log.h"
 
 static int

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/09aec6cc/sys/log/src/log_console.c
----------------------------------------------------------------------
diff --git a/sys/log/src/log_console.c b/sys/log/src/log_console.c
index 73814da..5fb2065 100644
--- a/sys/log/src/log_console.c
+++ b/sys/log/src/log_console.c
@@ -18,7 +18,7 @@
  */
 
 #include <os/os.h>
-#include <util/cbmem.h>
+#include <cbmem/cbmem.h>
 #include <console/console.h>
 #include "log/log.h"
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/09aec6cc/sys/log/src/log_shell.c
----------------------------------------------------------------------
diff --git a/sys/log/src/log_shell.c b/sys/log/src/log_shell.c
index 7188b5d..f7503f7 100644
--- a/sys/log/src/log_shell.c
+++ b/sys/log/src/log_shell.c
@@ -6,7 +6,7 @@
  * to you 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,
@@ -19,7 +19,7 @@
 
 #include "syscfg/syscfg.h"
 
-/* This whole file is conditionally compiled based on whether the 
+/* This whole file is conditionally compiled based on whether the
  * log package is configured to use the shell (MYNEWT_VAL(LOG_CLI)).
  */
 
@@ -29,20 +29,20 @@
 #include <string.h>
 
 #include "os/os.h"
-#include "util/cbmem.h"
+#include "cbmem/cbmem.h"
 #include "log/log.h"
 #include "shell/shell.h"
 #include "console/console.h"
 
-static int 
-shell_log_dump_entry(struct log *log, void *arg, void *dptr, uint16_t len) 
+static int
+shell_log_dump_entry(struct log *log, void *arg, void *dptr, uint16_t len)
 {
     struct log_entry_hdr ueh;
     char data[128];
     int dlen;
     int rc;
 
-    rc = log_read(log, dptr, &ueh, 0, sizeof(ueh)); 
+    rc = log_read(log, dptr, &ueh, 0, sizeof(ueh));
     if (rc != sizeof(ueh)) {
         goto err;
     }
@@ -55,8 +55,8 @@ shell_log_dump_entry(struct log *log, void *arg, void *dptr, uint16_t len)
     }
     data[rc] = 0;
 
-    /* XXX: This is evil.  newlib printf does not like 64-bit 
-     * values, and this causes memory to be overwritten.  Cast to a 
+    /* XXX: This is evil.  newlib printf does not like 64-bit
+     * values, and this causes memory to be overwritten.  Cast to a
      * unsigned 32-bit value for now.
      */
     console_printf("[%lu] %s\n", (unsigned long) ueh.ue_ts, data);
@@ -66,7 +66,7 @@ err:
     return (rc);
 }
 
-int 
+int
 shell_log_dump_all_cmd(int argc, char **argv)
 {
     struct log *log;
@@ -96,6 +96,6 @@ err:
     return (rc);
 }
 
-#endif 
+#endif
 
 

http://git-wip-us.apache.org/repos/asf/incubator-mynewt-core/blob/09aec6cc/util/cbmem/test/src/cbmem_test.c
----------------------------------------------------------------------
diff --git a/util/cbmem/test/src/cbmem_test.c b/util/cbmem/test/src/cbmem_test.c
index b486334..755908c 100644
--- a/util/cbmem/test/src/cbmem_test.c
+++ b/util/cbmem/test/src/cbmem_test.c
@@ -6,7 +6,7 @@
  * to you 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,
@@ -20,7 +20,7 @@
 #include <string.h>
 
 #include "testutil/testutil.h"
-#include "util/cbmem.h" 
+#include "cbmem/cbmem.h"
 
 #define CBMEM1_BUF_SIZE (64 * 1024)
 
@@ -31,7 +31,7 @@ uint8_t cbmem1_entry[1024];
 /*
  * Things to test.
  *
- * - Wrap of the circular buffer.  
+ * - Wrap of the circular buffer.
  * - Reading through all entries.
  */
 
@@ -46,9 +46,9 @@ setup_cbmem1(void)
 
     memset(cbmem1_entry, 0xff, sizeof(cbmem1_entry));
 
-    /* Insert 65 1024 entries, and overflow buffer.  
-     * This should overflow two entries, because the buffer is sized for 64 
-     * entries, and then the headers themselves will eat into one of the entries, 
+    /* Insert 65 1024 entries, and overflow buffer.
+     * This should overflow two entries, because the buffer is sized for 64
+     * entries, and then the headers themselves will eat into one of the entries,
      * so there should be a total of 63 entries.
      * Ensure no data corruption.
      */
@@ -59,8 +59,8 @@ setup_cbmem1(void)
     }
 }
 
-static int 
-cbmem_test_case_1_walk(struct cbmem *cbmem, struct cbmem_entry_hdr *hdr, 
+static int
+cbmem_test_case_1_walk(struct cbmem *cbmem, struct cbmem_entry_hdr *hdr,
         void *arg)
 {
     uint8_t expected;
@@ -71,7 +71,7 @@ cbmem_test_case_1_walk(struct cbmem *cbmem, struct cbmem_entry_hdr *hdr,
 
     rc = cbmem_read(cbmem, hdr, &actual, 0, sizeof(actual));
     TEST_ASSERT_FATAL(rc == 1, "Couldn't read 1 byte from cbmem");
-    TEST_ASSERT_FATAL(actual == expected, 
+    TEST_ASSERT_FATAL(actual == expected,
             "Actual doesn't equal expected (%d = %d)", actual, expected);
 
     *(uint8_t *) arg = ++expected;
@@ -79,7 +79,7 @@ cbmem_test_case_1_walk(struct cbmem *cbmem, struct cbmem_entry_hdr *hdr,
     return (0);
 }
 
-TEST_CASE(cbmem_test_case_1) 
+TEST_CASE(cbmem_test_case_1)
 {
     int i;
     int rc;
@@ -88,7 +88,7 @@ TEST_CASE(cbmem_test_case_1)
     i = 2;
     rc = cbmem_walk(&cbmem1, cbmem_test_case_1_walk, &i);
     TEST_ASSERT_FATAL(rc == 0, "Could not walk cbmem tree!  rc = %d", rc);
-    TEST_ASSERT_FATAL(i == 65, 
+    TEST_ASSERT_FATAL(i == 65,
             "Did not go through every element of walk, %d processed", i - 2);
 
 }
@@ -111,15 +111,15 @@ TEST_CASE(cbmem_test_case_2)
 
         rc = cbmem_read(&cbmem1, hdr, &val, 0, sizeof(val));
         TEST_ASSERT_FATAL(rc == 1, "Couldn't read 1 byte from cbmem");
-        TEST_ASSERT_FATAL(val == i, "Entry index does not match %d vs %d", 
+        TEST_ASSERT_FATAL(val == i, "Entry index does not match %d vs %d",
                 val, i);
 
         i++;
     }
 
     /* i starts at 2, for the 2 overwritten entries */
-    TEST_ASSERT_FATAL(i == 65, 
-            "Did not iterate through all 63 elements of CBMEM1, processed %d", 
+    TEST_ASSERT_FATAL(i == 65,
+            "Did not iterate through all 63 elements of CBMEM1, processed %d",
             i - 2);
 }
 
@@ -140,14 +140,14 @@ TEST_CASE(cbmem_test_case_3)
         if (hdr == NULL) {
             break;
         }
-        
+
         /* first ensure we can read the entire entry */
         off = 0;
         len = 0;
         while (1) {
             rc = cbmem_read(&cbmem1, hdr, buf, off, sizeof(buf));
             TEST_ASSERT_FATAL(rc >= 0,
-                    "Error reading from buffer rc=%d, off=%d,len=%d", rc, off, 
+                    "Error reading from buffer rc=%d, off=%d,len=%d", rc, off,
                     sizeof(buf));
             if (rc == 0) {
                 break;
@@ -155,13 +155,13 @@ TEST_CASE(cbmem_test_case_3)
             off += rc;
             len += rc;
         }
-        TEST_ASSERT_FATAL(len == 1024, 
+        TEST_ASSERT_FATAL(len == 1024,
                 "Couldn't read full entry, expected %d got %d", 1024, len);
         i++;
 
         /* go apesh*t, and read data out of bounds, see what we get. */
         rc = cbmem_read(&cbmem1, hdr, buf, 2048, sizeof(buf));
-        TEST_ASSERT_FATAL(rc < 0, 
+        TEST_ASSERT_FATAL(rc < 0,
                 "Reading invalid should return error, instead %d returned.",
                 rc);
     }