utils: add to PDK
authorJacob Stiffler <j-stiffler@ti.com>
Fri, 1 Nov 2019 18:54:16 +0000 (14:54 -0400)
committerJacob Stiffler <j-stiffler@ti.com>
Fri, 1 Nov 2019 18:54:16 +0000 (14:54 -0400)
Development of utils has been relocated here from:
* Repo: https://git.ti.com/keystone-rtos/utils
* Branch: master
* Commit ID: dbd2683d80326165d078282b1ef7dce44667e972

Signed-off-by: Jacob Stiffler <j-stiffler@ti.com>
68 files changed:
packages/ti/utils/profiling/.gitignore [new file with mode: 0644]
packages/ti/utils/profiling/README.dox [new file with mode: 0644]
packages/ti/utils/profiling/Settings.xdc.xdt [new file with mode: 0644]
packages/ti/utils/profiling/build/armv7/ti.utils.aa15fg.mk [new file with mode: 0644]
packages/ti/utils/profiling/build/armv7/ti.utils.profiling.aa15fg.mk [new file with mode: 0644]
packages/ti/utils/profiling/build/buildlib.xs [new file with mode: 0644]
packages/ti/utils/profiling/build/c66/ti.utils.ae66.mk [new file with mode: 0644]
packages/ti/utils/profiling/build/c66/ti.utils.ae66e.mk [new file with mode: 0644]
packages/ti/utils/profiling/build/c66/ti.utils.profiling.ae66.mk [new file with mode: 0644]
packages/ti/utils/profiling/build/c66/ti.utils.profiling.ae66e.mk [new file with mode: 0644]
packages/ti/utils/profiling/build/m4/ti.utils.aem4.mk [new file with mode: 0644]
packages/ti/utils/profiling/build/m4/ti.utils.profiling.aem4.mk [new file with mode: 0644]
packages/ti/utils/profiling/build/makefile_profile.mk [new file with mode: 0644]
packages/ti/utils/profiling/config.bld [new file with mode: 0755]
packages/ti/utils/profiling/config_mk.bld [new file with mode: 0755]
packages/ti/utils/profiling/docs/Module.xs [new file with mode: 0644]
packages/ti/utils/profiling/docs/ReleaseNotes_Utils.doc [new file with mode: 0644]
packages/ti/utils/profiling/docs/ReleaseNotes_Utils.pdf [new file with mode: 0644]
packages/ti/utils/profiling/docs/Utils_SoftwareManifest.doc [new file with mode: 0644]
packages/ti/utils/profiling/docs/Utils_SoftwareManifest.pdf [new file with mode: 0644]
packages/ti/utils/profiling/docs/doxyfile.xdt [new file with mode: 0644]
packages/ti/utils/profiling/docs/tifooter.htm [new file with mode: 0644]
packages/ti/utils/profiling/docs/tiheader.htm [new file with mode: 0644]
packages/ti/utils/profiling/docs/tilogo.gif [new file with mode: 0644]
packages/ti/utils/profiling/docs/titagline.gif [new file with mode: 0644]
packages/ti/utils/profiling/filters/Module.xs [new file with mode: 0644]
packages/ti/utils/profiling/filters/gpio_filter.txt [new file with mode: 0644]
packages/ti/utils/profiling/filters/i2c_filter.txt [new file with mode: 0644]
packages/ti/utils/profiling/filters/icss_emac_filter.txt [new file with mode: 0644]
packages/ti/utils/profiling/filters/mmcsd_filter.txt [new file with mode: 0644]
packages/ti/utils/profiling/filters/pruss_filter.txt [new file with mode: 0644]
packages/ti/utils/profiling/filters/spi_filter.txt [new file with mode: 0644]
packages/ti/utils/profiling/filters/uart_filter.txt [new file with mode: 0644]
packages/ti/utils/profiling/makefile [new file with mode: 0644]
packages/ti/utils/profiling/package.bld [new file with mode: 0644]
packages/ti/utils/profiling/package.xdc [new file with mode: 0644]
packages/ti/utils/profiling/package.xs [new file with mode: 0644]
packages/ti/utils/profiling/profilingHooks.h [new file with mode: 0644]
packages/ti/utils/profiling/profiling_component.mk [new file with mode: 0644]
packages/ti/utils/profiling/profiling_osal.h [new file with mode: 0644]
packages/ti/utils/profiling/profilingver.h [new file with mode: 0644]
packages/ti/utils/profiling/profilingver.h.xdt [new file with mode: 0644]
packages/ti/utils/profiling/scripts/Module.xs [new file with mode: 0644]
packages/ti/utils/profiling/scripts/decodeProfileDump.py [new file with mode: 0644]
packages/ti/utils/profiling/scripts/memXfer.js [new file with mode: 0644]
packages/ti/utils/profiling/scripts/readelf.py [new file with mode: 0644]
packages/ti/utils/profiling/src/Module.xs [new file with mode: 0644]
packages/ti/utils/profiling/src/profilingHooksArmV7_A.c [new file with mode: 0644]
packages/ti/utils/profiling/src/profilingHooksArmV7_AAssembly.asm [new file with mode: 0644]
packages/ti/utils/profiling/src/profilingHooksArmV8.c [new file with mode: 0644]
packages/ti/utils/profiling/src/profilingHooksC66.c [new file with mode: 0644]
packages/ti/utils/profiling/src/profilingHooksM4.c [new file with mode: 0644]
packages/ti/utils/profiling/src/profilingHooksR5.c [new file with mode: 0644]
packages/ti/utils/trace/.gitignore [new file with mode: 0644]
packages/ti/utils/trace/Settings.xdc.xdt [new file with mode: 0644]
packages/ti/utils/trace/build/buildlib.xs [new file with mode: 0644]
packages/ti/utils/trace/build/makefile_trace.mk [new file with mode: 0644]
packages/ti/utils/trace/config.bld [new file with mode: 0644]
packages/ti/utils/trace/config_mk.bld [new file with mode: 0644]
packages/ti/utils/trace/makefile [new file with mode: 0644]
packages/ti/utils/trace/package.bld [new file with mode: 0644]
packages/ti/utils/trace/package.xdc [new file with mode: 0644]
packages/ti/utils/trace/package.xs [new file with mode: 0644]
packages/ti/utils/trace/trace.h [new file with mode: 0644]
packages/ti/utils/trace/trace.h.xdt [new file with mode: 0644]
packages/ti/utils/trace/trace_component.mk [new file with mode: 0644]
packages/ti/utils/trace/tracever.h [new file with mode: 0644]
packages/ti/utils/trace/tracever.h.xdt [new file with mode: 0644]

diff --git a/packages/ti/utils/profiling/.gitignore b/packages/ti/utils/profiling/.gitignore
new file mode 100644 (file)
index 0000000..0033dd8
--- /dev/null
@@ -0,0 +1,20 @@
+*.swp
+*~
+*.bak
+*.orig
+.dlls
+.executables
+.interfaces
+.libraries
+.xdcenv.mak
+Settings.h
+Settings.xdc
+docs/Doxyfile
+docs/doxygen/
+docs/rmDocs.chm
+lib/
+/makefile
+package.mak
+package/
+packages/
+install/
diff --git a/packages/ti/utils/profiling/README.dox b/packages/ti/utils/profiling/README.dox
new file mode 100644 (file)
index 0000000..c6fa347
--- /dev/null
@@ -0,0 +1,229 @@
+/*
+ * This README contains instructions for using the profiling tools both
+ * manually using Code Composer Studio 6 and automatically using the bundled
+ * Debug Scripting Server tools. Scroll down to see the latter.
+ */
+/*!
+  @page profCCS Project Profiling in CCS
+  @brief This guide steps through the manual profiling pipeline using the TI
+  Utils library and CCS
+  ##Introduction##
+
+  These instructions are for manually compiling and benchmarking the included
+  LLD example projects in the TI Processor Development Kit. This benchmark tool
+  uses the hardware clock of the PMU to measure the length of each task in
+  processor cycles with minimal overhead. This guide and scripts were written
+  for the AM5728 RTOS platform, but use standard C programming hooks that
+  may be adapted for any platform and/or processor architecture.
+
+  Notes:
+  - Functions with more than one entry point may not always map correctly with
+  their symbols and in the trace. This does not affect their child or parent
+  functions.
+  - Functions that are still on the stack at the breakpoint will be considered
+  closed at the last recorded timestamp for continuity.
+  - BIOS functions that are not referenced in the project or its library are
+  not accounted for by instrumentation and will not appear in the report.
+  - The python script used to tabulate the instrumentation logs depends on the
+  file readelf.py, which must be in the same directory.
+  - Depending on your optimization level, some functions may be optimized out
+  and/or may not appear on certain platforms, including:
+      - Empty or single-line functions
+      - ti_sysbios_* functions
+      - SemaphoreP_* functions
+
+  ###Part I: Project Setup###
+  -# Download and install the TI RTOS Processor SDK for AM572x or the desired
+  product.
+           - The installer for the AM572x can be found at: http://www.ti.com/tool/PROCESSOR-SDK-AM572X. All other platform SDKs can be found at: http://www.ti.com/lsds/ti/tools-software/sw_portal.page
+  -# In CCS. select the desired project in the Project Explorer, and open its
+  *.cfg file in a text editor.
+  -# Any LLDs in use must have be set to enable profiling in order to be
+  profiled at runtime. This is done by setting enableProfiling to true in the
+  LLD package. For example, in GPIO, this would be:
+  @code
+  /* Load the GPIO package */
+  var Gpio = xdc.loadPackage('ti.drv.gpio');
+  Gpio.Settings.enableProfiling = true;
+  @endcode
+  Otherwise the time elapsed by their functions will count against the caller.
+  -# In the same file, add the following line so that the profiling library is
+  included in your project as well:
+  @code
+  var Profiling = xdc.loadPackage('ti.utils.profiling');
+  @endcode
+  -# Under the Project Explorer, right-click the desired project and select
+  Properties > CCS Build > "Set Additional Flags..." and add the flags for the
+  desired platform:
+      - ARM: `-finstrument-functions -gdwarf-3 -g`
+      - DSP: `--entry_parm=address --exit_hook=ti_utils_exit --exit_parm=address --entry_hook=ti_utils_entry -g`
+      - M4: `--entry_parm=address --exit_hook=ti_utils_exit --exit_parm=address --entry_hook=ti_utils_entry -g`
+  -# Also ensure that the optimization flags (-O1, -O2, -O3...) reflect the flags
+  set in the desired program so that functions are instrumented consistently.
+  By default, example projects and new CCS projects are set to no optimization.
+  -# Close the project properties and right-click the project and select
+  "Rebuild Project" to compile.
+
+  ###Part II: Profiling Project Runtime###
+  -# Load the compiled program onto the desired target platform and run the
+  program to a desired breakpoint or time interval.
+  -# While the program is at the break, open the Memory Browser (View > Memory
+  Browser).
+  -# (Optional) In the search field, search for "elemlog" and ensure that the
+  log array has been populated (consists of sets of four values that begin with
+  either 00000000, 00000001, or 00000002).
+  -# Save a memory snapshot by clicking "Save", and in the popup, choosing a
+  filename and location, and setting the start address to "elemlog" and length
+  to "log_idx*4".
+
+  ###Part III: Post-processing the Profiling Log###
+  -# Open a command prompt window set to the directory of the
+  "decodeProfileDump.py" Python script (typically under utils/profiling/scripts)
+  -# Assemble the processing command in the following format:
+  @code
+      python decodeProfileDump.py [log 1] [executable 1] [log 2] [executable 2] ...
+  @endcode
+  where the log is the profiling log memory dump created in Part II and the
+  executable is the *.out program.
+  -# Append any desired flags:
+        - -v      Display verbose output
+        - -t       Breakdown function totals by their reference sites
+        - -x       Print the tabulated results into a report.xlsx Excel file
+        - -csv    Print the tabulated results into a report.csv file
+        - -h       Print a histogram of the results (shown in the rightmost columns of the output)
+        - -off N  Manual instrumentation offset of N cycles, subtracted from each function.
+        Note: The instrumentation program already generates an offset from itself that is subtracted from the function times. Use this flag only if there is an additional offset you would like to subtract.
+
+  ###Part IV: Understanding the Output###
+  Term           | Meaning
+  ---------------|----------------------------------------------
+  Function          | The name of the function that was instrumented
+  Referenced_By  | The call site of the function instrumented
+  Total_Cycles   | The number of processor cycles elapsed for the function instrumented, both inclusively (inc), including the cycles of its child functions within, and exclusively (exc), excluding the cycles of its child functions
+  Average_Cycles | The number of processor cycles elapsed for the function instrumented per reference, both inclusively and exclusively
+  Total_Calls    | The number of internal, child functions referenced by the function that are part of the program or its library
+  Average_Calls  | The number of internal, child functions referenced by the function per reference
+  Iterations     | The number of times the function instrumented was referenced
+
+  -# If the histogram flag was set, the histogram is written in the ten columns following the measurements. These columns account for every iteration of the instrumented function, and are followed by its high, low, and bin size values, in processor cycles.
+  -# If the histogram flag was set, the last column includes the high outlying reference that used an disproportionate number of processor cycles compared to the other function references, including its file location.
+  -# The text file (generated by default) will also contain a visual trace of the results below the table, for each function reference and its measured cycle count.
+ */
+
+ /*!
+  @page profDSS Automated Profiling with DSS
+
+  @brief This guide steps through the automated profiling pipeline using the TI
+  Utils library and DSS, using the loadti script
+
+  ##Introduction##
+
+  These instructions are for benchmarking the included LLD example projects in
+  the TI Processor Development Kit using the loadti script. This benchmark tool
+  uses the hardware clock of the PMU to measure the length of each task in
+  processor cycles with minimal overhead. This guide and scripts were written
+  for the AM5728 RTOS platform, but use standard C programming hooks that
+  may be adapted for any platform and/or processor architecture.
+
+  Notes:
+  - Functions with more than one entry point may not always map correctly with
+  their symbols and in the trace. This does not affect their child or parent
+  functions.
+  - Functions that are still on the stack at the breakpoint will be considered
+  closed at the last recorded timestamp for continuity.
+  - BIOS functions that are not referenced in the project or its library are
+  not accounted for by instrumentation and will not appear in the report.
+  - The python script used to tabulate the instrumentation logs depends on the
+  file readelf.py, which must be in the same directory.
+  - Depending on your optimization level, some functions may be optimized out
+  and/or may not appear on certain platforms, including:
+      - Empty or single-line functions
+      - ti_sysbios_* functions
+      - SemaphoreP_* functions
+
+  ###Part I: Project Setup###
+  -# Download and install the TI RTOS Processor SDK for AM572x or the desired
+  product.
+           - The installer for the AM572x can be found at: http://www.ti.com/tool/PROCESSOR-SDK-AM572X. All other platform SDKs can be found at: http://www.ti.com/lsds/ti/tools-software/sw_portal.page
+  -# In the desired project directory, open the project's *.cfg file in a text
+  editor.
+  -# Any LLDs in use must have be set to enable profiling in order to be
+  profiled at runtime. This is done by setting enableProfiling to true in the
+  LLD package. For example, in GPIO, this would be:
+  @code
+  /* Load the GPIO package */
+  var Gpio = xdc.loadPackage('ti.drv.gpio');
+  Gpio.Settings.enableProfiling = true;
+  @endcode
+  Otherwise the time elapsed by their functions will count against the caller.
+  -# In the same file, add the following line so that the profiling library is
+  included in your project as well:
+  @code
+  var Profiling = xdc.loadPackage('ti.utils.profiling');
+  @endcode
+  -# Locate the configuration file for your project (typically a *.text file)
+  and add the flags for the desired platform:
+      - ARM: `-finstrument-functions -gdwarf-3 -g`
+      - DSP: `--entry_parm=address --exit_hook=ti_utils_exit --exit_parm=address --entry_hook=ti_utils_entry -g`
+      - M4: `--entry_parm=address --exit_hook=ti_utils_exit --exit_parm=address --entry_hook=ti_utils_entry -g`
+  -# Also ensure that the optimization flags (-O1, -O2, -O3...) reflect the flags
+  set in the desired program so that functions are instrumented consistently.
+  By default, example projects and new CCS projects are set to no optimization.
+  -# Save these files and recompile your project.
+
+  ###Part II: Profiling Project Runtime###
+  -# If you have not already, locate the loadti directory. This is typically
+  located under:
+  @code
+  C:\ti\ccsv6\ccs_base\scripting\examples\loadti
+  @endcode
+  -# Depending on the version of CCS installed, loadti may need to be patched
+  so that its saveData function can evaluate expressions as well as static
+  integer addresses.
+        - If this is the case, a patched version of the memXfer.js script is
+        included in the utils/profiling/scripts directory
+        - Simply replace the memXfer.js file in the loadti directory with the
+        patched memXfer.js file in the profiling library
+        - Note: This will not break existing applications that use static
+        integer addresses
+  -# Load the desired program onto the desired target platform and run the
+  program to a desired breakpoint or time interval using this format:
+  @code
+  loadti -v -c=[config *.ccxml] -t [time interval] -msd="0,elemlog,[output *.txt],4*log_idx,1,false" [executable *.out]
+  @endcode
+  -# This will automatically run the run the program and dump the profiling log
+  into a specified text file for post-processing.
+
+  ###Part III: Post-processing the Profiling Log###
+  -# Open a command prompt window set to the directory of the
+  "decodeProfileDump.py" Python script (typically under utils/profiling/scripts)
+  -# Assemble the processing command in the following format:
+  @code
+      python decodeProfileDump.py [log 1] [executable 1] [log 2] [executable 2] ...
+  @endcode
+  where the log is the profiling log memory dump created in Part II and the
+  executable is the *.out program.
+  -# Append any desired flags:
+        - -v      Display verbose output
+        - -t       Breakdown function totals by their reference sites
+        - -x       Print the tabulated results into a report.xlsx Excel file
+        - -csv    Print the tabulated results into a report.csv file
+        - -h       Print a histogram of the results (shown in the rightmost columns of the output)
+        - -off N  Manual instrumentation offset of N cycles, subtracted from each function.
+        Note: The instrumentation program already generates an offset from itself that is subtracted from the function times. Use this flag only if there is an additional offset you would like to subtract.
+
+  ###Part IV: Understanding the Output###
+  Term           | Meaning
+  ---------------|----------------------------------------------
+  Function          | The name of the function that was instrumented
+  Referenced_By  | The call site of the function instrumented
+  Total_Cycles   | The number of processor cycles elapsed for the function instrumented, both inclusively (inc), including the cycles of its child functions within, and exclusively (exc), excluding the cycles of its child functions
+  Average_Cycles | The number of processor cycles elapsed for the function instrumented per reference, both inclusively and exclusively
+  Total_Calls    | The number of internal, child functions referenced by the function that are part of the program or its library
+  Average_Calls  | The number of internal, child functions referenced by the function per reference
+  Iterations     | The number of times the function instrumented was referenced
+
+  -# If the histogram flag was set, the histogram is written in the ten columns following the measurements. These columns account for every iteration of the instrumented function, and are followed by its high, low, and bin size values, in processor cycles.
+  -# If the histogram flag was set, the last column includes the high outlying reference that used an disproportionate number of processor cycles compared to the other function references, including its file location.
+  -# The text file (generated by default) will also contain a visual trace of the results below the table, for each function reference and its measured cycle count.
+  */
diff --git a/packages/ti/utils/profiling/Settings.xdc.xdt b/packages/ti/utils/profiling/Settings.xdc.xdt
new file mode 100644 (file)
index 0000000..1a086de
--- /dev/null
@@ -0,0 +1,36 @@
+
+%%{
+/*!
+ *  This template implements the Settings.xdc
+ */
+  /* Versioning */
+  var ver = this;
+  for each(i=0;i<ver.length;i++)
+  {
+      if(String(ver[i]).length < 2)
+      {
+        ver[i]="0"+ver[i];
+      }
+  }
+
+  var packageVersion = "\""+ver[0]+"."+ver[1]+"."+ver[2]+"."+ver[3]+"\"";
+
+%%}
+
+module Settings
+{
+    config string profilingversionString = `packageVersion`;
+       
+    /*! This variable is to control the device library type selection.
+     * By default this variable is set to release.
+     * 
+     * To use CSL to use the debug/release library, add the following lines to config
+     * file and set the library profile accordingly:
+     * 
+     *      var Uart Settings = xdc.useModule ('ti.Uart.Settings');
+     *      UartSettings.libProfile = "debug";
+     * 
+     */
+    metaonly config string libProfile = "release";     
+
+}
diff --git a/packages/ti/utils/profiling/build/armv7/ti.utils.aa15fg.mk b/packages/ti/utils/profiling/build/armv7/ti.utils.aa15fg.mk
new file mode 100644 (file)
index 0000000..bd9cda0
--- /dev/null
@@ -0,0 +1,61 @@
+#*******************************************************************************
+#* FILE PURPOSE: Lower level makefile for Creating Component Libraries
+#*******************************************************************************
+#* FILE NAME: ./build/armv7/ti.utils.aa15fg.mk
+#*
+#* DESCRIPTION: Defines Source Files, Compilers flags and build rules
+#*
+#*
+#*******************************************************************************
+#
+
+#
+# Macro definitions referenced below
+#
+empty =
+space =$(empty) $(empty)
+CC = $(TOOLCHAIN_PATH_A15)/bin/$(CROSS_TOOL_PRFX)gcc
+AC = $(TOOLCHAIN_PATH_A15)/bin/$(CROSS_TOOL_PRFX)as
+ARIN = $(TOOLCHAIN_PATH_A15)/bin/$(CROSS_TOOL_PRFX)ar
+LD = $(TOOLCHAIN_PATH_A15)/bin/$(CROSS_TOOL_PRFX)gcc
+INCS = -I. -I$(strip $(subst ;, -I,$(subst $(space),\$(space),$(INCDIR)))) -I$(TOOLCHAIN_PATH_A15)/include
+OBJEXT = oa15fg
+AOBJEXT = sa15fg
+CFLAGS_INTERNAL = -mno-unaligned-access -c -mtune=cortex-a15 -marm -DDRA7xx -g -gdwarf-3 -gstrict-dwarf -Wall -D__ARMv7 -D_LITTLE_ENDIAN=1 -finstrument-functions -gdwarf-3 -g -D_ENABLE_BM -mcpu=cortex-a15 -mfpu=neon -mfloat-abi=hard -mabi=aapcs -g
+ASFLAGS_INTERNAL =  -mcpu=cortex-a15 -mfpu=neon -mfloat-abi=hard
+ARFLAGS_INTERNAL = cr
+LNKFLAGS_INTERNAL = 
+INTERNALDEFS = -MD -MF $@.dep
+INTERNALLINKDEFS = -o $@ -m $@.map
+OBJDIR =  $(LIBDIR)/armv7/obj
+
+#List the COMMONSRC Files
+COMMONSRCC= \
+    src/profilingHooksA15.c
+
+# FLAGS for the COMMONSRC Files
+COMMONSRCCFLAGS =   -I./src -I. 
+
+# Make Rule for the COMMONSRC Files
+COMMONSRCCOBJS = $(patsubst %.c, $(OBJDIR)/%.$(OBJEXT), $(COMMONSRCC))
+
+$(COMMONSRCCOBJS): $(OBJDIR)/%.$(OBJEXT): %.c
+       -@echo cla15fg $< ...
+       if [ ! -d $(@D) ]; then $(MKDIR) $(@D) ; fi;
+       $(RM) $@.dep
+       $(CC) $(CFLAGS_INTERNAL) $(COMMONSRCCFLAGS) $(INTERNALDEFS) $(INCS) $< -o $@
+
+#Create Empty rule for dependency
+$(COMMONSRCCOBJS):.\build\armv7\ti.utils.aa15fg.mk
+.\build\armv7\ti.utils.aa15fg.mk:
+
+#Include Depedency for COMMONSRC Files
+ifneq (clean,$(MAKECMDGOALS))
+ -include $(COMMONSRCCOBJS:%.$(OBJEXT)=%.$(OBJEXT).dep)
+endif
+
+
+$(LIBDIR)/armv7/ti.utils.aa15fg : $(COMMONSRCCOBJS)
+       @echo archiving $? into $@ ...
+       if [ ! -d $(LIBDIR)/armv7 ]; then $(MKDIR) $(LIBDIR)/armv7 ; fi;
+       $(ARIN) $(ARFLAGS_INTERNAL) $@ $?
diff --git a/packages/ti/utils/profiling/build/armv7/ti.utils.profiling.aa15fg.mk b/packages/ti/utils/profiling/build/armv7/ti.utils.profiling.aa15fg.mk
new file mode 100644 (file)
index 0000000..5667691
--- /dev/null
@@ -0,0 +1,61 @@
+#*******************************************************************************
+#* FILE PURPOSE: Lower level makefile for Creating Component Libraries
+#*******************************************************************************
+#* FILE NAME: ./build/armv7/ti.utils.profiling.aa15fg.mk
+#*
+#* DESCRIPTION: Defines Source Files, Compilers flags and build rules
+#*
+#*
+#*******************************************************************************
+#
+
+#
+# Macro definitions referenced below
+#
+empty =
+space =$(empty) $(empty)
+CC = $(TOOLCHAIN_PATH_A15)/bin/$(CROSS_TOOL_PRFX)gcc
+AC = $(TOOLCHAIN_PATH_A15)/bin/$(CROSS_TOOL_PRFX)as
+ARIN = $(TOOLCHAIN_PATH_A15)/bin/$(CROSS_TOOL_PRFX)ar
+LD = $(TOOLCHAIN_PATH_A15)/bin/$(CROSS_TOOL_PRFX)gcc
+INCS = -I. -I$(strip $(subst ;, -I,$(subst $(space),\$(space),$(INCDIR)))) -I$(TOOLCHAIN_PATH_A15)/include
+OBJEXT = oa15fg
+AOBJEXT = sa15fg
+CFLAGS_INTERNAL = -mno-unaligned-access -c -mtune=cortex-a15 -marm -DDRA7xx -g -gdwarf-3 -gstrict-dwarf -Wall -D__ARMv7 -D_LITTLE_ENDIAN=1 -finstrument-functions -gdwarf-3 -g -D_ENABLE_BM -mcpu=cortex-a15 -mfpu=neon -mfloat-abi=hard -mabi=aapcs -g
+ASFLAGS_INTERNAL =  -mcpu=cortex-a15 -mfpu=neon -mfloat-abi=hard
+ARFLAGS_INTERNAL = cr
+LNKFLAGS_INTERNAL = 
+INTERNALDEFS = -MD -MF $@.dep
+INTERNALLINKDEFS = -o $@ -m $@.map
+OBJDIR =  $(LIBDIR)/armv7/obj
+
+#List the COMMONSRC Files
+COMMONSRCC= \
+    src/profilingHooksA15.c
+
+# FLAGS for the COMMONSRC Files
+COMMONSRCCFLAGS =   -I./src -I. 
+
+# Make Rule for the COMMONSRC Files
+COMMONSRCCOBJS = $(patsubst %.c, $(OBJDIR)/%.$(OBJEXT), $(COMMONSRCC))
+
+$(COMMONSRCCOBJS): $(OBJDIR)/%.$(OBJEXT): %.c
+       -@echo cla15fg $< ...
+       if [ ! -d $(@D) ]; then $(MKDIR) $(@D) ; fi;
+       $(RM) $@.dep
+       $(CC) $(CFLAGS_INTERNAL) $(COMMONSRCCFLAGS) $(INTERNALDEFS) $(INCS) $< -o $@
+
+#Create Empty rule for dependency
+$(COMMONSRCCOBJS):.\build\armv7\ti.utils.profiling.aa15fg.mk
+.\build\armv7\ti.utils.profiling.aa15fg.mk:
+
+#Include Depedency for COMMONSRC Files
+ifneq (clean,$(MAKECMDGOALS))
+ -include $(COMMONSRCCOBJS:%.$(OBJEXT)=%.$(OBJEXT).dep)
+endif
+
+
+$(LIBDIR)/armv7/ti.utils.profiling.aa15fg : $(COMMONSRCCOBJS)
+       @echo archiving $? into $@ ...
+       if [ ! -d $(LIBDIR)/armv7 ]; then $(MKDIR) $(LIBDIR)/armv7 ; fi;
+       $(ARIN) $(ARFLAGS_INTERNAL) $@ $?
diff --git a/packages/ti/utils/profiling/build/buildlib.xs b/packages/ti/utils/profiling/build/buildlib.xs
new file mode 100644 (file)
index 0000000..d33779a
--- /dev/null
@@ -0,0 +1,608 @@
+/******************************************************************************
+ * FILE PURPOSE: Build Library Utilities
+ ******************************************************************************
+ * FILE NAME: buildlib.xs
+ *
+ * DESCRIPTION:
+ *  This file contains common routines that are used by the various utilities.
+ *
+ * Copyright (C) 2014-2015, Texas Instruments, Inc.
+ *****************************************************************************/
+
+/**************************************************************************
+ * FUNCTION NAME : listAllFiles
+ **************************************************************************
+ * DESCRIPTION   :
+ *  Utility function which lists all files with a specific extension
+ *  present in a directory and any directory inside it.
+ **************************************************************************/
+function listAllFiles(ext, dir, recurse)
+{
+    var srcFile = [];
+    var d;
+
+    /* If recurse parameter is not specified we default to recursive search. */
+    if (recurse == null)
+        recurse = true;
+
+    if (dir == undefined)
+          d = ".";
+    else
+      d = dir;
+
+    /* Get access to the current directory. */
+    var file = new java.io.File(d);
+
+    /* Check if the file exists and it is a directory. */
+    if (file.exists() && file.isDirectory())
+    {
+        /* Get a list of all files in the specific directory. */
+        var fileList = file.listFiles();
+        for (var i = 0; i < fileList.length; i++)
+        {
+            /* Dont add the generated directory 'package' and any of its files
+             * to the list here. */
+            if (fileList[i].getName().matches("package") == false)
+            {
+                /* Check if the detected file is a directory */
+                if (fileList[i].isDirectory())
+                {
+                    /* We will recurse into the subdirectory only if required to do so. */
+                    if (recurse == true)
+                    {
+                        /* Generate the directory Name in which we will recurse. */
+                        var directoryName = d + "/" + fileList[i].getName();
+
+                        /* Get a list of all files in this directory */
+                        var fileListing = listAllFiles (ext, directoryName, recurse);
+                        if (fileListing != null)
+                        {
+                            /* Return a list of all file names in the directory. */
+                            for (var j = 0 ; j < fileListing.length; j++)
+                                srcFile[srcFile.length++] = fileListing[j];
+                        }
+                    }
+                }
+                else
+                {
+                    /* This was a file. Check if the file name matches the extension */
+                    if (fileList[i].getName().endsWith(ext) == true)
+                        srcFile[srcFile.length++] = d + "/" + fileList[i].getName();
+                }
+            }
+        }
+
+        return srcFile;
+    }
+    return null;
+}
+
+
+function createMake(makefile)
+{
+    /* Create the main make file */
+    var fileModule = xdc.module('xdc.services.io.File');
+    if(makefile==undefined)
+    {
+      try{
+          makefile = fileModule.open("makefile", "w");
+         } catch (ex)
+         {
+           print("makefile cannot be written to. Please check Writing Permissions.");
+           java.lang.System.exit(1);
+         }
+
+      Pkg.makePrologue += "\ninclude makefile\n";
+
+      Pkg.makeEpilogue += "\nclean::\n\t-$(RM)  makefile\n";
+      makefile.writeLine("#*******************************************************************************");
+      makefile.writeLine("#* FILE PURPOSE: Top level makefile for Creating Component Libraries");
+      makefile.writeLine("#*******************************************************************************");
+      makefile.writeLine("#* FILE NAME: makefile");
+      makefile.writeLine("#*");
+      makefile.writeLine("#* DESCRIPTION: Defines Compiler tools paths, libraries , Build Options ");
+      makefile.writeLine("#*");
+      makefile.writeLine("#*");
+      makefile.writeLine("#*******************************************************************************");
+      makefile.writeLine("#*");
+      makefile.writeLine("# (Mandatory) Specify where various tools are installed.");
+
+      var file = xdc.module('xdc.services.io.File');
+
+
+      makefile.writeLine("\n# Output for prebuilt generated libraries");
+      makefile.writeLine("export LIBDIR ?= ./lib");
+      /* use sectti from path */
+      makefile.writeLine("export SECTTI ?= sectti");
+
+      /* Create INCDIR from XDCPATH */
+
+      /* copy the environment array from the current environment */
+      var env   = java.lang.System.getenv();
+      var getxdcpath=String(java.lang.System.getenv("XDCPATH"));
+      getxdcpath= getxdcpath.replace(/\\/g,"/");
+      var keys  = env.keySet().toArray();
+      var key;
+      var stat={};
+      var env_j=[];
+      var listxdcpath = new Array();
+      for (var i = 0; i < keys.length; i++) {
+           key = String(keys[i]);
+           if((key.match("INSTALL_PATH")) || (key.match("INSTALLDIR")))
+           {
+             var keyPath=String(env.get(key));
+             keyPath=keyPath.replace(/\\/g,"/");
+             var file = xdc.module('xdc.services.io.File');
+             keyPath=file.getDOSPath(keyPath);
+             if(getxdcpath.toString().match(keyPath))
+             {
+                 listxdcpath.push({keyname: key,keypath: keyPath});
+                 while(getxdcpath.toString().match(keyPath))
+                 {
+                   getxdcpath=getxdcpath.toString().replace(keyPath,"$("+key+")");
+                 }
+             }
+           }
+
+     }
+       var pkgroot="..";
+       for (var i = Pkg.name.split('.').length; i > 1; i--) {
+              pkgroot+="/..";
+          }
+
+      makefile.writeLine("\n# ROOT Directory");
+      makefile.writeLine("export ROOTDIR := "+pkgroot);
+
+      makefile.writeLine("\n# INCLUDE Directory");
+      makefile.writeLine("export INCDIR := "+getxdcpath+";$(ROOTDIR)");
+
+      makefile.writeLine("\n# Common Macros used in make");
+      makefile.writeLine("\nifndef RM");
+      makefile.writeLine("export RM = rm -f");
+      makefile.writeLine("endif");
+
+      makefile.writeLine("\nifndef CP");
+      makefile.writeLine("export CP = cp -p");
+      makefile.writeLine("endif");
+
+      makefile.writeLine("\nexport MKDIR = mkdir -p");
+
+      makefile.writeLine("\nifndef RMDIR");
+      makefile.writeLine("export RMDIR = rm -rf");
+      makefile.writeLine("endif");
+
+      makefile.writeLine("\nifndef SED");
+      makefile.writeLine("export SED = sed");
+      makefile.writeLine("endif");
+
+      makefile.writeLine("\nifndef MAKE");
+      makefile.writeLine("export MAKE = make");
+      makefile.writeLine("endif");
+
+      makefile.writeLine("\n# PHONY Targets");
+      makefile.writeLine(".PHONY: all clean cleanall ");
+
+      makefile.writeLine("\n# FORCE Targets");
+      makefile.writeLine("FORCE: ");
+
+      makefile.writeLine("\n# all rule");
+      makefile.writeLine("all: .executables");
+      makefile.writeLine(".executables: .libraries");
+      makefile.writeLine(".libraries:");
+
+      makefile.writeLine("\n# Clean Rule");
+      makefile.writeLine("clean:: clean_package");
+      makefile.writeLine("# Clean Top Level Object Directory ");
+      makefile.writeLine("clean_package :\n\t$(RMDIR) $(LIBDIR)/*/");
+      makefile.writeLine("\t$(RMDIR) package/cfg");
+   }
+   else
+   {
+     try{
+          makefile = fileModule.open("makefile", "a");
+         } catch (ex)
+         {
+           print("makefile cannot be written to. Please check Writing Permissions.");
+           java.lang.System.exit(1);
+         }
+
+    }
+
+ return makefile;
+}
+
+function createLibMake(device, objExtDir, makelibname,targetname, objectPath)
+{
+   var tooldir;
+   var cmdprefix;
+   var targetDir;
+   var stringname=String(targetname).replace("(xdc.bld.ITarget.Module)","");
+
+   switch(stringname)
+   {
+    case String(C66LE):
+      tooldir="C6X_GEN_INSTALL_PATH";
+      cmdprefix="";
+      targetDir="c66/release";
+      targetname=C66LE;
+      break;
+    case String(C66BE):
+      tooldir="C6X_GEN_INSTALL_PATH";
+      cmdprefix="";
+      targetDir="c66/release";
+      targetname=C66BE;
+      break;
+    case String(A15LE):
+      tooldir="TOOLCHAIN_PATH_A15";
+      cmdprefix="CROSS_TOOL_PRFX";
+      targetDir="a15/release";
+      targetname=A15LE;
+      break;
+    case String(A9LE):
+      tooldir="TOOLCHAIN_PATH_A9";
+      cmdprefix="CROSS_TOOL_PRFX";
+      targetDir="a9/release";
+      targetname=A9LE;
+      break;
+    case String(A8LE):
+      tooldir="TOOLCHAIN_PATH_A8";
+      cmdprefix="CROSS_TOOL_PRFX";
+      targetDir="a8/release";
+      targetname=A8LE;
+      break;
+    case String(M4LE):
+      tooldir="TOOLCHAIN_PATH_M4";
+      cmdprefix="";
+      targetDir="m4/release";
+      targetname=M4LE;
+      break;
+   }
+
+    var fileModule = xdc.module('xdc.services.io.File');
+    try{
+     var dstFile = new java.io.File(makelibname);
+     dstFile.getParentFile().mkdirs();
+     libmakefile = fileModule.open(makelibname, "w");
+     /* Add to Archive list */
+    } catch (ex)
+    {
+     print(makelibname+" cannot be written to. Please check Writing Permissions.");
+     java.lang.System.exit(1);
+    }
+    libmakefile.writeLine("#*******************************************************************************");
+    libmakefile.writeLine("#* FILE PURPOSE: Lower level makefile for Creating Component Libraries");
+    libmakefile.writeLine("#*******************************************************************************");
+    libmakefile.writeLine("#* FILE NAME: "+makelibname);
+    libmakefile.writeLine("#*");
+    libmakefile.writeLine("#* DESCRIPTION: Defines Source Files, Compilers flags and build rules");
+    libmakefile.writeLine("#*");
+    libmakefile.writeLine("#*");
+    libmakefile.writeLine("#*******************************************************************************");
+    libmakefile.writeLine("#");
+    libmakefile.writeLine("");
+    libmakefile.writeLine("#");
+    libmakefile.writeLine("# Macro definitions referenced below");
+    libmakefile.writeLine("#");
+    libmakefile.writeLine("empty =");
+    libmakefile.writeLine("space =$(empty) $(empty)");
+
+    if ((targetname.name == "A15F") || (targetname.name == "A9F") || (targetname.name == "A8F"))
+    {
+
+        if(stringname.match("gnu.targets"))
+        {
+            libmakefile.writeLine("CC = $("+tooldir+")/bin/$("+cmdprefix+")gcc");
+            libmakefile.writeLine("AC = $("+tooldir+")/bin/$("+cmdprefix+")as");
+            libmakefile.writeLine("ARIN = $("+tooldir+")/bin/$("+cmdprefix+")ar");
+            libmakefile.writeLine("LD = $("+tooldir+")/bin/$("+cmdprefix+")gcc");
+        }
+        else
+        {
+            print("Error: Non-GNU targets are not currently supported ");
+            java.lang.System.exit(1);
+
+        }
+
+        libmakefile.writeLine("INCS = -I. -I$(strip $(subst ;, -I,$(subst $(space),\\$(space),$(INCDIR)))) -I$("+tooldir+")/include");
+        libmakefile.writeLine("OBJEXT = o"+targetname.suffix);
+        libmakefile.writeLine("AOBJEXT = s"+targetname.suffix);
+        libmakefile.writeLine("CFLAGS_INTERNAL = " +targetname.ccOpts.prefix+" "+targetname.cc.opts);
+        libmakefile.writeLine("ASFLAGS_INTERNAL = " +targetname.asmOpts.prefix+" "+targetname.asm.opts);
+        libmakefile.writeLine("ARFLAGS_INTERNAL = " +targetname.ar.opts);
+        libmakefile.writeLine("LNKFLAGS_INTERNAL = " +targetname.lnk.opts);
+        libmakefile.writeLine("INTERNALDEFS = -MD -MF $@.dep");
+        libmakefile.writeLine("INTERNALLINKDEFS = -o $@ -m $@.map");  /* TBD */
+        libmakefile.writeLine("OBJDIR =  ./obj/obj_" +targetname.suffix +"/" + device.toString() + "/" + targetDir +"/obj" + "/" + objExtDir);
+
+    }
+    else
+    {
+
+        if(stringname.match("ti.targets"))
+        {
+
+            var rtslibtemp = targetname.lnkOpts.suffix.toString().split("/");
+            var rtslib;
+            for(n=0;n<rtslibtemp.length;n++)
+            {
+                if(rtslibtemp[n].match(".lib"))
+                {
+                    rtslib=rtslibtemp[n];
+                }
+            }
+
+            libmakefile.writeLine("CC = $("+tooldir+")/bin/"+targetname.cc.cmd);
+            libmakefile.writeLine("AC = $("+tooldir+")/bin/"+targetname.asm.cmd);
+            libmakefile.writeLine("ARIN = $("+tooldir+")/bin/"+targetname.ar.cmd);
+            libmakefile.writeLine("LD = $("+tooldir+")/bin/"+targetname.lnk.cmd);
+            libmakefile.writeLine("RTSLIB = -l $("+tooldir+")/lib/"+rtslib);
+        }
+        else
+        {
+            print("Error: Non-TI targets are not currently supported ");
+            java.lang.System.exit(1);
+
+        }
+
+        libmakefile.writeLine("INCS = -I. -I$(strip $(subst ;, -I,$(subst $(space),\\$(space),$(INCDIR)))) -I$("+tooldir+")/include");
+        libmakefile.writeLine("OBJEXT = o"+targetname.suffix);
+        libmakefile.writeLine("AOBJEXT = s"+targetname.suffix);
+        libmakefile.writeLine("CFLAGS_INTERNAL = " +targetname.ccOpts.prefix+" "+targetname.cc.opts);
+        libmakefile.writeLine("ASFLAGS_INTERNAL = " +targetname.asmOpts.prefix+" "+targetname.asm.opts);
+        libmakefile.writeLine("ARFLAGS_INTERNAL = " +targetname.ar.opts);
+        libmakefile.writeLine("LNKFLAGS_INTERNAL = " +targetname.lnk.opts);
+        /* libmakefile.writeLine("INTERNALDEFS = -D"+stringname.replace(/\./g,"_")+" -Dxdc_target_types__=ti/targets/std.h -DMAKEFILE_BUILD -eo.$(OBJEXT) -ea.$(AOBJEXT) -fr=$(@D) -fs=$(@D) -ppa -ppd=$@.dep");*/
+        libmakefile.writeLine("INTERNALDEFS = -D"+stringname.replace(/\./g,"_")+"  -DMAKEFILE_BUILD -eo.$(OBJEXT) -ea.$(AOBJEXT) -fr=$(@D) -fs=$(@D) -ppa -ppd=$@.dep");
+        libmakefile.writeLine("INTERNALLINKDEFS = -o $@ -m $@.map");
+        libmakefile.writeLine("OBJDIR =  ./obj/obj_" +targetname.suffix +"/" + device.toString() + "/" + targetDir +"/obj" + "/" + objExtDir);
+    }
+
+ return libmakefile;
+
+}
+
+function makeAddObjects(srcString, makefilename, srcfiles, flags,fileExt, targetName, objDir)
+{
+  var  sourcestring = (srcString + fileExt).toString().toUpperCase();
+  var  compileflagstring = sourcestring + "FLAGS";
+  var  objectliststring = sourcestring + "OBJS";
+  /* List all the source files */
+  makefilename.writeLine("\n#List the "+srcString+" Files");
+  makefilename.writeLine(sourcestring + "= \\");
+  for(var i=0;i<srcfiles.length-1;i++)
+  {
+    makefilename.writeLine("    "+srcfiles[i]+"\\");
+  }
+    makefilename.writeLine("    "+srcfiles[i]+"\n");
+
+ /* Flags for the source files */
+ makefilename.writeLine("# FLAGS for the "+srcString+" Files");
+ var compileflags="";
+ if(fileExt == "asm" && flags.aopts != undefined)
+ {
+   compileflags+=" "+flags.aopts;
+ }
+ else if((fileExt == "c" || fileExt == "sa")&& flags.copts != undefined)
+ {
+   compileflags+=" "+flags.copts;
+ }
+
+ if(flags.incs != undefined)
+ {
+   compileflags+=" "+flags.incs;
+ }
+
+
+ makefilename.writeLine(compileflagstring+" = "+compileflags +" \n");
+ makefilename.writeLine("# Make Rule for the "+srcString+" Files");
+
+ makefilename.writeLine(objectliststring +" = $(patsubst %."+fileExt+", "+objDir+"/%.$(OBJEXT), $(" + sourcestring + "))");
+ makefilename.writeLine("\n$("+objectliststring+"): "+objDir+"/%.$(OBJEXT): %."+fileExt);
+ if(fileExt == "c")
+ {
+   makefilename.writeLine("\t-@echo cl"+targetName.suffix +" $< ...");
+ }
+ else
+ {
+   makefilename.writeLine("\t-@echo asm"+targetName.suffix +" $< ...");
+ }
+ makefilename.writeLine("\tif [ ! -d $(@D) ]; then $(MKDIR) $(@D) ; fi;");
+
+ if(fileExt == "c")
+ {
+   if ((targetName.name == "A15F") || (targetName.name == "A9F") || (targetName.name == "A8F"))
+   {
+    makefilename.writeLine("\t$(RM) $@.dep");
+    makefilename.writeLine("\t$(CC) $(CFLAGS_INTERNAL) $("+compileflagstring+") $(INTERNALDEFS) $(INCS) $< -o $@");
+   /*
+    TBD
+   */
+   }
+   else
+   {
+    makefilename.writeLine("\t$(RM) $@.dep");
+    makefilename.writeLine("\t$(CC) $(CFLAGS_INTERNAL) $("+compileflagstring+") $(INTERNALDEFS) $(INCS) -fc $< ");
+    makefilename.writeLine("\t-@$(CP) $@.dep $@.pp; \\");
+    makefilename.writeLine("         $(SED) -e 's/#.*//' -e 's/^[^:]*: *//' -e 's/ *\\\\$$//' \\");
+    makefilename.writeLine("             -e '/^$$/ d' -e 's/$$/ :/' < $@.pp >> $@.dep; \\");
+    makefilename.writeLine("         $(RM) $@.pp ");
+   }
+ }
+ else if(fileExt == "asm")
+ {
+   makefilename.writeLine("\t$(AC) $(ASFLAGS_INTERNAL) $("+compileflagstring+") $(INTERNALDEFS) $(INCS) -fa $< ");
+ }
+ else if(fileExt == "sa")
+ {
+   makefilename.writeLine("\t$(AC) $(ASFLAGS_INTERNAL) $("+compileflagstring+") $(INTERNALDEFS) $(INCS) $< ");
+ }
+
+ makefilename.writeLine("\n#Create Empty rule for dependency");
+ makefilename.writeLine("$("+objectliststring+"):"+makefilename.$private.fd);
+ makefilename.writeLine(makefilename.$private.fd+":");
+ makefilename.writeLine("\n#Include Depedency for "+srcString+" Files");
+ makefilename.writeLine("ifneq (clean,$(MAKECMDGOALS))");
+ makefilename.writeLine(" -include $("+objectliststring+":%.$(OBJEXT)=%.$(OBJEXT).dep)");
+ makefilename.writeLine("endif");
+
+}
+
+/**************************************************************************
+ * FUNCTION NAME : buildLibrary
+ **************************************************************************
+ * DESCRIPTION   :
+ *  Utility function which will build a specific library
+ **************************************************************************/
+var makefilelocal;
+function buildLibrary (socName, isDmaSoc, isSoc, libOptions, libName, target, libFiles)
+{
+    var targetDir;
+    var objExtDir;
+
+    if (target.name == "A15F")
+    {
+        targetDir = "a15/release";
+    }
+    else if (target.name == "A9F")
+    {
+        targetDir = "a9/release";
+    }
+    else if (target.name == "A8F")
+    {
+        targetDir = "a8/release";
+    }
+    else if (target.name == "M4")
+    {
+        targetDir = "m4/release";
+    }
+    else
+    {
+        targetDir = "c66/release";
+    }
+
+    /* Derive the operating system and soc names */
+    if (isDmaSoc == "true") {
+        var libNameExp = libName+".dma";
+        targetDir = socName+"/"+targetDir;
+        objExtDir ="dma";
+    }
+    else if (isSoc == "true") {
+        var libNameExp = libName;
+        targetDir = socName+"/"+targetDir;
+        objExtDir = "soc";
+    }
+    else  {
+        var libNameExp = libName;
+        objExtDir = "all";
+    }
+
+    var lldFullLibraryPath = "./lib/" + targetDir +"/" + libNameExp;
+    var lldFullBuildPath = "./build/" + targetDir +"/" + libNameExp;
+    var lldFullLibraryPathMake = "$(LIBDIR)/" + targetDir +"/" + libNameExp;
+
+    /* Create Main make file in the root of package folder */
+    makefilelocal = createMake(makefilelocal);
+
+    /* Write the rule to make library in main makefile */
+    lib = lldFullBuildPath+".a"+target.suffix;
+    libMake = lldFullLibraryPathMake+".a"+target.suffix;
+    var objectPath= "./package/"+lldFullBuildPath;
+
+    makefilelocal.writeLine("\n\n# Make rule to create "+libMake+" library");
+    makefilelocal.writeLine(".libraries: "+ libMake);
+    makefilelocal.writeLine(libMake+": FORCE\n\t$(MAKE) -f "+lib+".mk $@");
+
+    /* Create Library make file in the lib folder */
+    var makefilelib= createLibMake(socName, objExtDir, lib+".mk",target,objectPath);
+
+    /* Rule to clean library in main makefile */
+    makefilelocal.writeLine("# Rule to clean "+libMake+" library");
+    makefilelocal.writeLine("clean ::\n\t$(RM) "+ libMake);
+    librule="\n\n"+libMake+" :";
+
+    /* Add files to be compiled */
+    /* Separate out the C and assembly files */
+    var cfiles= new Array();
+    var afiles= new Array();
+    var safiles= new Array();
+    for each(var srcFile in libFiles)
+    {
+        var srcFile=String(srcFile);
+        var dot = srcFile.lastIndexOf(".");
+        var extension = srcFile.substr(dot,srcFile.length);
+        if(extension == ".c")
+        {
+            cfiles.push(srcFile);
+        }
+        else if(extension == ".sa")
+        {
+            safiles.push(srcFile);
+        }
+        else if(extension == ".asm")
+        {
+            afiles.push(srcFile);
+        }
+        else
+        {
+            print("ERROR: Unsupported file extension");
+            java.lang.System.exit(1);
+        }
+    }
+    if(cfiles.length > 0)
+    {
+      makeAddObjects("COMMONSRC",makefilelib,cfiles,libOptions,"c",target, "$(OBJDIR)");
+      librule += " $(COMMONSRCCOBJS)";
+    }
+    if(afiles.length > 0)
+    {
+      makeAddObjects("COMMONSRC",makefilelib,afiles,libOptions,"asm",target, "$(OBJDIR)");
+      librule += " $(COMMONSRCASMOBJS)";
+    }
+    if(safiles.length > 0)
+    {
+      makeAddObjects("COMMONSRC",makefilelib,safiles,libOptions,"sa",target, "$(OBJDIR)");
+      librule += " $(COMMONSRCSAOBJS)";
+    }
+
+    makefilelib.writeLine(librule);
+    makefilelib.writeLine("\t@echo archiving $? into $@ ...");
+    makefilelib.writeLine("\tif [ ! -d $(LIBDIR)/"+targetDir+" ]; then $(MKDIR) $(LIBDIR)/"+targetDir+" ; fi;");
+       makefilelib.writeLine("\t$(ARIN) $(ARFLAGS_INTERNAL) $@ $?");
+       makefilelib.close();
+
+    /* Create the Epilogue; which executes after all the builds are completed.
+     * This is used to generate the benchmark information for the built library.
+     * Also add the benchmarking information file to the package. */
+    /* Put the temp file in object directory since javascript doesn't have a built in tmpname, 
+     * and don't want --jobs=# with # > 1 to result in collisions */
+    var libFullName = lldFullLibraryPath + ".a" + target.suffix;
+    var tempFile = libFullName + ".xml";
+    Pkg.makeEpilogue += ".libraries: " + libFullName +  "_size.txt\n";
+    Pkg.makeEpilogue += libFullName +  "_size.txt: " + libFullName + "\n";
+    if ( java.lang.String(target.name).contains('66') )
+    {    
+        Pkg.makeEpilogue += "\n\t $(C6X_GEN_INSTALL_PATH)/bin/ofd6x -x " + libFullName + " > " + tempFile;
+        Pkg.makeEpilogue += "\n\t $(SECTTI) " + tempFile + " > " + libFullName +  "_size.txt";
+        Pkg.makeEpilogue += "\n\t $(RM) " + tempFile + "\n\n";
+    }   
+    else if (target.name == "M4")
+    {
+        Pkg.makeEpilogue += "\n\t $(TOOLCHAIN_PATH_M4)/bin/armofd -x " + libFullName + " > " + tempFile;
+        Pkg.makeEpilogue += "\n\t $(SECTTI) " + tempFile + " > " + libFullName +  "_size.txt";
+        Pkg.makeEpilogue += "\n\t $(RM) " + tempFile + "\n\n";
+    }
+    else
+    {
+        Pkg.makeEpilogue += "\n\t $(TOOLCHAIN_PATH_A15)/bin/$(CROSS_TOOL_PRFX)size " + libFullName + " > " + libFullName + "_size.txt";
+    }                
+    Pkg.otherFiles[Pkg.otherFiles.length++] = lldFullLibraryPath + ".a" + target.suffix + "_size.txt";
+    Pkg.otherFiles[Pkg.otherFiles.length++] = lldFullBuildPath + ".a" + target.suffix + ".mk";
+    Pkg.otherFiles[Pkg.otherFiles.length++] = lldFullLibraryPath + ".a" + target.suffix;
+
+    /* We need to clean after ourselves; extend the 'clean' target to take care of this. */
+    Pkg.makeEpilogue += "\nclean::\n";
+    Pkg.makeEpilogue += "\t$(RM) " + lldFullBuildPath + ".a" + target.suffix + "_size.txt\n";
+    Pkg.makeEpilogue += "\t$(RMDIR) " + "$(LIBDIR)/" + targetDir + "/ \n\n";
+
+    return lib;
+}
diff --git a/packages/ti/utils/profiling/build/c66/ti.utils.ae66.mk b/packages/ti/utils/profiling/build/c66/ti.utils.ae66.mk
new file mode 100644 (file)
index 0000000..4610545
--- /dev/null
@@ -0,0 +1,66 @@
+#*******************************************************************************
+#* FILE PURPOSE: Lower level makefile for Creating Component Libraries
+#*******************************************************************************
+#* FILE NAME: ./build/c66/ti.utils.ae66.mk
+#*
+#* DESCRIPTION: Defines Source Files, Compilers flags and build rules
+#*
+#*
+#*******************************************************************************
+#
+
+#
+# Macro definitions referenced below
+#
+empty =
+space =$(empty) $(empty)
+CC = $(C6X_GEN_INSTALL_PATH)/bin/cl6x -c
+AC = $(C6X_GEN_INSTALL_PATH)/bin/cl6x -c
+ARIN = $(C6X_GEN_INSTALL_PATH)/bin/ar6x
+LD = $(C6X_GEN_INSTALL_PATH)/bin/lnk6x
+RTSLIB = -l $(C6X_GEN_INSTALL_PATH)/lib/undefined
+INCS = -I. -I$(strip $(subst ;, -I,$(subst $(space),\$(space),$(INCDIR)))) -I$(C6X_GEN_INSTALL_PATH)/include
+OBJEXT = oe66
+AOBJEXT = se66
+CFLAGS_INTERNAL = -mo -q -k -eo.o --entry_parm=address --exit_hook=ti_utils_exit --exit_parm=address --entry_hook=ti_utils_entry -g -D_ENABLE_BM -mv6600 --abi=eabi
+ASFLAGS_INTERNAL = -qq -mv6600 --abi=eabi
+ARFLAGS_INTERNAL = rq
+LNKFLAGS_INTERNAL = --abi=eabi
+INTERNALDEFS = -Dti_targets_elf_C66  -DMAKEFILE_BUILD -eo.$(OBJEXT) -ea.$(AOBJEXT) -fr=$(@D) -fs=$(@D) -ppa -ppd=$@.dep
+INTERNALLINKDEFS = -o $@ -m $@.map
+OBJDIR =  $(LIBDIR)/c66/obj
+
+#List the COMMONSRC Files
+COMMONSRCC= \
+    src/profilingHooksC66.c
+
+# FLAGS for the COMMONSRC Files
+COMMONSRCCFLAGS =   -I./src -I. 
+
+# Make Rule for the COMMONSRC Files
+COMMONSRCCOBJS = $(patsubst %.c, $(OBJDIR)/%.$(OBJEXT), $(COMMONSRCC))
+
+$(COMMONSRCCOBJS): $(OBJDIR)/%.$(OBJEXT): %.c
+       -@echo cle66 $< ...
+       if [ ! -d $(@D) ]; then $(MKDIR) $(@D) ; fi;
+       $(RM) $@.dep
+       $(CC) $(CFLAGS_INTERNAL) $(COMMONSRCCFLAGS) $(INTERNALDEFS) $(INCS) -fc $< 
+       -@$(CP) $@.dep $@.pp; \
+         $(SED) -e 's/#.*//' -e 's/^[^:]*: *//' -e 's/ *\\$$//' \
+             -e '/^$$/ d' -e 's/$$/ :/' < $@.pp >> $@.dep; \
+         $(RM) $@.pp 
+
+#Create Empty rule for dependency
+$(COMMONSRCCOBJS):.\build\c66\ti.utils.ae66.mk
+.\build\c66\ti.utils.ae66.mk:
+
+#Include Depedency for COMMONSRC Files
+ifneq (clean,$(MAKECMDGOALS))
+ -include $(COMMONSRCCOBJS:%.$(OBJEXT)=%.$(OBJEXT).dep)
+endif
+
+
+$(LIBDIR)/c66/ti.utils.ae66 : $(COMMONSRCCOBJS)
+       @echo archiving $? into $@ ...
+       if [ ! -d $(LIBDIR)/c66 ]; then $(MKDIR) $(LIBDIR)/c66 ; fi;
+       $(ARIN) $(ARFLAGS_INTERNAL) $@ $?
diff --git a/packages/ti/utils/profiling/build/c66/ti.utils.ae66e.mk b/packages/ti/utils/profiling/build/c66/ti.utils.ae66e.mk
new file mode 100644 (file)
index 0000000..013e197
--- /dev/null
@@ -0,0 +1,66 @@
+#*******************************************************************************
+#* FILE PURPOSE: Lower level makefile for Creating Component Libraries
+#*******************************************************************************
+#* FILE NAME: ./build/c66/ti.utils.ae66e.mk
+#*
+#* DESCRIPTION: Defines Source Files, Compilers flags and build rules
+#*
+#*
+#*******************************************************************************
+#
+
+#
+# Macro definitions referenced below
+#
+empty =
+space =$(empty) $(empty)
+CC = $(C6X_GEN_INSTALL_PATH)/bin/cl6x -c
+AC = $(C6X_GEN_INSTALL_PATH)/bin/cl6x -c
+ARIN = $(C6X_GEN_INSTALL_PATH)/bin/ar6x
+LD = $(C6X_GEN_INSTALL_PATH)/bin/lnk6x
+RTSLIB = -l $(C6X_GEN_INSTALL_PATH)/lib/undefined
+INCS = -I. -I$(strip $(subst ;, -I,$(subst $(space),\$(space),$(INCDIR)))) -I$(C6X_GEN_INSTALL_PATH)/include
+OBJEXT = oe66e
+AOBJEXT = se66e
+CFLAGS_INTERNAL = -mo -q -k -eo.o -DBIGENDIAN --entry_parm=address --exit_hook=ti_utils_exit --exit_parm=address --entry_hook=ti_utils_entry -g -D_ENABLE_BM -me -mv6600 --abi=eabi
+ASFLAGS_INTERNAL = -qq -me -mv6600 --abi=eabi
+ARFLAGS_INTERNAL = rq
+LNKFLAGS_INTERNAL = --abi=eabi
+INTERNALDEFS = -Dti_targets_elf_C66_big_endian  -DMAKEFILE_BUILD -eo.$(OBJEXT) -ea.$(AOBJEXT) -fr=$(@D) -fs=$(@D) -ppa -ppd=$@.dep
+INTERNALLINKDEFS = -o $@ -m $@.map
+OBJDIR =  $(LIBDIR)/c66/obj
+
+#List the COMMONSRC Files
+COMMONSRCC= \
+    src/profilingHooksC66.c
+
+# FLAGS for the COMMONSRC Files
+COMMONSRCCFLAGS =   -I./src -I. 
+
+# Make Rule for the COMMONSRC Files
+COMMONSRCCOBJS = $(patsubst %.c, $(OBJDIR)/%.$(OBJEXT), $(COMMONSRCC))
+
+$(COMMONSRCCOBJS): $(OBJDIR)/%.$(OBJEXT): %.c
+       -@echo cle66e $< ...
+       if [ ! -d $(@D) ]; then $(MKDIR) $(@D) ; fi;
+       $(RM) $@.dep
+       $(CC) $(CFLAGS_INTERNAL) $(COMMONSRCCFLAGS) $(INTERNALDEFS) $(INCS) -fc $< 
+       -@$(CP) $@.dep $@.pp; \
+         $(SED) -e 's/#.*//' -e 's/^[^:]*: *//' -e 's/ *\\$$//' \
+             -e '/^$$/ d' -e 's/$$/ :/' < $@.pp >> $@.dep; \
+         $(RM) $@.pp 
+
+#Create Empty rule for dependency
+$(COMMONSRCCOBJS):.\build\c66\ti.utils.ae66e.mk
+.\build\c66\ti.utils.ae66e.mk:
+
+#Include Depedency for COMMONSRC Files
+ifneq (clean,$(MAKECMDGOALS))
+ -include $(COMMONSRCCOBJS:%.$(OBJEXT)=%.$(OBJEXT).dep)
+endif
+
+
+$(LIBDIR)/c66/ti.utils.ae66e : $(COMMONSRCCOBJS)
+       @echo archiving $? into $@ ...
+       if [ ! -d $(LIBDIR)/c66 ]; then $(MKDIR) $(LIBDIR)/c66 ; fi;
+       $(ARIN) $(ARFLAGS_INTERNAL) $@ $?
diff --git a/packages/ti/utils/profiling/build/c66/ti.utils.profiling.ae66.mk b/packages/ti/utils/profiling/build/c66/ti.utils.profiling.ae66.mk
new file mode 100644 (file)
index 0000000..66020f0
--- /dev/null
@@ -0,0 +1,66 @@
+#*******************************************************************************
+#* FILE PURPOSE: Lower level makefile for Creating Component Libraries
+#*******************************************************************************
+#* FILE NAME: ./build/c66/ti.utils.profiling.ae66.mk
+#*
+#* DESCRIPTION: Defines Source Files, Compilers flags and build rules
+#*
+#*
+#*******************************************************************************
+#
+
+#
+# Macro definitions referenced below
+#
+empty =
+space =$(empty) $(empty)
+CC = $(C6X_GEN_INSTALL_PATH)/bin/cl6x -c
+AC = $(C6X_GEN_INSTALL_PATH)/bin/cl6x -c
+ARIN = $(C6X_GEN_INSTALL_PATH)/bin/ar6x
+LD = $(C6X_GEN_INSTALL_PATH)/bin/lnk6x
+RTSLIB = -l $(C6X_GEN_INSTALL_PATH)/lib/undefined
+INCS = -I. -I$(strip $(subst ;, -I,$(subst $(space),\$(space),$(INCDIR)))) -I$(C6X_GEN_INSTALL_PATH)/include
+OBJEXT = oe66
+AOBJEXT = se66
+CFLAGS_INTERNAL = -mo -q -k -eo.o --entry_parm=address --exit_hook=ti_utils_exit --exit_parm=address --entry_hook=ti_utils_entry -g -D_ENABLE_BM -mv6600 --abi=eabi
+ASFLAGS_INTERNAL = -qq -mv6600 --abi=eabi
+ARFLAGS_INTERNAL = rq
+LNKFLAGS_INTERNAL = --abi=eabi
+INTERNALDEFS = -Dti_targets_elf_C66  -DMAKEFILE_BUILD -eo.$(OBJEXT) -ea.$(AOBJEXT) -fr=$(@D) -fs=$(@D) -ppa -ppd=$@.dep
+INTERNALLINKDEFS = -o $@ -m $@.map
+OBJDIR =  $(LIBDIR)/c66/obj
+
+#List the COMMONSRC Files
+COMMONSRCC= \
+    src/profilingHooksC66.c
+
+# FLAGS for the COMMONSRC Files
+COMMONSRCCFLAGS =   -I./src -I. 
+
+# Make Rule for the COMMONSRC Files
+COMMONSRCCOBJS = $(patsubst %.c, $(OBJDIR)/%.$(OBJEXT), $(COMMONSRCC))
+
+$(COMMONSRCCOBJS): $(OBJDIR)/%.$(OBJEXT): %.c
+       -@echo cle66 $< ...
+       if [ ! -d $(@D) ]; then $(MKDIR) $(@D) ; fi;
+       $(RM) $@.dep
+       $(CC) $(CFLAGS_INTERNAL) $(COMMONSRCCFLAGS) $(INTERNALDEFS) $(INCS) -fc $< 
+       -@$(CP) $@.dep $@.pp; \
+         $(SED) -e 's/#.*//' -e 's/^[^:]*: *//' -e 's/ *\\$$//' \
+             -e '/^$$/ d' -e 's/$$/ :/' < $@.pp >> $@.dep; \
+         $(RM) $@.pp 
+
+#Create Empty rule for dependency
+$(COMMONSRCCOBJS):.\build\c66\ti.utils.profiling.ae66.mk
+.\build\c66\ti.utils.profiling.ae66.mk:
+
+#Include Depedency for COMMONSRC Files
+ifneq (clean,$(MAKECMDGOALS))
+ -include $(COMMONSRCCOBJS:%.$(OBJEXT)=%.$(OBJEXT).dep)
+endif
+
+
+$(LIBDIR)/c66/ti.utils.profiling.ae66 : $(COMMONSRCCOBJS)
+       @echo archiving $? into $@ ...
+       if [ ! -d $(LIBDIR)/c66 ]; then $(MKDIR) $(LIBDIR)/c66 ; fi;
+       $(ARIN) $(ARFLAGS_INTERNAL) $@ $?
diff --git a/packages/ti/utils/profiling/build/c66/ti.utils.profiling.ae66e.mk b/packages/ti/utils/profiling/build/c66/ti.utils.profiling.ae66e.mk
new file mode 100644 (file)
index 0000000..e64b6c9
--- /dev/null
@@ -0,0 +1,66 @@
+#*******************************************************************************
+#* FILE PURPOSE: Lower level makefile for Creating Component Libraries
+#*******************************************************************************
+#* FILE NAME: ./build/c66/ti.utils.profiling.ae66e.mk
+#*
+#* DESCRIPTION: Defines Source Files, Compilers flags and build rules
+#*
+#*
+#*******************************************************************************
+#
+
+#
+# Macro definitions referenced below
+#
+empty =
+space =$(empty) $(empty)
+CC = $(C6X_GEN_INSTALL_PATH)/bin/cl6x -c
+AC = $(C6X_GEN_INSTALL_PATH)/bin/cl6x -c
+ARIN = $(C6X_GEN_INSTALL_PATH)/bin/ar6x
+LD = $(C6X_GEN_INSTALL_PATH)/bin/lnk6x
+RTSLIB = -l $(C6X_GEN_INSTALL_PATH)/lib/undefined
+INCS = -I. -I$(strip $(subst ;, -I,$(subst $(space),\$(space),$(INCDIR)))) -I$(C6X_GEN_INSTALL_PATH)/include
+OBJEXT = oe66e
+AOBJEXT = se66e
+CFLAGS_INTERNAL = -mo -q -k -eo.o -DBIGENDIAN --entry_parm=address --exit_hook=ti_utils_exit --exit_parm=address --entry_hook=ti_utils_entry -g -D_ENABLE_BM -me -mv6600 --abi=eabi
+ASFLAGS_INTERNAL = -qq -me -mv6600 --abi=eabi
+ARFLAGS_INTERNAL = rq
+LNKFLAGS_INTERNAL = --abi=eabi
+INTERNALDEFS = -Dti_targets_elf_C66_big_endian  -DMAKEFILE_BUILD -eo.$(OBJEXT) -ea.$(AOBJEXT) -fr=$(@D) -fs=$(@D) -ppa -ppd=$@.dep
+INTERNALLINKDEFS = -o $@ -m $@.map
+OBJDIR =  $(LIBDIR)/c66/obj
+
+#List the COMMONSRC Files
+COMMONSRCC= \
+    src/profilingHooksC66.c
+
+# FLAGS for the COMMONSRC Files
+COMMONSRCCFLAGS =   -I./src -I. 
+
+# Make Rule for the COMMONSRC Files
+COMMONSRCCOBJS = $(patsubst %.c, $(OBJDIR)/%.$(OBJEXT), $(COMMONSRCC))
+
+$(COMMONSRCCOBJS): $(OBJDIR)/%.$(OBJEXT): %.c
+       -@echo cle66e $< ...
+       if [ ! -d $(@D) ]; then $(MKDIR) $(@D) ; fi;
+       $(RM) $@.dep
+       $(CC) $(CFLAGS_INTERNAL) $(COMMONSRCCFLAGS) $(INTERNALDEFS) $(INCS) -fc $< 
+       -@$(CP) $@.dep $@.pp; \
+         $(SED) -e 's/#.*//' -e 's/^[^:]*: *//' -e 's/ *\\$$//' \
+             -e '/^$$/ d' -e 's/$$/ :/' < $@.pp >> $@.dep; \
+         $(RM) $@.pp 
+
+#Create Empty rule for dependency
+$(COMMONSRCCOBJS):.\build\c66\ti.utils.profiling.ae66e.mk
+.\build\c66\ti.utils.profiling.ae66e.mk:
+
+#Include Depedency for COMMONSRC Files
+ifneq (clean,$(MAKECMDGOALS))
+ -include $(COMMONSRCCOBJS:%.$(OBJEXT)=%.$(OBJEXT).dep)
+endif
+
+
+$(LIBDIR)/c66/ti.utils.profiling.ae66e : $(COMMONSRCCOBJS)
+       @echo archiving $? into $@ ...
+       if [ ! -d $(LIBDIR)/c66 ]; then $(MKDIR) $(LIBDIR)/c66 ; fi;
+       $(ARIN) $(ARFLAGS_INTERNAL) $@ $?
diff --git a/packages/ti/utils/profiling/build/m4/ti.utils.aem4.mk b/packages/ti/utils/profiling/build/m4/ti.utils.aem4.mk
new file mode 100644 (file)
index 0000000..5133cc1
--- /dev/null
@@ -0,0 +1,66 @@
+#*******************************************************************************
+#* FILE PURPOSE: Lower level makefile for Creating Component Libraries
+#*******************************************************************************
+#* FILE NAME: ./build/m4/ti.utils.aem4.mk
+#*
+#* DESCRIPTION: Defines Source Files, Compilers flags and build rules
+#*
+#*
+#*******************************************************************************
+#
+
+#
+# Macro definitions referenced below
+#
+empty =
+space =$(empty) $(empty)
+CC = $(TOOLCHAIN_PATH_M4)/bin/armcl -c
+AC = $(TOOLCHAIN_PATH_M4)/bin/armcl -c
+ARIN = $(TOOLCHAIN_PATH_M4)/bin/armar
+LD = $(TOOLCHAIN_PATH_M4)/bin/armlnk
+RTSLIB = -l $(TOOLCHAIN_PATH_M4)/lib/undefined
+INCS = -I. -I$(strip $(subst ;, -I,$(subst $(space),\$(space),$(INCDIR)))) -I$(TOOLCHAIN_PATH_M4)/include
+OBJEXT = oem4
+AOBJEXT = sem4
+CFLAGS_INTERNAL = -qq -pdsw255 -DMAKEFILE_BUILD --entry_parm=address --exit_hook=ti_utils_exit --exit_parm=address --entry_hook=ti_utils_entry -g -D_ENABLE_BM --endian=little -mv7M4 --float_support=vfplib --abi=eabi
+ASFLAGS_INTERNAL = -qq --endian=little -mv7M4 --float_support=vfplib --abi=eabi
+ARFLAGS_INTERNAL = rq
+LNKFLAGS_INTERNAL = --silicon_version=7M4 --strict_compatibility=on
+INTERNALDEFS = -Dti_targets_arm_elf_M4  -DMAKEFILE_BUILD -eo.$(OBJEXT) -ea.$(AOBJEXT) -fr=$(@D) -fs=$(@D) -ppa -ppd=$@.dep
+INTERNALLINKDEFS = -o $@ -m $@.map
+OBJDIR =  $(LIBDIR)/m4/obj
+
+#List the COMMONSRC Files
+COMMONSRCC= \
+    src/profilingHooksM4.c
+
+# FLAGS for the COMMONSRC Files
+COMMONSRCCFLAGS =   -I./src -I. 
+
+# Make Rule for the COMMONSRC Files
+COMMONSRCCOBJS = $(patsubst %.c, $(OBJDIR)/%.$(OBJEXT), $(COMMONSRCC))
+
+$(COMMONSRCCOBJS): $(OBJDIR)/%.$(OBJEXT): %.c
+       -@echo clem4 $< ...
+       if [ ! -d $(@D) ]; then $(MKDIR) $(@D) ; fi;
+       $(RM) $@.dep
+       $(CC) $(CFLAGS_INTERNAL) $(COMMONSRCCFLAGS) $(INTERNALDEFS) $(INCS) -fc $< 
+       -@$(CP) $@.dep $@.pp; \
+         $(SED) -e 's/#.*//' -e 's/^[^:]*: *//' -e 's/ *\\$$//' \
+             -e '/^$$/ d' -e 's/$$/ :/' < $@.pp >> $@.dep; \
+         $(RM) $@.pp 
+
+#Create Empty rule for dependency
+$(COMMONSRCCOBJS):.\build\m4\ti.utils.aem4.mk
+.\build\m4\ti.utils.aem4.mk:
+
+#Include Depedency for COMMONSRC Files
+ifneq (clean,$(MAKECMDGOALS))
+ -include $(COMMONSRCCOBJS:%.$(OBJEXT)=%.$(OBJEXT).dep)
+endif
+
+
+$(LIBDIR)/m4/ti.utils.aem4 : $(COMMONSRCCOBJS)
+       @echo archiving $? into $@ ...
+       if [ ! -d $(LIBDIR)/m4 ]; then $(MKDIR) $(LIBDIR)/m4 ; fi;
+       $(ARIN) $(ARFLAGS_INTERNAL) $@ $?
diff --git a/packages/ti/utils/profiling/build/m4/ti.utils.profiling.aem4.mk b/packages/ti/utils/profiling/build/m4/ti.utils.profiling.aem4.mk
new file mode 100644 (file)
index 0000000..76b532f
--- /dev/null
@@ -0,0 +1,66 @@
+#*******************************************************************************
+#* FILE PURPOSE: Lower level makefile for Creating Component Libraries
+#*******************************************************************************
+#* FILE NAME: ./build/m4/ti.utils.profiling.aem4.mk
+#*
+#* DESCRIPTION: Defines Source Files, Compilers flags and build rules
+#*
+#*
+#*******************************************************************************
+#
+
+#
+# Macro definitions referenced below
+#
+empty =
+space =$(empty) $(empty)
+CC = $(TOOLCHAIN_PATH_M4)/bin/armcl -c
+AC = $(TOOLCHAIN_PATH_M4)/bin/armcl -c
+ARIN = $(TOOLCHAIN_PATH_M4)/bin/armar
+LD = $(TOOLCHAIN_PATH_M4)/bin/armlnk
+RTSLIB = -l $(TOOLCHAIN_PATH_M4)/lib/undefined
+INCS = -I. -I$(strip $(subst ;, -I,$(subst $(space),\$(space),$(INCDIR)))) -I$(TOOLCHAIN_PATH_M4)/include
+OBJEXT = oem4
+AOBJEXT = sem4
+CFLAGS_INTERNAL = -qq -pdsw255 -DMAKEFILE_BUILD --entry_parm=address --exit_hook=ti_utils_exit --exit_parm=address --entry_hook=ti_utils_entry -g -D_ENABLE_BM --endian=little -mv7M4 --float_support=vfplib --abi=eabi
+ASFLAGS_INTERNAL = -qq --endian=little -mv7M4 --float_support=vfplib --abi=eabi
+ARFLAGS_INTERNAL = rq
+LNKFLAGS_INTERNAL = --silicon_version=7M4 --strict_compatibility=on
+INTERNALDEFS = -Dti_targets_arm_elf_M4  -DMAKEFILE_BUILD -eo.$(OBJEXT) -ea.$(AOBJEXT) -fr=$(@D) -fs=$(@D) -ppa -ppd=$@.dep
+INTERNALLINKDEFS = -o $@ -m $@.map
+OBJDIR =  $(LIBDIR)/m4/obj
+
+#List the COMMONSRC Files
+COMMONSRCC= \
+    src/profilingHooksM4.c
+
+# FLAGS for the COMMONSRC Files
+COMMONSRCCFLAGS =   -I./src -I. 
+
+# Make Rule for the COMMONSRC Files
+COMMONSRCCOBJS = $(patsubst %.c, $(OBJDIR)/%.$(OBJEXT), $(COMMONSRCC))
+
+$(COMMONSRCCOBJS): $(OBJDIR)/%.$(OBJEXT): %.c
+       -@echo clem4 $< ...
+       if [ ! -d $(@D) ]; then $(MKDIR) $(@D) ; fi;
+       $(RM) $@.dep
+       $(CC) $(CFLAGS_INTERNAL) $(COMMONSRCCFLAGS) $(INTERNALDEFS) $(INCS) -fc $< 
+       -@$(CP) $@.dep $@.pp; \
+         $(SED) -e 's/#.*//' -e 's/^[^:]*: *//' -e 's/ *\\$$//' \
+             -e '/^$$/ d' -e 's/$$/ :/' < $@.pp >> $@.dep; \
+         $(RM) $@.pp 
+
+#Create Empty rule for dependency
+$(COMMONSRCCOBJS):.\build\m4\ti.utils.profiling.aem4.mk
+.\build\m4\ti.utils.profiling.aem4.mk:
+
+#Include Depedency for COMMONSRC Files
+ifneq (clean,$(MAKECMDGOALS))
+ -include $(COMMONSRCCOBJS:%.$(OBJEXT)=%.$(OBJEXT).dep)
+endif
+
+
+$(LIBDIR)/m4/ti.utils.profiling.aem4 : $(COMMONSRCCOBJS)
+       @echo archiving $? into $@ ...
+       if [ ! -d $(LIBDIR)/m4 ]; then $(MKDIR) $(LIBDIR)/m4 ; fi;
+       $(ARIN) $(ARFLAGS_INTERNAL) $@ $?
diff --git a/packages/ti/utils/profiling/build/makefile_profile.mk b/packages/ti/utils/profiling/build/makefile_profile.mk
new file mode 100644 (file)
index 0000000..9652b52
--- /dev/null
@@ -0,0 +1,81 @@
+#
+# Copyright (c) 2016 - 2018, Texas Instruments Incorporated
+# 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 Texas Instruments Incorporated nor the names of
+#    its contributors may be used to endorse or promote products derived
+#    from this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#
+
+include $(PDK_INSTALL_PATH)/ti/build/Rules.make
+
+MODULE_NAME = profiling
+
+SRCDIR = . src
+INCDIR = . src
+
+# Common source files across all platforms and cores
+ifeq ($(CORE),$(filter $(CORE), mpu1_0))
+  SRCS_COMMON += profilingHooksArmV8.c
+else ifeq ($(CORE),$(filter $(CORE), mcu1_0))
+  SRCS_COMMON += profilingHooksR5.c
+else ifeq ($(CORE),$(filter $(CORE), a15_0 a9host a8host))
+  SRCS_COMMON += profilingHooksArmV7_A.c
+  SRCS_ASM_COMMON += profilingHooksArmV7_AAssembly.asm
+else ifeq ($(CORE),$(filter $(CORE), c66x))
+  SRCS_COMMON += profilingHooksC66.c
+else
+  SRCS_COMMON += profilingHooksM4.c
+endif
+
+ifeq ($(CORE),$(filter $(CORE), mpu1_0 a15_0 a9host a8host))
+  CFLAGS_LOCAL_COMMON = $(PDK_CFLAGS) -finstrument-functions -gdwarf-3 -g -D_ENABLE_BM
+else
+  CFLAGS_LOCAL_COMMON = $(PDK_CFLAGS) --entry_parm=address --exit_hook=ti_utils_exit --exit_parm=address --entry_hook=ti_utils_entry -g -D_ENABLE_BM
+endif
+
+# List all the external components/interfaces, whose interface header files
+#  need to be included for this component
+INCLUDE_EXTERNAL_INTERFACES = pdk edma
+ifeq ($(CORE),$(filter $(CORE), mcu1_0))
+INCLUDE_EXTERNAL_INTERFACES += csl
+endif
+
+PACKAGE_SRCS_COMMON = makefile profilingHooks.h profiling_component.mk profiling_osal.h \
+                      docs/ReleaseNotes_Utils.pdf src build/makefile_profile.mk \
+                      
+# Include common make files
+ifeq ($(MAKERULEDIR), )
+#Makerule path not defined, define this and assume relative path from ROOTDIR
+  MAKERULEDIR := $(ROOTDIR)/ti/build/makerules
+  export MAKERULEDIR
+endif
+include $(MAKERULEDIR)/common.mk
+
+# OBJs and libraries are built by using rule defined in rules_<target>.mk
+#     and need not be explicitly specified here
+
+# Nothing beyond this point
diff --git a/packages/ti/utils/profiling/config.bld b/packages/ti/utils/profiling/config.bld
new file mode 100755 (executable)
index 0000000..1cb23af
--- /dev/null
@@ -0,0 +1,303 @@
+/******************************************************************************
+ * FILE PURPOSE: Build configuration Script for the Utilities Library
+ ******************************************************************************
+ * FILE NAME: config.bld
+ *
+ * DESCRIPTION:
+ *  This file contains the build configuration script for the Utilities Library
+ *  and is responsible for configuration of the paths for the various tools
+ *  required to build the utility.
+ *
+ * Copyright (C) 2015, Texas Instruments, Inc.
+ *****************************************************************************/
+
+/* Get the Tools Base directory from the Environment Variable. */
+var c66ToolsBaseDir = java.lang.System.getenv("C6X_GEN_INSTALL_PATH");
+var m4ToolsBaseDir = java.lang.System.getenv("TOOLCHAIN_PATH_M4");
+var a15ToolsBaseDir = java.lang.System.getenv("TOOLCHAIN_PATH_A15");
+var a9ToolsBaseDir  = java.lang.System.getenv("TOOLCHAIN_PATH_A9");
+var a8ToolsBaseDir  = java.lang.System.getenv("TOOLCHAIN_PATH_A8");
+
+/* Get the extended debug flags for C66x, 
+ * did not change the name for backwards compatibilty */
+var extDbgFlags = java.lang.System.getenv("EXTDBGFLAGS");
+
+/* Get the extended debug flags for A15 */
+var extDbgFlags_a15 = java.lang.System.getenv("EXTDBGFLAGS_A15");
+
+/* Get the extended debug flags for A8 */
+var extDbgFlags_a8 = java.lang.System.getenv("EXTDBGFLAGS_A8");
+
+/* Get the extended debug flags for A9 */
+var extDbgFlags_a9 = java.lang.System.getenv("EXTDBGFLAGS_A9");
+
+/* Get the extended debug flags for M4 */
+var extDbgFlags_m4 = java.lang.System.getenv("EXTDBGFLAGS_M4");
+
+/* Get the base directory for the uart Socket Driver Package */
+var driverPath = new java.io.File(".//").getPath();
+
+/* Include Path */
+var lldIncludePath = " -I" + driverPath + "/src" + " -I" + driverPath;
+
+/* Configure Release Version Information */
+var driverReleaseVersion = (""+Pkg.version.replace(/\s/g, "")).split(',');
+
+/* Print the Compiler Options */
+var pOpts = 1;
+
+/* C66 ELF compiler configuration for Little Endian Mode. */
+var C66LE          = xdc.useModule('ti.targets.elf.C66');
+C66LE.rootDir       = c66ToolsBaseDir;
+C66LE.ccOpts.prefix  = "-mo -q -k -eo.o " + "--entry_parm=address --exit_hook=ti_utils_exit --exit_parm=address --entry_hook=ti_utils_entry -g -D_ENABLE_BM";
+if(extDbgFlags)     
+    C66LE.ccOpts.prefix = C66LE.ccOpts.prefix + " " + extDbgFlags; 
+
+/* C66 ELF compiler configuration for Big Endian Mode. */
+var C66BE          = xdc.useModule('ti.targets.elf.C66_big_endian');
+C66BE.rootDir       = c66ToolsBaseDir;
+C66BE.ccOpts.prefix  = "-mo -q -k -eo.o -DBIGENDIAN " + "--entry_parm=address --exit_hook=ti_utils_exit --exit_parm=address --entry_hook=ti_utils_entry -g -D_ENABLE_BM";
+if(extDbgFlags)     
+    C66BE.ccOpts.prefix = C66BE.ccOpts.prefix + " " + extDbgFlags;
+
+/* ARMv7 A15 compiler configuration */
+var A15LE            = xdc.useModule('gnu.targets.arm.A15F');
+A15LE.rootDir        = a15ToolsBaseDir;
+A15LE.ccOpts.prefix  = "-mno-unaligned-access -c -mtune=cortex-a15 -marm -DDRA7xx -g -gdwarf-3 -gstrict-dwarf -Wall -D__ARMv7 -D_LITTLE_ENDIAN=1 " + "-finstrument-functions -gdwarf-3 -g -D_ENABLE_BM";
+if(extDbgFlags_a15)     
+    A15LE.ccOpts.prefix = A15LE.ccOpts.prefix + " " + extDbgFlags_a15; 
+    
+/* ARMv7 A9 compiler configuration */
+var A9LE            = xdc.useModule('gnu.targets.arm.A9F');
+A9LE.rootDir        = a9ToolsBaseDir;
+A9LE.ccOpts.prefix  = "-mno-unaligned-access -c -mtune=cortex-a9 -marm -DDRA7xx -g -gdwarf-3 -gstrict-dwarf -Wall -D__ARMv7 -D_LITTLE_ENDIAN=1 " + "-finstrument-functions -gdwarf-3 -g -D_ENABLE_BM";
+if(extDbgFlags_a9)     
+    A9LE.ccOpts.prefix = A9LE.ccOpts.prefix + " " + extDbgFlags_a9; 
+
+/* ARMv7 A8 compiler configuration */
+var A8LE            = xdc.useModule('gnu.targets.arm.A8F');
+A8LE.rootDir        = a8ToolsBaseDir;
+A8LE.ccOpts.prefix  = "-mno-unaligned-access -c -mtune=cortex-a8 -marm -DDRA7xx -g -gdwarf-3 -gstrict-dwarf -Wall -D__ARMv7 -D_LITTLE_ENDIAN=1 " + "-finstrument-functions -gdwarf-3 -g -D_ENABLE_BM";
+if(extDbgFlags_a8)     
+    A8LE.ccOpts.prefix = A8LE.ccOpts.prefix + " " + extDbgFlags_a8; 
+
+/* M4 ELF compiler configuration for Little Endian Mode. */
+var M4LE            = xdc.useModule('ti.targets.arm.elf.M4');
+M4LE.rootDir        = m4ToolsBaseDir;
+M4LE.ccOpts.prefix  = "-qq -pdsw255 -DMAKEFILE_BUILD " + "--entry_parm=address --exit_hook=ti_utils_exit --exit_parm=address --entry_hook=ti_utils_entry -g -D_ENABLE_BM";
+if(extDbgFlags_m4)
+    M4LE.ccOpts.prefix = M4LE.ccOpts.prefix + " " + extDbgFlags_m4; 
+
+/* Create the SoC List  */
+var socs = { 
+    /* device independent libraries */
+    all :
+    {
+        /* Build this library */
+        build: "true",
+        /* SoC lib enabled */
+        socDevLib: "false",
+        /* Library options */
+        copts: "",
+        /* target lists, kept blank now, would be updated based on argument lists */
+        targets: []
+    },
+    am335x :
+    {
+        /* this variable would be reinitialized to true, if XDCARGS contains am335x */
+        build: "false",
+        /* SoC lib enabled */
+        socDevLib: "false",
+        /* Library options */
+        copts: " -DSOC_AM335x",
+        /* target list */
+        targets: [ A8LE ]
+    },
+    am437x :
+    {
+        /* this variable would be reinitialized to true, if XDCARGS contains am437x */
+        build: "false",       
+        /* SoC lib enabled */
+        socDevLib: "false",
+        /* Library options */
+        copts: " -DSOC_AM437x",
+        /* target list */
+        targets: [ A9LE ]
+   },
+   am572x :
+    {
+        /* this variable would be reinitialized to true, if XDCARGS contains am572x */
+        build: "false", 
+       /* SoC lib enabled */
+       socDevLib: "false",
+       /* Library options */
+       copts: " -DSOC_AM572x",
+       /* target list */
+       targets: [ C66LE, M4LE, A15LE]
+    },
+   am574x :
+    {
+        /* this variable would be reinitialized to true, if XDCARGS contains am574x */
+        build: "false",
+       /* SoC lib enabled */
+       socDevLib: "false",
+       /* Library options */
+       copts: " -DSOC_AM574x",
+       /* target list */
+       targets: [ C66LE, M4LE, A15LE]
+    },
+   am571x :
+    {
+        /* this variable would be reinitialized to true, if XDCARGS contains am571x */
+        build: "false",     
+       /* SoC lib enabled */
+       socDevLib: "false",
+       /* Library options */
+       copts: " -DSOC_AM571x",
+       /* target list */
+       targets: [ C66LE, M4LE, A15LE]
+    },    
+   k2h :
+    {
+        /* this variable would be reinitialized to true, if XDCARGS contains k2h */
+        build: "false",     
+       /* SoC lib enabled */
+       socDevLib: "false",
+       /* Library options */
+       copts: " -DSOC_K2H",
+       /* target list */
+       targets: [ C66LE, C66BE, A15LE]
+    },    
+   k2k :
+    {
+        /* this variable would be reinitialized to true, if XDCARGS contains k2k */
+        build: "false",     
+       /* SoC lib enabled */
+       socDevLib: "false",
+       /* Library options */
+       copts: " -DSOC_K2H",
+       /* target list */
+       targets: [ C66LE, C66BE, A15LE]
+    },   
+   k2e :
+    {
+        /* this variable would be reinitialized to true, if XDCARGS contains k2e */
+        build: "false",     
+       /* SoC lib enabled */
+       socDevLib: "false",
+       /* Library options */
+       copts: " -DSOC_K2E",
+       /* target list */
+       targets: [ C66LE, C66BE, A15LE]
+    },   
+   k2l :
+    {
+        /* this variable would be reinitialized to true, if XDCARGS contains k2l */
+        build: "false",     
+       /* SoC lib enabled */
+       socDevLib: "false",
+       /* Library options */
+       copts: " -DSOC_K2L",
+       /* target list */
+       targets: [ C66LE, C66BE, A15LE]
+    },
+   k2g :
+    {
+        /* this variable would be reinitialized to true, if XDCARGS contains k2g */
+        build: "false",     
+       /* SoC lib enabled */
+       socDevLib: "false",
+       /* Library options */
+       copts: " -DSOC_K2G",
+       /* target list */
+       targets: [ C66LE, C66BE, A15LE]
+    },
+    c6678 :
+    {
+        /* this variable would be reinitialized to true, if XDCARGS contains c6678 */
+        build: "false",
+        /* SoC lib enabled */
+        socDevLib: "false",
+        /* Library options */
+        copts: " -DSOC_C6678",
+        /* target list */
+        targets: [ C66LE, C66BE ]
+    },
+    c6657 :
+    {
+        /* this variable would be reinitialized to true, if XDCARGS contains c6657 */
+        build: "false",
+        /* SoC lib enabled */
+        socDevLib: "false",
+        /* Library options */
+        copts: " -DSOC_C6657",
+        /* target list */
+        targets: [ C66LE, C66BE ]
+    }
+};
+
+/**************************************************************************
+ * FUNCTION NAME : merge
+ **************************************************************************
+ * DESCRIPTION   :
+ *  The function is used to merge two arrarys
+ **************************************************************************/
+function merge() {
+    var args = arguments;
+    var hash = {};
+    var arr = [];
+    for (var i = 0; i < args.length; i++) {
+       for (var j = 0; j < args[i].length; j++) {
+         if (hash[args[i][j]] !== true) {
+           arr[arr.length] = args[i][j];
+           hash[args[i][j]] = true;
+         }
+       }
+     }
+    return arr;
+}
+
+/* Grab input from XDCARGS */
+var buildArguments  = [];
+
+/* Construct the build arguments */
+for (var tmp=0; arguments[tmp] != undefined; tmp++)
+{
+
+    /* If no arguments are provided, override for building all */
+    if ( ( arguments.length == 1) && (arguments[tmp].equals("./config.bld")) )
+        buildArguments[buildArguments.length++] = "all";
+    else
+        buildArguments[buildArguments.length++] = arguments[tmp];
+}
+
+/* Build targets on this build */
+var build_targets = [];
+var soc_names = Object.keys(socs);
+
+for (var i=0; i < buildArguments.length; i++ ) {
+    /* Build it for all targets */
+    if (buildArguments[i] == "all") {
+        for (var j = 0; j < soc_names.length; j++)  {
+            build_targets = merge (build_targets.slice(0), socs[soc_names[j]].targets.slice(0));
+            /* Set build to "true" for that SoC */
+            socs[soc_names[j]].build = "true";
+        }
+    }
+    else {
+        /* Skip the first argument, which is ./config.bld to get to next SoCs */
+        if (i == 0) continue;          
+        /* Set that build to true if it is found in supported build socs */
+        for (j = 0; j < soc_names.length; j++) {
+            if (buildArguments[i] == soc_names[j]) {
+                socs[buildArguments[i]].build = "true";
+                build_targets = merge (build_targets.slice(0), socs[buildArguments[i]].targets.slice(0));
+                break;
+            }
+        }
+    }   
+}
+
+/* Update the Build target generated list */
+socs["all"].targets = build_targets; 
+Build.targets   = build_targets;
diff --git a/packages/ti/utils/profiling/config_mk.bld b/packages/ti/utils/profiling/config_mk.bld
new file mode 100755 (executable)
index 0000000..ffb1a91
--- /dev/null
@@ -0,0 +1,42 @@
+/******************************************************************************
+ * FILE PURPOSE: Build configuration Script for the Utilities Library
+ ******************************************************************************
+ * FILE NAME: config.bld
+ *
+ * DESCRIPTION:
+ *  This file contains the build configuration script for the Utilities Library
+ *  and is responsible for configuration of the paths for the various tools
+ *  required to build the utility.
+ *
+ * Copyright (C) 2015, Texas Instruments, Inc.
+ *****************************************************************************/
+
+/* Get the Tools Base directory from the Environment Variable. */
+var c66ToolsBaseDir = java.lang.System.getenv("C6X_GEN_INSTALL_PATH");
+var m4ToolsBaseDir = java.lang.System.getenv("TOOLCHAIN_PATH_M4");
+var a15ToolsBaseDir = java.lang.System.getenv("TOOLCHAIN_PATH_A15");
+var a9ToolsBaseDir  = java.lang.System.getenv("TOOLCHAIN_PATH_A9");
+var a8ToolsBaseDir  = java.lang.System.getenv("TOOLCHAIN_PATH_A8");
+
+/* Get the base directory for the uart Socket Driver Package */
+var driverPath = new java.io.File(".//").getPath();
+
+/* Include Path */
+var lldIncludePath = " -I" + driverPath + "/src" + " -I" + driverPath;
+
+/* Configure Release Version Information */
+var driverReleaseVersion = (""+Pkg.version.replace(/\s/g, "")).split(',');
+
+/* Do not Print the Compiler Options */
+var pOpts = 0;
+
+
+/* List of all devices that needs to be build via XDC
+ * As the build happens through makefile, there is nothing to build via XDC
+ * using the below for packaging infrastructure
+ */
+var socs = [];
+var devices = [];
+var build_devices = [];
+Build.targets = []
+
diff --git a/packages/ti/utils/profiling/docs/Module.xs b/packages/ti/utils/profiling/docs/Module.xs
new file mode 100644 (file)
index 0000000..5610c9e
--- /dev/null
@@ -0,0 +1,42 @@
+/******************************************************************************
+ * FILE PURPOSE: Processor SDK Utilities DOCS Module specification file.
+ ******************************************************************************
+ * FILE NAME: module.xs
+ *
+ * DESCRIPTION:
+ *  This file contains the module specification for the Processor SDK Utilities
+ *  Documentation .
+ *
+ * Copyright (C) 20015, Texas Instruments, Inc.
+ *****************************************************************************/
+
+/* Load the library utility. */
+var libUtility = xdc.loadCapsule ("../build/buildlib.xs");
+
+/**************************************************************************
+ * FUNCTION NAME : modBuild
+ **************************************************************************
+ * DESCRIPTION   :
+ *  The function is used to build the LLD documentation and add it to the
+ *  package.
+ **************************************************************************/
+function modBuild()
+{
+    /* Create the actual PROLOGUE Section for the Documentation.*/
+    Pkg.makePrologue += "release: utils_document_generation\n";
+    Pkg.makePrologue += "utils_document_generation:\n";
+    Pkg.makePrologue += "\t @echo ----------------------------\n";
+    Pkg.makePrologue += "\t @echo Generating PDK Utilities Documentation\n";
+    Pkg.makePrologue += "\t doxygen docs/Doxyfile\n";
+    Pkg.makePrologue += "\t @echo PDK Utilities Documentation Generated \n";
+    Pkg.makePrologue += "\t @echo ----------------------------\n";
+
+    /* Add the documentation file to the package. */
+    Pkg.otherFiles[Pkg.otherFiles.length++] = "docs/tifooter.htm";
+    Pkg.otherFiles[Pkg.otherFiles.length++] = "docs/tiheader.htm";
+    Pkg.otherFiles[Pkg.otherFiles.length++] = "docs/tilogo.gif";
+    Pkg.otherFiles[Pkg.otherFiles.length++] = "docs/titagline.gif";
+
+    /* Add the HTML documentation to the package */
+    Pkg.otherFiles[Pkg.otherFiles.length++] = "docs/doxygen";
+}
diff --git a/packages/ti/utils/profiling/docs/ReleaseNotes_Utils.doc b/packages/ti/utils/profiling/docs/ReleaseNotes_Utils.doc
new file mode 100644 (file)
index 0000000..fab43df
Binary files /dev/null and b/packages/ti/utils/profiling/docs/ReleaseNotes_Utils.doc differ
diff --git a/packages/ti/utils/profiling/docs/ReleaseNotes_Utils.pdf b/packages/ti/utils/profiling/docs/ReleaseNotes_Utils.pdf
new file mode 100644 (file)
index 0000000..0e8c45c
Binary files /dev/null and b/packages/ti/utils/profiling/docs/ReleaseNotes_Utils.pdf differ
diff --git a/packages/ti/utils/profiling/docs/Utils_SoftwareManifest.doc b/packages/ti/utils/profiling/docs/Utils_SoftwareManifest.doc
new file mode 100644 (file)
index 0000000..ec5ba6f
Binary files /dev/null and b/packages/ti/utils/profiling/docs/Utils_SoftwareManifest.doc differ
diff --git a/packages/ti/utils/profiling/docs/Utils_SoftwareManifest.pdf b/packages/ti/utils/profiling/docs/Utils_SoftwareManifest.pdf
new file mode 100644 (file)
index 0000000..d721a75
Binary files /dev/null and b/packages/ti/utils/profiling/docs/Utils_SoftwareManifest.pdf differ
diff --git a/packages/ti/utils/profiling/docs/doxyfile.xdt b/packages/ti/utils/profiling/docs/doxyfile.xdt
new file mode 100644 (file)
index 0000000..5c3b868
--- /dev/null
@@ -0,0 +1,296 @@
+%%{
+/*!
+ *  This template implements the Doxyfile
+ */
+  /* Versioning */
+  var ver = this;
+  var packageVersion = ver[0]+"."+ver[1]+"."+ver[2]+"."+ver[3];
+
+%%}
+
+# Doxyfile 1.5.6
+
+#---------------------------------------------------------------------------
+# Project related configuration options
+#---------------------------------------------------------------------------
+DOXYFILE_ENCODING      = UTF-8
+PROJECT_NAME           = "Processor SDK Utilities"
+PROJECT_NUMBER         = `packageVersion`
+OUTPUT_DIRECTORY       = ./docs/doxygen
+CREATE_SUBDIRS         = NO
+OUTPUT_LANGUAGE        = English
+BRIEF_MEMBER_DESC      = YES
+REPEAT_BRIEF           = YES
+ABBREVIATE_BRIEF       = "The $name class" \
+                         "The $name widget" \
+                         "The $name file" \
+                         is \
+                         provides \
+                         specifies \
+                         contains \
+                         represents \
+                         a \
+                         an \
+                         the
+ALWAYS_DETAILED_SEC    = NO
+INLINE_INHERITED_MEMB  = NO
+FULL_PATH_NAMES        = NO
+STRIP_FROM_PATH        =
+STRIP_FROM_INC_PATH    =
+SHORT_NAMES            = NO
+JAVADOC_AUTOBRIEF      = NO
+QT_AUTOBRIEF           = NO
+MULTILINE_CPP_IS_BRIEF = NO
+DETAILS_AT_TOP         = NO
+INHERIT_DOCS           = YES
+SEPARATE_MEMBER_PAGES  = NO
+TAB_SIZE               = 8
+ALIASES                =
+OPTIMIZE_OUTPUT_FOR_C  = YES
+OPTIMIZE_OUTPUT_JAVA   = NO
+OPTIMIZE_FOR_FORTRAN   = NO
+OPTIMIZE_OUTPUT_VHDL   = NO
+BUILTIN_STL_SUPPORT    = NO
+CPP_CLI_SUPPORT        = NO
+SIP_SUPPORT            = NO
+IDL_PROPERTY_SUPPORT   = YES
+DISTRIBUTE_GROUP_DOC   = NO
+SUBGROUPING            = YES
+TYPEDEF_HIDES_STRUCT   = NO
+#---------------------------------------------------------------------------
+# Build related configuration options
+#---------------------------------------------------------------------------
+EXTRACT_ALL            = NO
+EXTRACT_PRIVATE        = NO
+EXTRACT_STATIC         = YES
+EXTRACT_LOCAL_CLASSES  = YES
+EXTRACT_LOCAL_METHODS  = NO
+EXTRACT_ANON_NSPACES   = NO
+HIDE_UNDOC_MEMBERS     = YES
+HIDE_UNDOC_CLASSES     = YES
+HIDE_FRIEND_COMPOUNDS  = NO
+HIDE_IN_BODY_DOCS      = NO
+INTERNAL_DOCS          = NO
+CASE_SENSE_NAMES       = NO
+HIDE_SCOPE_NAMES       = NO
+SHOW_INCLUDE_FILES     = YES
+INLINE_INFO            = YES
+SORT_MEMBER_DOCS       = YES
+SORT_BRIEF_DOCS        = NO
+SORT_GROUP_NAMES       = NO
+SORT_BY_SCOPE_NAME     = NO
+GENERATE_TODOLIST      = YES
+GENERATE_TESTLIST      = YES
+GENERATE_BUGLIST       = YES
+GENERATE_DEPRECATEDLIST= YES
+ENABLED_SECTIONS       =
+MAX_INITIALIZER_LINES  = 30
+SHOW_USED_FILES        = YES
+SHOW_DIRECTORIES       = NO
+SHOW_FILES             = YES
+SHOW_NAMESPACES        = YES
+FILE_VERSION_FILTER    =
+#---------------------------------------------------------------------------
+# configuration options related to warning and progress messages
+#---------------------------------------------------------------------------
+QUIET                  = NO
+WARNINGS               = YES
+WARN_IF_UNDOCUMENTED   = YES
+WARN_IF_DOC_ERROR      = YES
+WARN_NO_PARAMDOC       = NO
+WARN_FORMAT            = "$file:$line: $text"
+WARN_LOGFILE           =
+#---------------------------------------------------------------------------
+# configuration options related to the input files
+#---------------------------------------------------------------------------
+INPUT                  =
+INPUT_ENCODING         = UTF-8
+FILE_PATTERNS          = *.c \
+                         *.cc \
+                         *.cxx \
+                         *.cpp \
+                         *.c++ \
+                         *.d \
+                         *.java \
+                         *.ii \
+                         *.ixx \
+                         *.ipp \
+                         *.i++ \
+                         *.inl \
+                         *.h \
+                         *.hh \
+                         *.hxx \
+                         *.hpp \
+                         *.h++ \
+                         *.idl \
+                         *.odl \
+                         *.cs \
+                         *.php \
+                         *.php3 \
+                         *.inc \
+                         *.m \
+                         *.mm \
+                         *.dox \
+                         *.py \
+                         *.f90 \
+                         *.f \
+                         *.vhd \
+                         *.vhdl
+RECURSIVE              = YES
+EXCLUDE                = YES
+EXCLUDE_SYMLINKS       = NO
+EXCLUDE_PATTERNS       = cslr_*.h
+EXCLUDE_SYMBOLS        =
+EXAMPLE_PATH           =
+EXAMPLE_PATTERNS       = *
+EXAMPLE_RECURSIVE      = NO
+IMAGE_PATH             =
+INPUT_FILTER           =
+FILTER_PATTERNS        =
+FILTER_SOURCE_FILES    = NO
+#---------------------------------------------------------------------------
+# configuration options related to source browsing
+#---------------------------------------------------------------------------
+SOURCE_BROWSER         = NO
+INLINE_SOURCES         = NO
+STRIP_CODE_COMMENTS    = YES
+REFERENCED_BY_RELATION = NO
+REFERENCES_RELATION    = NO
+REFERENCES_LINK_SOURCE = YES
+USE_HTAGS              = NO
+VERBATIM_HEADERS       = NO
+#---------------------------------------------------------------------------
+# configuration options related to the alphabetical class index
+#---------------------------------------------------------------------------
+ALPHABETICAL_INDEX     = NO
+COLS_IN_ALPHA_INDEX    = 5
+IGNORE_PREFIX          =
+#---------------------------------------------------------------------------
+# configuration options related to the HTML output
+#---------------------------------------------------------------------------
+GENERATE_HTML          = YES
+HTML_OUTPUT            = html
+HTML_FILE_EXTENSION    = .html
+HTML_HEADER            = ./docs/tiheader.htm
+HTML_FOOTER            = ./docs/tifooter.htm
+HTML_STYLESHEET        =
+HTML_ALIGN_MEMBERS     = YES
+GENERATE_HTMLHELP      = YES
+GENERATE_DOCSET        = NO
+DOCSET_FEEDNAME        = "Doxygen generated docs"
+DOCSET_BUNDLE_ID       = org.doxygen.Project
+HTML_DYNAMIC_SECTIONS  = NO
+CHM_FILE               = ..\..\gpiolldDocs.chm
+HHC_LOCATION           = hhc.exe
+GENERATE_CHI           = NO
+CHM_INDEX_ENCODING     =
+BINARY_TOC             = NO
+TOC_EXPAND             = NO
+DISABLE_INDEX          = NO
+ENUM_VALUES_PER_LINE   = 4
+GENERATE_TREEVIEW      = NONE
+TREEVIEW_WIDTH         = 250
+FORMULA_FONTSIZE       = 10
+#---------------------------------------------------------------------------
+# configuration options related to the LaTeX output
+#---------------------------------------------------------------------------
+GENERATE_LATEX         = NO
+LATEX_OUTPUT           = latex
+LATEX_CMD_NAME         = latex
+MAKEINDEX_CMD_NAME     = makeindex
+COMPACT_LATEX          = NO
+PAPER_TYPE             = a4wide
+EXTRA_PACKAGES         =
+LATEX_HEADER           =
+PDF_HYPERLINKS         = YES
+USE_PDFLATEX           = YES
+LATEX_BATCHMODE        = NO
+LATEX_HIDE_INDICES     = NO
+#---------------------------------------------------------------------------
+# configuration options related to the RTF output
+#---------------------------------------------------------------------------
+GENERATE_RTF           = NO
+RTF_OUTPUT             = rtf
+COMPACT_RTF            = NO
+RTF_HYPERLINKS         = NO
+RTF_STYLESHEET_FILE    =
+RTF_EXTENSIONS_FILE    =
+#---------------------------------------------------------------------------
+# configuration options related to the man page output
+#---------------------------------------------------------------------------
+GENERATE_MAN           = NO
+MAN_OUTPUT             = man
+MAN_EXTENSION          = .3
+MAN_LINKS              = NO
+#---------------------------------------------------------------------------
+# configuration options related to the XML output
+#---------------------------------------------------------------------------
+GENERATE_XML           = NO
+XML_OUTPUT             = xml
+XML_SCHEMA             =
+XML_DTD                =
+XML_PROGRAMLISTING     = YES
+#---------------------------------------------------------------------------
+# configuration options for the AutoGen Definitions output
+#---------------------------------------------------------------------------
+GENERATE_AUTOGEN_DEF   = NO
+#---------------------------------------------------------------------------
+# configuration options related to the Perl module output
+#---------------------------------------------------------------------------
+GENERATE_PERLMOD       = NO
+PERLMOD_LATEX          = NO
+PERLMOD_PRETTY         = YES
+PERLMOD_MAKEVAR_PREFIX =
+#---------------------------------------------------------------------------
+# Configuration options related to the preprocessor
+#---------------------------------------------------------------------------
+ENABLE_PREPROCESSING   = YES
+MACRO_EXPANSION        = NO
+EXPAND_ONLY_PREDEF     = NO
+SEARCH_INCLUDES        = YES
+INCLUDE_PATH           =
+INCLUDE_FILE_PATTERNS  =
+PREDEFINED             =
+EXPAND_AS_DEFINED      =
+SKIP_FUNCTION_MACROS   = YES
+#---------------------------------------------------------------------------
+# Configuration::additions related to external references
+#---------------------------------------------------------------------------
+TAGFILES               =
+GENERATE_TAGFILE       =
+ALLEXTERNALS           = NO
+EXTERNAL_GROUPS        = YES
+PERL_PATH              = /usr/bin/perl
+#---------------------------------------------------------------------------
+# Configuration options related to the dot tool
+#---------------------------------------------------------------------------
+CLASS_DIAGRAMS         = NO
+MSCGEN_PATH            =
+HIDE_UNDOC_RELATIONS   = YES
+HAVE_DOT               = NO
+DOT_FONTNAME           = FreeSans
+DOT_FONTPATH           =
+CLASS_GRAPH            = YES
+COLLABORATION_GRAPH    = YES
+GROUP_GRAPHS           = YES
+UML_LOOK               = NO
+TEMPLATE_RELATIONS     = NO
+INCLUDE_GRAPH          = YES
+INCLUDED_BY_GRAPH      = YES
+CALL_GRAPH             = NO
+CALLER_GRAPH           = NO
+GRAPHICAL_HIERARCHY    = YES
+DIRECTORY_GRAPH        = YES
+DOT_IMAGE_FORMAT       = png
+DOT_PATH               =
+DOTFILE_DIRS           =
+DOT_GRAPH_MAX_NODES    = 50
+MAX_DOT_GRAPH_DEPTH    = 1000
+DOT_TRANSPARENT        = YES
+DOT_MULTI_TARGETS      = NO
+GENERATE_LEGEND        = YES
+DOT_CLEANUP            = YES
+#---------------------------------------------------------------------------
+# Configuration::additions related to the search engine
+#---------------------------------------------------------------------------
+SEARCHENGINE           = NO
diff --git a/packages/ti/utils/profiling/docs/tifooter.htm b/packages/ti/utils/profiling/docs/tifooter.htm
new file mode 100644 (file)
index 0000000..4bdf9c9
--- /dev/null
@@ -0,0 +1,4 @@
+<hr size="1"><small>
+Copyright  $year, Texas Instruments Incorporated</small>
+</body>
+</html>
diff --git a/packages/ti/utils/profiling/docs/tiheader.htm b/packages/ti/utils/profiling/docs/tiheader.htm
new file mode 100644 (file)
index 0000000..3c61efe
--- /dev/null
@@ -0,0 +1,12 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
+<html><head><meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
+<title>$title</title>
+<link href="$relpath$doxygen.css" rel="stylesheet" type="text/css">
+<link href="$relpath$tabs.css" rel="stylesheet" type="text/css">
+</head><body>
+<table width=100%>
+<tr>
+  <td bgcolor="black" width="1"><a href="http://www.ti.com"><img border=0 src="../../tilogo.gif"></a></td>
+  <td bgcolor="red"><img src="../../titagline.gif"></td>
+</tr>
+</table>
diff --git a/packages/ti/utils/profiling/docs/tilogo.gif b/packages/ti/utils/profiling/docs/tilogo.gif
new file mode 100644 (file)
index 0000000..f2fab2d
Binary files /dev/null and b/packages/ti/utils/profiling/docs/tilogo.gif differ
diff --git a/packages/ti/utils/profiling/docs/titagline.gif b/packages/ti/utils/profiling/docs/titagline.gif
new file mode 100644 (file)
index 0000000..743a024
Binary files /dev/null and b/packages/ti/utils/profiling/docs/titagline.gif differ
diff --git a/packages/ti/utils/profiling/filters/Module.xs b/packages/ti/utils/profiling/filters/Module.xs
new file mode 100644 (file)
index 0000000..055620a
--- /dev/null
@@ -0,0 +1,28 @@
+/******************************************************************************
+ * FILE PURPOSE: Profilng Tool Module specification file.
+ ******************************************************************************
+ * FILE NAME: Module.xs
+ *
+ * DESCRIPTION:
+ *  This file contains the module specification for the Profiling Tool.
+ *
+ * Copyright (C) 2017, Texas Instruments, Inc.
+ *****************************************************************************/
+
+/* Load the library utility. */
+var libUtility = xdc.loadCapsule ("../build/buildlib.xs");
+
+/**************************************************************************
+ * FUNCTION NAME : modBuild
+ **************************************************************************
+ * DESCRIPTION   :
+ *  The function is used to add all the filters in the filter
+ *  directory into the package.
+ **************************************************************************/
+function modBuild()
+{
+    /* Add all the .txt files to the release package. */
+    var filterFiles = libUtility.listAllFiles (".txt", "filters", true);
+    for (var k = 0 ; k < filterFiles.length; k++)
+        Pkg.otherFiles[Pkg.otherFiles.length++] = filterFiles[k];
+}
diff --git a/packages/ti/utils/profiling/filters/gpio_filter.txt b/packages/ti/utils/profiling/filters/gpio_filter.txt
new file mode 100644 (file)
index 0000000..ab066f9
--- /dev/null
@@ -0,0 +1,3 @@
+^GPIO
+^main$
+^get
diff --git a/packages/ti/utils/profiling/filters/i2c_filter.txt b/packages/ti/utils/profiling/filters/i2c_filter.txt
new file mode 100644 (file)
index 0000000..b052b15
--- /dev/null
@@ -0,0 +1,2 @@
+^I2C
+^main$
diff --git a/packages/ti/utils/profiling/filters/icss_emac_filter.txt b/packages/ti/utils/profiling/filters/icss_emac_filter.txt
new file mode 100644 (file)
index 0000000..e07a0a9
--- /dev/null
@@ -0,0 +1,9 @@
+^ICSS_Emac
+^main$
+ICSSMacInit
+^ICSS_EMacOs
+ICSSHostConfig
+ICSSMacConfig
+ICSSICSS_EmacHostInit
+ICSSPortMemInit
+ICSSHostMemInit
diff --git a/packages/ti/utils/profiling/filters/mmcsd_filter.txt b/packages/ti/utils/profiling/filters/mmcsd_filter.txt
new file mode 100644 (file)
index 0000000..0408d5c
--- /dev/null
@@ -0,0 +1,3 @@
+^MMCSD
+^HSMMCSD
+^main$
diff --git a/packages/ti/utils/profiling/filters/pruss_filter.txt b/packages/ti/utils/profiling/filters/pruss_filter.txt
new file mode 100644 (file)
index 0000000..0fc9519
--- /dev/null
@@ -0,0 +1,2 @@
+^PRUICSS
+^main$
diff --git a/packages/ti/utils/profiling/filters/spi_filter.txt b/packages/ti/utils/profiling/filters/spi_filter.txt
new file mode 100644 (file)
index 0000000..8b7f96d
--- /dev/null
@@ -0,0 +1,5 @@
+^SPI
+^QSPI
+^McSPI
+^main$
+MCSPISysConfigSetup
diff --git a/packages/ti/utils/profiling/filters/uart_filter.txt b/packages/ti/utils/profiling/filters/uart_filter.txt
new file mode 100644 (file)
index 0000000..fa2aaf6
--- /dev/null
@@ -0,0 +1,2 @@
+^UART
+^main$
diff --git a/packages/ti/utils/profiling/makefile b/packages/ti/utils/profiling/makefile
new file mode 100644 (file)
index 0000000..60b5095
--- /dev/null
@@ -0,0 +1,46 @@
+#
+# Copyright (c) 2016, Texas Instruments Incorporated
+# 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 Texas Instruments Incorporated nor the names of
+#    its contributors may be used to endorse or promote products derived
+#    from this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#
+
+ifeq ($(RULES_MAKE), )
+include $(PDK_INSTALL_PATH)/ti/build/Rules.make
+else
+include $(RULES_MAKE)
+endif
+
+COMP = drvprofiling
+
+lib_$(COMP)_BUILD_DEPENDENCY = soc
+
+$(COMP)_DOXYGEN_SUPPORT = yes
+
+include $(PDK_INSTALL_PATH)/ti/build/comp_top.mk
+
diff --git a/packages/ti/utils/profiling/package.bld b/packages/ti/utils/profiling/package.bld
new file mode 100644 (file)
index 0000000..33b6d6b
--- /dev/null
@@ -0,0 +1,123 @@
+/******************************************************************************
+ * FILE PURPOSE: Build description for the Utilities Tool
+ ******************************************************************************
+ * FILE NAME: package.bld
+ *
+ * DESCRIPTION:
+ *  This file contains the build specification and description for the Utilities Tool
+ *
+ *  The file takes the following parameters from the command line through the
+ *  XDCARGS variable.
+ *      XDCARGS[0] = Utilities Install Type
+ *      Valid Values are "TAR" or "SETUP"
+ *      DEFAULT is "TAR"
+ *
+ *  Example for a valid command:
+ *      xdc XDCARGS="SETUP" release
+ *
+ * Copyright (C) 2015-2017, Texas Instruments, Inc.
+ *****************************************************************************/
+
+/* List of all subdirectories that combine to make the Utilities Package. */
+var subDirectories = [ "src", "docs", "scripts", "filters" ];
+
+var driverInstallType;
+
+/* Determine if we need to create the InstallJammer Application or not?
+ * Utilities Deliverables be either of the following formats:
+ *  - TAR Ball Package
+ *  - Setup Executable
+ * DEFAULT is a SETUP Executable. */
+
+if ((arguments[0] != "TAR") && (arguments[0] != "SETUP"))
+    driverInstallType = "TAR";
+else
+    driverInstallType = arguments[0];
+
+/* Irrespective of the InstallType we always create a TAR Ball Package as a part
+ * of the RTSC Build. Here we determine the name of the TAR Ball Package
+ *  Format is as follows:
+ *      utils_<version> */
+var utilsRTSCFileName = "utils"+"_"+
+                      driverReleaseVersion[0] + "_" +  driverReleaseVersion[1] + "_" + 
+                      driverReleaseVersion[2]  + "_" + driverReleaseVersion[3];
+
+/******************************************************************
+ ************************ Release Banner **************************
+ ******************************************************************/
+
+print ("************* utilities Tool Build Information *************");
+print ("Utilities Tool Install          : " + driverInstallType);
+print ("Utilities Tool Version          : " + driverReleaseVersion);
+print ("RTSC File Name                 : " + utilsRTSCFileName);
+print ("Utilities Tool Path             : " + driverPath);
+print ("C66 Tools Directory             : " + c66ToolsBaseDir);
+print ("M4 Tools Directory              : " + m4ToolsBaseDir);
+print ("A15 Tools Directory             : " + a15ToolsBaseDir);
+if (pOpts == 1) 
+{      
+    print ("CC LE opts                      : " + C66LE.ccOpts.prefix);
+    print ("CC BE opts                      : " + C66BE.ccOpts.prefix);
+    print ("M4 LE opts                      : " + M4LE.ccOpts.prefix);
+    print ("A15 basic opts                  : " + A15LE.ccOpts.prefix);
+}
+print ("************************************************************");
+
+/* Create the release package for the Utilities Tool */
+Pkg.defaultRelease = Pkg.addRelease (utilsRTSCFileName, {prefix: "./packages/"});
+
+/* Moving forward we need to set the Archiver of the package to be ZIP. This is currently
+ * not supported in the XDC tools being used. Currenly builds need to be done with the
+ * following options:-
+ *   xdc MK_FIXLISTOPTS=-t release
+ * ZIP is a better option as it works natively with INSTALL Jammer and we can remove the
+ * uncompression into a temporary directory. XDC Tools with xdc-rXX support the ZIP archiver. */
+//Pkg.attrs = {archiver : "zip"};
+
+/* Cycle through all the sub-directories and build all the files */
+for (var i = 0; i < subDirectories.length; i++)
+{
+    /* Load the capsule in the sub directory. */
+    var caps = xdc.loadCapsule (subDirectories[i]+"/Module.xs");
+
+    print ("Building directory " + subDirectories[i]);
+
+    /* Build the capsule. */
+    caps.modBuild();
+
+    /* Package the module.xs files for building via package */
+    Pkg.otherFiles[Pkg.otherFiles.length++] = subDirectories[i]+"/Module.xs";
+}
+
+/* Package the remaining files */
+Pkg.otherFiles[Pkg.otherFiles.length++] = "config.bld";
+Pkg.otherFiles[Pkg.otherFiles.length++] = "config_mk.bld";
+Pkg.otherFiles[Pkg.otherFiles.length++] = "package.bld";
+Pkg.otherFiles[Pkg.otherFiles.length++] = "Settings.xdc";
+Pkg.otherFiles[Pkg.otherFiles.length++] = "Settings.xdc.xdt";
+Pkg.otherFiles[Pkg.otherFiles.length++] = "docs/Doxyfile";
+Pkg.otherFiles[Pkg.otherFiles.length++] = "docs/doxyfile.xdt";
+Pkg.otherFiles[Pkg.otherFiles.length++] = "build/buildlib.xs";
+Pkg.otherFiles[Pkg.otherFiles.length++] = "makefile";
+Pkg.otherFiles[Pkg.otherFiles.length++] = "scripts";
+Pkg.otherFiles[Pkg.otherFiles.length++] = "profilingHooks.h";
+Pkg.otherFiles[Pkg.otherFiles.length++] = "profiling_osal.h";
+Pkg.otherFiles[Pkg.otherFiles.length++] = "profilingver.h";
+Pkg.otherFiles[Pkg.otherFiles.length++] = "profilingver.h.xdt";
+Pkg.otherFiles[Pkg.otherFiles.length++] = "README.dox";
+Pkg.otherFiles[Pkg.otherFiles.length++] = "build/makefile_profile.mk";
+Pkg.otherFiles[Pkg.otherFiles.length++] = "profiling_component.mk";
+Pkg.otherFiles[Pkg.otherFiles.length++] = "./lib";
+
+/* Generate Users Manual Doxyfile */
+var tplt = xdc.loadTemplate("./docs/doxyfile.xdt");
+tplt.genFile("./docs/Doxyfile",driverReleaseVersion);
+
+/* Generate Settings.xdc */
+var tplt = xdc.loadTemplate("./Settings.xdc.xdt");
+tplt.genFile("./Settings.xdc",driverReleaseVersion);
+
+/* Generate paver.h */
+var tplt = xdc.loadTemplate("./profilingver.h.xdt");
+tplt.genFile("./profilingver.h",driverReleaseVersion);
+
diff --git a/packages/ti/utils/profiling/package.xdc b/packages/ti/utils/profiling/package.xdc
new file mode 100644 (file)
index 0000000..d8760c4
--- /dev/null
@@ -0,0 +1,15 @@
+/******************************************************************************
+ * FILE PURPOSE: Package specification file
+ ******************************************************************************
+ * FILE NAME: package.xdc
+ *
+ * DESCRIPTION:
+ *  This file contains the package specification for the Profiling Tool
+ *
+ * Copyright (C) 2015-2018, Texas Instruments, Inc.
+ *****************************************************************************/
+
+
+package ti.utils.profiling[1, 0, 0, 8] {
+    module Settings;
+}
diff --git a/packages/ti/utils/profiling/package.xs b/packages/ti/utils/profiling/package.xs
new file mode 100644 (file)
index 0000000..34373f9
--- /dev/null
@@ -0,0 +1,79 @@
+/*
+ *  ======== package.xs ========
+ *
+ */
+
+
+/*
+ *  ======== Package.getLibs ========
+ *  This function is called when a program's configuration files are
+ *  being generated and it returns the name of a library appropriate
+ *  for the program's configuration.
+ */
+
+function getLibs(prog)
+{
+    var suffix = prog.build.target.suffix;
+
+    var name = this.$name + ".a" + suffix;
+
+    /* Read LIBDIR variable */
+    var lib = java.lang.System.getenv("LIBDIR");
+
+    /* If NULL, default to "lib" folder */
+    if (lib == null)
+    {
+        lib = "./lib";
+    } else {
+        print ("\tSystem environment LIBDIR variable defined : " + lib);
+    }
+
+    /* Get target folder, if applicable */
+    if ( java.lang.String(suffix).contains('66') )
+        lib = lib + "/c66";
+    else if (java.lang.String(suffix).contains('a15') )
+        lib = lib + "/a15";
+    else if (java.lang.String(suffix).contains('m4') )
+        lib = lib + "/m4";
+    else if (java.lang.String(suffix).contains('a9') )
+        lib = lib + "/a9";
+    else if (java.lang.String(suffix).contains('a8') )
+        lib = lib + "/a8";
+    else if (java.lang.String(suffix).contains('a53'))
+           lib = lib + "/a53";
+       else if (java.lang.String(suffix).contains('r5f'))
+           lib = lib + "/r5f";
+    else
+        throw new Error("\tUnknown target for: " + this.packageBase + lib);
+
+    var libProfiles = ["debug", "release"];
+    /* get the configured library profile */
+    for each(var profile in libProfiles)
+    {
+        if (this.Settings.libProfile.equals(profile))
+        {
+            lib = lib + "/" + profile;
+            break;
+        }
+    }  
+
+    /* Get library name with path */
+    lib = lib + "/" + name;
+    if (java.io.File(this.packageBase + lib).exists()) {
+       print ("\tLinking with library " + this.$name + ":" + lib);
+       return lib;
+    }
+
+    /* Could not find any library, throw exception */
+    throw new Error("\tLibrary not found: " + this.packageBase + lib);
+}
+
+/*
+ *  ======== package.close ========
+ */
+function close()
+{
+    if (xdc.om.$name != 'cfg') {
+        return;
+    }
+}
diff --git a/packages/ti/utils/profiling/profilingHooks.h b/packages/ti/utils/profiling/profilingHooks.h
new file mode 100644 (file)
index 0000000..389abeb
--- /dev/null
@@ -0,0 +1,150 @@
+/*
+ * Copyright (c) 2015, Texas Instruments Incorporated
+ * 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 Texas Instruments Incorporated nor the names of
+ *    its contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+ * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+ * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+/** @mainpage Processor SDK Utilities
+ *
+ *  @section intro Introduction
+ *
+ *  This document describes the Processor SDK Utilities used for profiling, and
+ *  potentially other tools developed by TI in the future.
+ *  - @subpage profCCS
+ *  - @subpage profDSS
+ *
+ */
+/** @defgroup pdk_profiling_tool PDK Profiling tools
+ *  @{
+ */
+/** @} */
+/** @defgroup pdk_profiling_hooks PDK Instrumentation hooks
+ *  @ingroup pdk_profiling_tool
+ *  For more information, see:
+ *  - @subpage profCCS
+ *  - @subpage profDSS
+ */
+/**
+ *  @file    profilingHooks.h
+ *
+ *  @brief   Declarations for the runtime programming hooks of the Processor SDK Profiling Tool.
+ *
+ *  For more information, see:
+ *  - @subpage profCCS
+ *  - @subpage profDSS
+ *
+ *  ## Usage ##
+ *
+ *  Applications that are included in a profiling session must  set these
+ *  compiler flags for the desired platform:
+ *    - ARM: `-finstrument-functions -gdwarf-3 -g`
+ *    - DSP: `--entry_parm=address --exit_hook=ti_utils_exit --exit_parm=address --entry_hook=ti_utils_entry -g`
+ *    - M4: `--entry_parm=address --exit_hook=ti_utils_exit --exit_parm=address --entry_hook=ti_utils_entry -g`
+ *
+ *  For best results, ensure that the optimization levels are consistent between
+ *  the library and the project (typically -O3, or optimization level 3).
+ *
+ */
+/* Defined for C66, or DSP */
+#if defined (_TMS320C6X)
+
+/*!
+ *  @brief    TI Toolchain Utils Entry Hook
+ *
+ *  Instruments the entry point and timestamp of the current function into
+ *  memory. Note that this function is automatically referenced at entry of
+ *  every function by TI Toolchain.
+ *
+ *  @param    *func_addr  Function Assembly Address (Hexadecimal)
+ */
+void ti_utils_entry(void (* func_addr)(void));
+
+/*!
+ *  @brief    TI Toolchain Utils Exit Hook
+ *
+ *  Instruments the exit point and timestamp of the current function into
+ *  memory. Note that this function is automatically referenced at end of
+ *  every function by TI Toolchain.
+ *
+ *  @param    *func_addr  Function Assembly Address (Hexadecimal)
+ */
+void ti_utils_exit(void (* func_addr)(void));
+
+#endif
+/* Defined for M4 */
+#if defined (__TI_ARM_V7M4__)
+
+/*!
+ *  @brief    TI Toolchain Utils Entry Hook
+ *
+ *  Instruments the entry point and timestamp of the current function into
+ *  memory. Note that this function is automatically referenced at entry of
+ *  every function by TI Toolchain.
+ *
+ *  @param    *func_addr  Function Assembly Address (Hexadecimal)
+ */
+void ti_utils_entry(void (* func_addr)(void));
+
+/*!
+ *  @brief    TI Toolchain Utils Exit Hook
+ *
+ *  Instruments the exit point and timestamp of the current function into
+ *  memory. Note that this function is automatically referenced at end of
+ *  every function by TI Toolchain.
+ *
+ *  @param    *func_addr  Function Assembly Address (Hexadecimal)
+ */
+void ti_utils_exit(void (* func_addr)(void));
+/* Defined for ARM that is not M4 */
+#elif defined(__arm__)
+
+/*!
+ *  @brief    ARMv7 GCC Utils Entry Hook
+ *
+ *  Instruments the entry point, call site and timestamp of the current function
+ *  into memory. Note that this is a standard GCC library prototype function and
+ *  is automatically referenced at the entry of every function by GCC.
+ *
+ *  @param    *this_fn    Function Assembly Address (Hexadecimal)
+ *  @param    *call_site  Call Site Assembly Address (Hexadecimal)
+ */
+void __attribute__((no_instrument_function))__cyg_profile_func_enter(const void *this_fn, const void *call_site);
+
+/*!
+ *  @brief    ARMv7 GCC Utils Exit Hook
+ *
+ *  Instruments the entry point, call site and timestamp of the current function
+ *  into memory. Note that this is a standard GCC library prototype function and
+ *  is automatically referenced at the entry of every function by GCC.
+ *
+ *  @param    *this_fn    Function Assembly Address (Hexadecimal)
+ *  @param    *call_site  Call Site Assembly Address (Hexadecimal)
+ */
+void __attribute__((no_instrument_function))__cyg_profile_func_exit(const void *this_fn, void *call_site);
+
+#endif
diff --git a/packages/ti/utils/profiling/profiling_component.mk b/packages/ti/utils/profiling/profiling_component.mk
new file mode 100644 (file)
index 0000000..c9da73c
--- /dev/null
@@ -0,0 +1,135 @@
+#
+# Copyright (c) 2016 - 2018, Texas Instruments Incorporated
+# 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 Texas Instruments Incorporated nor the names of
+#    its contributors may be used to endorse or promote products derived
+#    from this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#
+
+# File: profiling_component.mk
+#       This file is component include make file of PROFILING library.
+# List of variables set in this file and their purpose:
+# <mod>_RELPATH        - This is the relative path of the module, typically from
+#                        top-level directory of the package
+# <mod>_PATH           - This is the absolute path of the module. It derives from
+#                        absolute path of the top-level directory (set in env.mk)
+#                        and relative path set above
+# <mod>_INCLUDE        - This is the path that has interface header files of the
+#                        module. This can be multiple directories (space separated)
+# <mod>_PKG_LIST       - Names of the modules (and sub-modules) that are a part
+#                        part of this module, including itself.
+# <mod>_BOARD_DEPENDENCY - "yes": means the code for this module depends on
+#                             board and the compiled obj/lib has to be kept
+#                             under <board> directory
+#                             "no" or "" or if this variable is not defined: means
+#                             this module has no board dependent code and hence
+#                             the obj/libs are not kept under <board> dir.
+# <mod>_CORE_DEPENDENCY     - "yes": means the code for this module depends on
+#                             core and the compiled obj/lib has to be kept
+#                             under <core> directory
+#                             "no" or "" or if this variable is not defined: means
+#                             this module has no core dependent code and hence
+#                             the obj/libs are not kept under <core> dir.
+# <mod>_APP_STAGE_FILES     - List of source files that belongs to the module
+#                             <mod>, but that needs to be compiled at application
+#                             build stage (in the context of the app). This is
+#                             primarily for link time configurations or if the
+#                             source file is dependent on options/defines that are
+#                             application dependent. This can be left blank or
+#                             not defined at all, in which case, it means there
+#                             no source files in the module <mod> that are required
+#                             to be compiled in the application build stage.
+#
+ifeq ($(profiling_component_make_include), )
+
+# under other list
+drvprofiling_SOCLIST         = tda2xx tda2ex tda3xx dra75x dra78x am572x am574x am571x k2h k2k k2l k2e k2g c6678 c6657 am437x am335x am65xx j721e
+drvprofiling_tda2xx_CORELIST = c66x a15_0 ipu1_0
+drvprofiling_tda2ex_CORELIST = c66x a15_0 ipu1_0
+drvprofiling_tda3xx_CORELIST = c66x ipu1_0
+drvprofiling_dra75x_CORELIST = c66x a15_0 ipu1_0
+drvprofiling_dra78x_CORELIST = c66x ipu1_0
+drvprofiling_am572x_CORELIST = c66x a15_0 ipu1_0
+drvprofiling_am574x_CORELIST = c66x a15_0 ipu1_0
+drvprofiling_am571x_CORELIST = c66x a15_0 ipu1_0
+drvprofiling_k2h_CORELIST    = c66x a15_0
+drvprofiling_k2k_CORELIST    = c66x a15_0
+drvprofiling_k2l_CORELIST    = c66x a15_0
+drvprofiling_k2e_CORELIST    = c66x a15_0
+drvprofiling_k2g_CORELIST    = c66x a15_0
+drvprofiling_c6678_CORELIST  = c66x
+drvprofiling_c6657_CORELIST  = c66x
+drvprofiling_am437x_CORELIST = a9host
+drvprofiling_am335x_CORELIST = a8host
+drvprofiling_am65xx_CORELIST = mpu1_0 mcu1_0
+drvprofiling_j721e_CORELIST  = mpu1_0 mcu1_0 mcu1_1 mcu2_0 mcu2_1 mcu3_0 mcu3_1 c66xdsp_1 c66xdsp_2
+
+############################
+# profiling package
+# List of components included under profiling lib
+# The components included here are built and will be part of profiling lib
+############################
+profiling_LIB_LIST = profiling
+drvprofiling_LIB_LIST = $(profiling_LIB_LIST)
+
+#
+# PROFILING Modules
+#
+
+# PROFILING LIB
+profiling_COMP_LIST = profiling
+profiling_RELPATH = ti/utils/profiling
+profiling_PATH = $(PDK_PROFILING_COMP_PATH)
+profiling_LIBNAME = ti.utils.profiling
+export profiling_LIBNAME
+profiling_LIBPATH = $(profiling_PATH)/lib
+export profiling_LIBPATH
+profiling_OBJPATH = $(profiling_RELPATH)/profiling
+export profiling_OBJPATH
+profiling_MAKEFILE = -f build/makefile_profile.mk
+export profiling_MAKEFILE
+profiling_BOARD_DEPENDENCY = no
+profiling_CORE_DEPENDENCY = no
+profiling_SOC_DEPENDENCY = no
+export profiling_COMP_LIST
+export profiling_BOARD_DEPENDENCY
+export profiling_CORE_DEPENDENCY
+export profiling_SOC_DEPENDENCY
+profiling_PKG_LIST = profiling
+profiling_INCLUDE = $(profiling_PATH)
+profiling_SOCLIST = $(drvprofiling_SOCLIST)
+export profiling_SOCLIST
+profiling_$(SOC)_CORELIST = $(drvprofiling_$(SOC)_CORELIST)
+export profiling_$(SOC)_CORELIST
+
+
+export drvprofiling_LIB_LIST
+export profiling_LIB_LIST
+export profiling_EXAMPLE_LIST
+
+profiling_component_make_include := 1
+endif
diff --git a/packages/ti/utils/profiling/profiling_osal.h b/packages/ti/utils/profiling/profiling_osal.h
new file mode 100644 (file)
index 0000000..f1c28b8
--- /dev/null
@@ -0,0 +1,331 @@
+/**
+ *  @file   profiling_osal.h
+ *
+ *  @brief  This is the OS Adaptation Layer used by the PDK Utilities
+ *          primarily for instantiating interrupt functions for the ARM
+ *          platform while profiling is running.
+ *
+ * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of Texas Instruments Incorporated nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#ifndef profiling_osal_H
+#define profiling_osal_H
+
+#ifndef COMMON_OSAL_DATATYPES
+#define COMMON_OSAL_DATATYPES
+
+#define OSAL_OK  (0)
+#define OSAL_FAILURE (-(1))
+#define OSAL_TIMEOUT (2)
+
+/*!
+ *  @brief    Status codes for SemaphoreP APIs
+ */
+typedef enum SemaphoreP_Status_e {
+    /*! API completed successfully */
+    SemaphoreP_OK = 0,
+    /*! API failed */
+    SemaphoreP_FAILURE = -1,
+    /*! API failed because of a timeout */
+    SemaphoreP_TIMEOUT = -2
+} SemaphoreP_Status;
+
+/*!
+ *  @brief    Wait forever define
+ */
+#define SemaphoreP_WAIT_FOREVER  (~(0))
+
+/*!
+ *  @brief    No wait define
+ */
+#define SemaphoreP_NO_WAIT       (0)
+
+
+/*!
+ *  @brief    Opaque client reference to an instance of a SemaphoreP
+ *
+ *  A SemaphoreP_Handle returned from the SemaphoreP_create represents that
+ *  instance and  is used in the other instance based functions (e.g.
+ *  SemaphoreP_post or SemaphoreP_pend, etc.).
+ */
+typedef  void *SemaphoreP_Handle;
+
+/*!
+ *  @brief    Mode of the semaphore
+ */
+typedef enum SemaphoreP_Mode_e {
+    SemaphoreP_Mode_COUNTING = 0x0,
+    SemaphoreP_Mode_BINARY   = 0x1
+} SemaphoreP_Mode;
+
+/*!
+ *  @brief    Basic SemaphoreP Parameters
+ *
+ *  Structure that contains the parameters are passed into SemaphoreP_create
+ *  when creating a SemaphoreP instance. The SemaphoreP_Params_init function
+ *  should be used to initialize the fields to default values before the
+ *  application sets the fields manually. The SemaphoreP default parameters are
+ *  noted in SemaphoreP_Params_init.
+ */
+typedef struct SemaphoreP_Params_s {
+    char *name;           /*!< Name of the semaphore instance. Memory must
+                               persist for the life of the semaphore instance */
+    SemaphoreP_Mode mode; /*!< Mode for the semaphore */
+    uint32_t maxCount;    /*!< The max count allowed for counting semaphore */
+} SemaphoreP_Params;
+
+/*!
+ *  @brief    Opaque client reference to an instance of a HwiP
+ *
+ *  A HwiP_Handle returned from the HwiP_create represents that instance.
+ */
+typedef  void *HwiP_Handle;
+
+/*!
+ *  @brief    Status codes for HwiP APIs
+ */
+typedef enum HwiP_Status_e {
+    HwiP_OK = 0,
+    HwiP_FAILURE = -1
+} HwiP_Status;
+
+
+/*!
+ *  @brief  Prototype for the entry function for a hardware interrupt
+ */
+typedef void (*HwiP_Fxn)(uintptr_t arg);
+
+
+/*!
+ *  @brief    Basic HwiP Parameters
+ *
+ *  Structure that contains the parameters passed into ::HwiP_create
+ *  when creating a HwiP instance. The ::HwiP_Params_init function should
+ *  be used to initialize the fields to default values before the application sets
+ *  the fields manually. The HwiP default parameters are noted in
+ *  HwiP_Params_init.
+ */
+typedef struct HwiP_Params_s {
+    char      *name;      /*!< Name of the clock instance. Memory must
+                               persist for the life of the clock instance.
+                               This can be used for debugging purposes, or
+                               set to NULL if not needed. */
+    uintptr_t  arg;       /*!< Argument passed into the Hwi function. */
+    uint32_t   priority;  /*!< Device specific priority. */
+    uint32_t   evtId;     /*!< Event Id. */
+} HwiP_Params;
+
+
+
+#define OSAL_Assert(expr)  {                      \
+                             if(expr)             \
+                             {                    \
+                                while(1);         \
+                             }                    \
+                           }
+
+#endif /* COMMON_OSAL_DATATYPES */
+/**********************************************************************
+ ************************* Extern Declarations ************************
+ **********************************************************************/
+
+extern SemaphoreP_Handle SemaphoreP_create(uint32_t count,
+                                           SemaphoreP_Params *params);
+extern SemaphoreP_Status SemaphoreP_delete(SemaphoreP_Handle handle);
+extern void SemaphoreP_Params_init(SemaphoreP_Params *params);
+extern SemaphoreP_Status SemaphoreP_pend(SemaphoreP_Handle handle,
+                                         uint32_t timeout);
+extern SemaphoreP_Status SemaphoreP_post(SemaphoreP_Handle handle);
+extern uintptr_t HwiP_disable(void);
+extern void HwiP_restore(uintptr_t key);
+extern HwiP_Status HwiP_delete(HwiP_Handle handle);
+extern void HwiP_disableInterrupt(int32_t interruptNum);
+extern void HwiP_enableInterrupt(int32_t interruptNum);
+extern HwiP_Handle HwiP_create(int32_t interruptNum, HwiP_Fxn hwiFxn,
+                               HwiP_Params *params);
+extern void HwiP_Params_init(HwiP_Params *params);
+
+/**
+ * @brief   Assert API. If expression is true then it will stay in the while
+ *          loop.
+ *
+ * @param   expr  Expression which need to be evaluated.
+ *
+ */
+#define profiling_osalAssert(expr)         OSAL_Assert(expr)
+
+/*!
+ *  @brief  Initialize params structure to default values.
+ *
+ *  The default parameters are:
+ *   - mode: SemOSAL_Mode_COUNTING
+ *   - name: NULL
+ *
+ *  @param params  Pointer to the instance configuration parameters.
+ */
+#define profiling_osalSemParamsInit(params)  (SemaphoreP_Params_init(params))
+
+/**
+ * @brief   Function to disable interrupts to enter a critical region
+ *
+ * <b> Prototype: </b>
+ *  The following is the C prototype for the expected OSAL API.
+ *
+ *  @verbatim
+       void HwiOSAL_enterCritical()
+    @endverbatim
+ *
+ *  <b> Parameter </b>
+ *  @n  Not Applicable
+ *
+ *  <b> Return Value </b>
+ *  @n  Interrupt key
+ */
+#define profiling_osalHardwareIntDisable() (HwiP_disable())
+
+/**
+ * @brief   Function to restore interrupts to exit a critical region
+ *
+ * <b> Prototype: </b>
+ *  The following is the C prototype for the expected OSAL API.
+ *
+ *  @verbatim
+       void HwiOSAL_exitCritical(int key)
+    @endverbatim
+ *
+ *  <b> Parameter </b>
+ *  @n  Interrupt key
+ *
+ *  <b> Return Value </b>
+ *  @n  Not Applicable
+ */
+#define profiling_osalHardwareIntRestore(X) (HwiP_restore(X))
+
+/**
+ * @brief  Function to deregister a interrupt
+ *
+ * <b> Prototype: </b>
+ *  The following is the C prototype for the expected OSAL API.
+ *
+ *  @verbatim
+       int HwiOSAL_deregisterInterrupt(void* hwiPtr)
+    @endverbatim
+ *
+ *  <b> Parameter </b>
+ *  @n  Interrupt handler
+ *
+ *  <b> Return Value </b>
+ *  @n  status of operation
+ */
+#define profiling_osalHardwareIntDestruct(X)  (HwiP_delete(X))
+
+/**
+ * @brief  Function to register an interrupt
+ *
+ * <b> Prototype: </b>
+ *  The following is the C prototype for the expected OSAL API.
+ *
+ *  @verbatim
+       int HwiOSAL_registerInterrupt(X,Y,Z,U,V)
+    @endverbatim
+ *
+ *  <b> Parameter </b>
+ *  @n  Interrupt number
+ *
+ *  <b> Parameter </b>
+ *  @n  eventID
+ *
+ *  <b> Parameter </b>
+ *  @n  entry entry function of the hardware interrupt
+ *
+ *  <b> Parameter </b>
+ *  @n  arg  argument passed into the entry function
+ *
+ *  <b> Parameter </b>
+ *  @n  priority
+ *
+ *  <b> Return Value </b>
+ *  @n  Interrupt handler
+ */
+#define profiling_osalRegisterInterrupt(X,Y,Z)     (HwiP_create((X),(Y),(Z)))
+
+
+/**
+ * @brief  Function to initialize hardware interrupt parameters.
+ *
+ * <b> Prototype: </b>
+ *  The following is the C prototype for the expected OSAL API.
+ *
+ *  @verbatim
+       void HwiP_Params_init(X)
+    @endverbatim
+ *
+ *  <b> Parameter </b>
+ *  @n  params pointer to the hardware interrupts parameter structure
+ *
+ */
+#define profiling_osalHwiParamsInit(X)             (HwiP_Params_init(X))
+
+
+/**
+ * @brief  Function to disable specific hardware interrupt
+ *
+ * <b> Prototype: </b>
+ *  The following is the C prototype for the expected OSAL API.
+ *
+ *  @verbatim
+       void HwiOSAL_disableInterrupt(uint32_t intrNum)
+    @endverbatim
+ *
+ *  <b> Parameter </b>
+ *  @n  Interrupt number
+ *
+ */
+#define profiling_osalHardwareIntrDisable(X)    (HwiP_disableInterrupt(X))
+
+/**
+ * @brief  Function to enable specific hardware interrupt
+ *
+ * <b> Prototype: </b>
+ *  The following is the C prototype for the expected OSAL API.
+ *
+ *  @verbatim
+       void HwiOSAL_enableInterrupt(uint32_t intrNum)
+    @endverbatim
+ *
+ *  <b> Parameter </b>
+ *  @n  Interrupt number
+ *
+ */
+#define profiling_osalHardwareIntrEnable(X)     (HwiP_enableInterrupt(X))
+
+#endif /* profiling_osal_H */
diff --git a/packages/ti/utils/profiling/profilingver.h b/packages/ti/utils/profiling/profilingver.h
new file mode 100644 (file)
index 0000000..238fa62
--- /dev/null
@@ -0,0 +1,68 @@
+#ifndef _profilingver_H
+#define _profilingver_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* ============================================================= */
+/**
+ *   @file  profilingver.h
+ *
+ *   path  ti/utils/profilingver.h
+ *
+ *   @brief  UTILS Tool Version Definitions
+ *
+ *  ============================================================
+ *  Copyright (c) Texas Instruments Incorporated 2009-2011
+ *
+ *  Redistribution and use in source and binary forms, with or without
+ *  modification, are permitted provided that the following conditions
+ *  are met:
+ *
+ *    Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *
+ *    Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the
+ *    distribution.
+ *
+ *    Neither the name of Texas Instruments Incorporated nor the names of
+ *    its contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ *  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ *  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ *  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ *  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ *  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+*/
+
+/**
+ * @brief   This is the Utilities Tool Version. Versions numbers are encoded in
+ * the following format:
+ *  0xAABBCCDD -> Arch (AA); API Changes (BB); Major (CC); Minor (DD)
+ */
+#define UTILS_VERSION_ID                   (0x01000009)
+
+/**
+ * @brief   This is the version string which describes the Utilities Tool along
+ * with the date and build information.
+ */
+#define UTILS_VERSION_STR                  "Utilities Tool Revision: 01.00.00.09"
+
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif  /* _profilingver_H */
diff --git a/packages/ti/utils/profiling/profilingver.h.xdt b/packages/ti/utils/profiling/profilingver.h.xdt
new file mode 100644 (file)
index 0000000..0dbc0dd
--- /dev/null
@@ -0,0 +1,100 @@
+%%{
+/*!
+ *  This template implements the profilingver.h
+ */
+  /* Versioning */
+  var ver = this;
+  var ver1 = [00,00,00,09];
+  var ver2 = [00,00,00,09];
+
+  for each(i=0;i<ver.length;i++)
+  {
+      if(String(ver[i]).length < 2)
+      {
+        ver1[i]="0"+ver[i];
+      }
+      else
+      {
+        ver1[i] = ver[i];
+      }
+
+      ver2[i] = Number(ver[i]).toString(16).toUpperCase();
+
+      if(String(ver2[i]).length < 2)
+      {
+        ver2[i]="0"+ver2[i];
+      }
+  }
+
+  var versionStr = "\""+"Utilities Tool Revision: "+ver1[0]+"."+ver1[1]+"."+ver1[2]+"."+ver1[3]+"\"";
+  var versionID = "(0x"+ver2[0]+ver2[1]+ver2[2]+ver2[3]+")";
+
+%%}
+#ifndef _profilingver_H
+#define _profilingver_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* ============================================================= */
+/**
+ *   @file  profilingver.h
+ *
+ *   path  ti/utils/profilingver.h
+ *
+ *   @brief  UTILS Tool Version Definitions
+ *
+ *  ============================================================
+ *  Copyright (c) Texas Instruments Incorporated 2009-2011
+ *
+ *  Redistribution and use in source and binary forms, with or without
+ *  modification, are permitted provided that the following conditions
+ *  are met:
+ *
+ *    Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *
+ *    Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the
+ *    distribution.
+ *
+ *    Neither the name of Texas Instruments Incorporated nor the names of
+ *    its contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ *  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ *  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ *  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ *  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ *  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+*/
+
+/**
+ * @brief   This is the Utilities Tool Version. Versions numbers are encoded in
+ * the following format:
+ *  0xAABBCCDD -> Arch (AA); API Changes (BB); Major (CC); Minor (DD)
+ */
+#define UTILS_VERSION_ID                   `versionID`
+
+/**
+ * @brief   This is the version string which describes the Utilities Tool along
+ * with the date and build information.
+ */
+#define UTILS_VERSION_STR                  `versionStr`
+
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif  /* _profilingver_H */
diff --git a/packages/ti/utils/profiling/scripts/Module.xs b/packages/ti/utils/profiling/scripts/Module.xs
new file mode 100644 (file)
index 0000000..8cd138c
--- /dev/null
@@ -0,0 +1,34 @@
+/******************************************************************************
+ * FILE PURPOSE: Profilng Tool Module specification file.
+ ******************************************************************************
+ * FILE NAME: Module.xs
+ *
+ * DESCRIPTION:
+ *  This file contains the module specification for the Profiling Tool.
+ *
+ * Copyright (C) 2015, Texas Instruments, Inc.
+ *****************************************************************************/
+
+/* Load the library utility. */
+var libUtility = xdc.loadCapsule ("../build/buildlib.xs");
+
+/**************************************************************************
+ * FUNCTION NAME : modBuild
+ **************************************************************************
+ * DESCRIPTION   :
+ *  The function is used to add all the source files in the device
+ *  directory into the package.
+ **************************************************************************/
+function modBuild()
+{
+    /* Add all the .h files to the release package. */
+    var deviceFiles = libUtility.listAllFiles (".h", "scripts", true);
+    for (var k = 0 ; k < deviceFiles.length; k++)
+        Pkg.otherFiles[Pkg.otherFiles.length++] = deviceFiles[k];
+
+    /* Add all the .mk files to the release package. */
+    var mkFiles = libUtility.listAllFiles (".mk", "scripts", true);
+    for (var k = 0 ; k < mkFiles.length; k++)
+        Pkg.otherFiles[Pkg.otherFiles.length++] = mkFiles[k];
+
+}
diff --git a/packages/ti/utils/profiling/scripts/decodeProfileDump.py b/packages/ti/utils/profiling/scripts/decodeProfileDump.py
new file mode 100644 (file)
index 0000000..2af67d5
--- /dev/null
@@ -0,0 +1,1015 @@
+#!/usr/bin/env python
+
+## @package  DecodeProfileDump
+#
+#
+#  @file     decodeProfileDump.py
+#
+#  @brief    This is the script used for profile post-processing.
+#
+#  For more information, see:
+#  - @subpage profCCS
+#  - @subpage profDSS
+#
+#  ## Usage ##
+#
+#  Applications that are included in a profiling session must  set these
+#  compiler flags for the desired platform:
+#    - ARM: `-finstrument-functions -gdwarf-3 -g`
+#    - DSP: `--entry_parm=address --exit_hook=ti_utils_exit --exit_parm=address --entry_hook=ti_utils_entry -g`
+#    - M4: `--entry_parm=address --exit_hook=ti_utils_exit --exit_parm=address --entry_hook=ti_utils_entry -g`
+#
+#  For best results, ensure that the optimization levels are consistent between
+#  the library and the project (typically -O3, or optimization level 3).
+#
+# Dependencies required:
+#            * elftools (http://github.com/eliben/pyelftools/)
+#            * tabulate (http://bitbucket.org/astanin/python-tabulate/)
+#            * xlsxwriter (https://github.com/jmcnamara/XlsxWriter/)
+#            * readelf.py included in the same directory as the script
+#
+# Usage:     python decodeProfileDump.py [log] [Function] ... [-v verbose]
+#            [-t breakdown totals] [-x print Excel] [-h print histogram]
+#            [-off N instrumentation offset of N cycles] [-csv print CSV]
+#
+# Known Issues:
+#            * Functions with more than one entry point may not always map
+#              correctly with their symbols
+#
+# Copyright (c) 2015, Texas Instruments Incorporated. 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 Texas Instruments Incorporated nor the names of
+#        its contributors may be used to endorse or promote products derived
+#        from this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#
+## @defgroup pdk_profiling_postprocessing PDK Post-Processing Script
+## @ingroup pdk_profiling_tool
+## @{
+
+from collections import namedtuple
+from collections import deque
+from elftools.elf.elffile import ELFFile
+from elftools.elf.sections import SymbolTableSection
+from elftools.common.py3compat import maxint, bytes2str
+from elftools.dwarf.descriptions import describe_form_class
+from tabulate import tabulate
+from operator import attrgetter
+from sys import argv
+import xlsxwriter
+import subprocess
+import copy
+import csv
+import os
+import re
+
+def readerror():
+    print("Usage: python "+argv[0]+"[log] [optional: func] [-v verbose] [-t breakdown totals] [-x print Excel] [-csv print CSV] [-h print histogram] [-off N instrumentation offset]")
+    exit()
+
+# Custom Parameters: Parameters used in the script that can be altered for
+# different uses, applications, or localizations
+arguments = argv[1:]
+should_log = "-v" in arguments
+separate_callsite = "-t" in arguments
+print_excel = "-x" in arguments
+print_csv = "-csv" in arguments
+should_print_hist = "-h" in arguments
+instrumentation_entry_offset = 0
+instrumentation_exit_offset = 0
+# Manual Instrumentation Offset: Use this sparingly and only if the value
+# calculated by the instrumentation hooks themselves is wrong or missing
+has_offset = "-off" in arguments
+instrumentation_entry_offset = 0
+instrumentation_exit_offset = 0
+if has_offset:
+    try:
+        instrumentation_entry_offset = int(arguments.pop(arguments.index("-off")+1))
+        instrumentation_exit_offset = int(arguments.pop(arguments.index("-off")+2))
+    except ValueError:
+        readerror()
+flags = [x for x in arguments if re.search('-',x)]
+files = [x for x in arguments if (x not in flags and x != "" and x != " ")]
+
+overall_label = "[overall]"
+enter_keyword = "ENTER"
+exit_keyword = "EXIT "
+xlfilename = "report"
+log_delimiter = "\n"
+main_func_name = "main"
+histogram_bins = 10
+executable = None
+if separate_callsite:
+    headers = [
+        "FUNCTION","REFERENCED BY", "TOTAL CYCLES (inc)", "TOTAL CYCLES (exc)",
+        "AVG CYCLES (inc)","AVG CYCLES(exc)", "TOTAL CALLS", "ITER"]
+else:
+    headers = [
+        "FUNCTION", "TOTAL CYCLES (inc)", "TOTAL CYCLES (exc)", "AVG CYCLES (inc)",
+        "AVG CYCLES (exc)", "TOTAL CALLS", "ITER"]
+histogramlabel = "Histogram"
+binlabels = ["Low","High","Bin Size","Notes"]
+devicelabels = ["Unknown Device","ARM","DSP","M4"]
+
+# Boilerplate Functions: Used for simple operations throughout the script:
+# * Returning the first element in a list that matches a query
+def first(iterable):
+        for element in iterable:
+            return element
+        return None
+# * Returning a list of subarrays, or "chunks," iterable based on a given size
+def chunks(array, size):
+    # Note: This is an iterable; seen throughout this script and is a standard
+    # Python syntax. Don't be afraid of iterables! They're fairly simple:
+    #      objects of desired attr... with value...  in the array...
+    return (array[pos:pos + size] for pos in xrange(0, len(array), size))
+    #       subarrays for every...    index... in sequence... 0,1*size,2*size...
+    #      ...then returned as a list
+    #    You can think of iterables as a "for" loop that compares a given
+    #    attribute and assembles an array of objects with that attribute. The
+    #    attribute can be a comparison, but in this case, is used as the lower
+    #    and upper bounds of a subarray
+# * Parsing an input list into an array, using a predefined delimitor
+def split(input):
+    txt = str(input)
+    parsed_logs = txt.split(log_delimiter)
+    return parsed_logs
+
+FuncNode = namedtuple('FuncNode',['lowpc','highpc','namestring'],verbose=False)
+## @brief Build Function List
+#
+# Creates a lookup table from the given DWARF symbol
+# table, based on the assembly addresses of each function
+# Note: For both functions, named tuples are used instead of objects. Although
+#        they are functionally the same, tuples hold values in a static context,
+#        in Python, resulting in a faster access and search time
+def parse_dwarf(dwarfinfo):
+    if should_log:
+        print("")
+        print("Building DWARF lookup table...")
+    templist = []
+    for CU in dwarfinfo.iter_CUs():
+        for DIE in CU.iter_DIEs():
+            try:
+                # Using each DIE (Debugging Information Entry), the lower and
+                # upper bounds of a function (subprogram) are recorded. This
+                # takes into account entries that may only have a length instead
+                # of an upper-bound attribute
+                if DIE.tag == 'DW_TAG_subprogram':
+                    lowpc = DIE.attributes['DW_AT_low_pc'].value
+                    highpc_attr = DIE.attributes['DW_AT_high_pc']
+                    highpc_attr_class = describe_form_class(highpc_attr.form)
+                    if highpc_attr_class == 'address':
+                        highpc = highpc_attr.value
+                    elif highpc_attr_class == 'constant':
+                        highpc = lowpc + highpc_attr.value
+                    else:
+                        highpc = 0
+                    namestring = bytes2str(DIE.attributes['DW_AT_name'].value)
+                    if lowpc > 0:
+                        templist.append(
+                            FuncNode(
+                                lowpc = lowpc, highpc = highpc,
+                                namestring = namestring))
+            except KeyError:
+                continue
+    if should_log:
+        for temp in templist:
+            print(temp.namestring+": "+str(temp.lowpc)+"/"+str(temp.highpc))
+    return sorted(templist, key=lambda x: x.lowpc)
+## @brief Secondary Build Function List
+# Creates a secondary function list based on the
+# symbol table in actual executable itself, as some symbols seem to be lost or
+# ignored in the DWARF table, possibly due to function pointers
+def parse_exec(elf_executable):
+    dump_command = "python "+os.path.dirname(os.path.realpath(__file__))+"/readelf.py -s "+elf_executable
+    if should_log:
+        print("")
+        print("Building secondary lookup table from elf dump...")
+        print (dump_command)
+    process = subprocess.Popen(dump_command, shell=True, stdout=subprocess.PIPE)
+    output = process.stdout.read()
+    symbols = output.split("\n")
+    templist = []
+    for symbol in symbols:
+        func_params = symbol.split()
+        if len(func_params) == 8 and func_params[3] == 'FUNC':
+            lowpc = int(func_params[1],16)
+            highpc = lowpc + int(func_params[2])
+            namestring = str(func_params[7])
+            templist.append(
+                FuncNode(
+                    lowpc = lowpc, highpc = highpc, namestring = namestring))
+    if should_log:
+        for temp in templist:
+            print(temp.namestring+": "+str(temp.lowpc)+":"+str(temp.highpc))
+    return sorted(templist, key=lambda x: x.lowpc)
+
+## @brief Binary Search
+# Used for quick lookup of a given address from a given lookup table
+def binsearch(address, sym_dw_list):
+    first = 0
+    last = len(sym_dw_list) - 1
+    while first <= last:
+        mid = (first + last)/2
+        if sym_dw_list[mid].lowpc <= address < sym_dw_list[mid].highpc:
+            return sym_dw_list[mid].namestring
+        if sym_dw_list[mid].lowpc > address:
+            last = mid-1
+        else:
+            first = mid+1
+    return None
+
+## @brief Function Name Lookup
+# Resolves the function name of the hex assembly address
+# provided in the lookup tables. Note: If the function is not found in the
+# symbol table generated from the DWARF table, the secondary table is searched
+# as well. There is currently an issue with the pyelftools library in processing
+# certain functions or function pointers
+def lookup_funcname(addresshex, sym_dw_list, sym_ex_list):
+    if addresshex == None or addresshex == overall_label or addresshex == '':
+        return None
+    address = addresshex
+    namestring = binsearch(address, sym_dw_list)
+    if namestring == None:
+        namestring = binsearch(address, sym_ex_list)
+    if namestring != None:
+        return namestring
+    else:
+        if should_log:
+            print("Could not resolve "+str(addresshex)+". Check your ELF file for consistency")
+        return str(addresshex)
+
+## @brief Outprint Logs
+# Prints each entry of the log passed into the script with
+# entry/exit labels, each function's resolved name, and timestamp
+def print_logs(logs, sym_dw_list, sym_ex_list):
+    print("")
+    print("Resolving logs of "+executable+"...")
+    for chunk in chunks(logs, 4):
+        if chunk[0] != '':
+            is_enter = int(chunk[0], 16)
+            fn_addr = int(chunk[1],16)
+            ref_addr = int(chunk[2],16)
+            timestamp = chunk[3]
+            if is_enter == 1:
+                fn_name = lookup_funcname(fn_addr, sym_dw_list, sym_ex_list)
+                print(enter_keyword+" "+fn_name+" "+timestamp)
+            elif is_enter == 0:
+                fn_name = lookup_funcname(fn_addr, sym_dw_list, sym_ex_list)
+                print(exit_keyword+" "+fn_name+" "+timestamp)
+            # The first quartet of the log is the exec information, consisting
+            #    of the device type, instrumentation time offset, and potentially
+            #    more information in future iterations
+            elif is_enter == 2:
+                # Uses the localized device descriptions above for logging
+                arch_type = fn_addr
+                if arch_type == 1 or arch_type == 2 or arch_type == 3:
+                    device = devicelabels[arch_type]
+                else:
+                    device = devicelabels[0]
+                print(device+" Log with time offset "+timestamp)
+
+## @brief Expand Timestamp
+# Utilizes the fact log entry timestamps are increasing 32-bit
+# unsigned integers, tracking each timestamp's overflow to expand it to 64-bit
+last_clock = 0
+high_clock = 0
+def expand_timestamp(low_clock):
+    global high_clock
+    global last_clock
+    if (last_clock & 2147483648) and not (low_clock & 2147483648):
+        high_clock += 1
+    last_clock = low_clock
+    new_clock = (high_clock << 32) | low_clock
+    return new_clock
+
+## @brief Increment Object
+# Stores total measurements counted during processing to be
+# printed once processing is complete
+class PrintNode(object):
+        def __init__(
+                self, fn_name, ref_addr, cycles_inc,cycles_exc, calls_inc,
+                calls_exc, count):
+            self.fn_name = fn_name
+            self.ref_addr = ref_addr
+            self.cycles_inc = cycles_inc
+            self.cycles_exc = cycles_exc
+            self.calls_inc = calls_inc
+            self.calls_exc = calls_exc
+            self.iter = count
+            self.histogram = []
+def increment_obj(print_list,tempexc,tempinc,should_append_overall):
+    if should_append_overall:
+        # Note that if the user opts to separate logs by callsite, this function
+        #    is called again to maintain another printnode object of the total
+        #    measurements
+        increment_obj(print_list,tempexc,tempinc,False)
+        tempobj = first(temp for temp in print_list if (
+            temp.fn_name == tempinc.fn_name and
+            temp.ref_addr == tempinc.ref_addr))
+    else:
+        tempobj = first(temp for temp in print_list if (
+            temp.fn_name == tempinc.fn_name and
+            temp.ref_addr == overall_label))
+    if tempobj != None:
+        tempindex = print_list.index(tempobj)
+        print_list[tempindex].cycles_exc += tempexc.time
+        print_list[tempindex].cycles_inc += tempinc.time
+        print_list[tempindex].calls_exc = tempexc.iter
+        print_list[tempindex].calls_inc = tempinc.iter
+        print_list[tempindex].iter += 1
+    else:
+        if should_append_overall:
+            print_list.append(
+                PrintNode(
+                    tempexc.fn_name, tempexc.ref_addr, tempinc.time,
+                    tempexc.time, tempinc.iter, tempexc.iter, 1))
+        else:
+            if separate_callsite:
+                tempobj1 = first(temp for temp in print_list if (
+                    temp.fn_name == tempinc.fn_name and
+                    temp.ref_addr != tempinc.ref_addr))
+                if tempobj1 != None:
+                    tempobj1 = copy.copy(tempobj1)
+                    tempobj1.ref_addr = overall_label
+                    print_list.append(tempobj1)
+                    increment_obj(print_list,tempexc,tempinc,False)
+            else:
+                print_list.append(
+                    PrintNode(
+                        tempexc.fn_name, overall_label, tempinc.time,
+                        tempexc.time, tempinc.iter, tempexc.iter, 1))
+
+## @brief Exit Log
+# Handles "exit" log entries, calculating the time elapsed by each
+# function and the total cycles required. Note:
+#    * The inclusive time elapsed by a function is added to the timestamp of
+#      the top function of the exclusive stack so that the time taken by the
+#      inclusive function is not included in the exclusive function
+def log_exit(log_list,print_list,timestamp,stack_exc,stack_inc,instrumentation_entry_offset,instrumentation_exit_offset):
+    tempinc = stack_inc.pop()
+    tempexc = stack_exc.pop()
+    tempinc.time = timestamp-tempinc.time+instrumentation_exit_offset
+    tempexc.time = timestamp-tempexc.time-instrumentation_entry_offset
+    if len(stack_exc) != 0:
+        stack_inc[len(stack_inc)-1].iter += tempinc.iter
+        stack_exc[len(stack_exc)-1].time += tempinc.time
+    tempstring = "    "*(len(stack_inc)+1)+str(tempinc.time)+" cycles, at "+str(tempinc.iter)+" fn calls inc"+"\n"+"    "*(len(stack_inc)+1)+str(tempexc.time)+" cycles, at "+str(tempexc.iter)+" fn calls exc"+"\n"+"    "*len(stack_inc)+"}" # + "  " + str(timestamp)
+    if should_log:
+        print(tempstring)
+    increment_obj(print_list,tempexc,tempinc,separate_callsite)
+    log_list.append(tempexc)
+    if len(stack_inc) == 0:
+        return tempstring, tempinc.time, 1
+    else:
+        return tempstring, 0, 0        
+
+## @brief Process Logs
+# Iterates through each log entry and processes entry/exit pairs
+#    to calculate time elapsed, total calls, and iterations while resolving the
+#    name of each function for the final printout. Note:
+#    * "Calls" are defined as instrumented function calls that are made by a
+#      given function
+#    * "Cycles" are the total number of processor ticks elapsed by the function
+#    * "Iterations" are the number of references, or times the single function
+#      is called
+class LogNode(object):
+    def __init__(self, fn_addr, fn_name, ref_addr, time, count):
+        self.fn_addr = fn_addr
+        self.fn_name = fn_name
+        self.ref_addr = ref_addr
+        self.time = time
+        self.iter = count
+def process_logs(arch_list,logs,sym_dw_list, sym_ex_list):
+    arch_list_size = len(arch_list)
+    log_list = []
+    print_list = []
+    out_buffer = ""
+    if should_log:
+        print("")
+        print("Counting iterations of "+executable+":")
+    stack_inc = deque([])
+    stack_exc = deque([])
+    task_stack_dict_inc = {}
+    task_stack_dict_exc = {}
+    task_timestamp_dict_inc = {}
+    task_timestamp_dict_exc = {}
+    task_timestamp_dict_idle = {}
+    task_timestamp_cycle_inc = {}
+    last_timestamp = 0
+    idle_time_flag = 0
+    cycle_count_inc = 0
+    cycle_count_inc1 = 0
+    cycle_count_idle = 0
+    cycle_count_idle1 = 0
+    cycle_count_offset = 0
+    # this factor decides if clock for core and timer is different.
+    divide_factor = 1
+    for chunk in chunks(logs, 4):
+        if chunk[0] != '':
+            # Break each chunk, or log, into its individual attributes. Note
+            # that each value is in hex
+            is_enter = int(chunk[0], 16)
+            fn_addr = int(chunk[1], 16)
+            ref_addr = int(chunk[2], 16)
+            timestamp = (expand_timestamp(int(chunk[3], 16)) / divide_factor)
+            if is_enter == 1:
+                fn_name = lookup_funcname(fn_addr, sym_dw_list, sym_ex_list)
+                if separate_callsite:
+                    cs_name = lookup_funcname(ref_addr, sym_dw_list, sym_ex_list)
+                else:
+                    cs_name = ref_addr
+                if len(stack_inc) != 0:
+                    stack_inc[len(stack_inc)-1].iter += 1
+                    stack_exc[len(stack_exc)-1].iter += 1
+                # Used for debugging and for logging output:
+                tempstring = "    "*len(stack_inc)+str(fn_name)+" {    " # + str(fn_addr) + "  " + str(timestamp)
+                out_buffer += tempstring+"\n"
+                if should_log:
+                    print(tempstring)
+                # Programs compiled with GCC have an extra "call_site" attribute
+                # that records the function that called the function currently
+                # being instrumented. If this information is not provided,
+                # likely because the program used the TI compiler, the address
+                # of the last function on the stack is used instead
+                if ref_addr == 0:
+                    tempinc = LogNode(fn_addr,fn_name,"",timestamp,0)
+                    tempexc = LogNode(fn_addr,fn_name,"",timestamp,0)
+                    if len(stack_inc) != 0:
+                        tempinc.ref_addr = stack_inc[len(stack_inc)-1].fn_name
+                        tempexc.ref_addr = stack_inc[len(stack_exc)-1].fn_name
+                else:
+                    tempinc = LogNode(fn_addr,fn_name,cs_name,timestamp,0)
+                    tempexc = LogNode(fn_addr,fn_name,cs_name,timestamp,0)
+                stack_inc.append(tempinc)
+                stack_exc.append(tempexc)
+                if idle_time_flag != 0:
+                    cycle_count_idle = cycle_count_idle + timestamp - last_timestamp
+                    idle_time_flag = 0
+            elif is_enter == 0:
+                fn_name = lookup_funcname(fn_addr, sym_dw_list, sym_ex_list)
+                # The exit log is matched to the entry hook to ensure that no
+                # functions are unaccounted for. This can become problematic
+                # so the last function on the stack is removed before proceeding
+                if fn_addr == stack_inc[len(stack_inc)-1].fn_addr:
+                    tempstring, temp_count, idle_time_flag = log_exit(log_list,print_list,timestamp,stack_exc,stack_inc,instrumentation_entry_offset,instrumentation_exit_offset)
+                    cycle_count_inc = cycle_count_inc + temp_count
+                    cycle_count_offset += instrumentation_exit_offset+instrumentation_entry_offset
+                    out_buffer += tempstring+"\n"
+                    if idle_time_flag != 0:
+                        last_timestamp = timestamp
+                else:
+                    print("Inconsistency error. Function exit \""+stack_inc[len(stack_inc)-1].fn_name+"\" does not match function begin \""+fn_name+"\" on stack")
+                    stack_inc.pop()
+                    stack_exc.pop()
+            elif is_enter == 2:
+                # The first log generated by the programming hooks contains
+                # the processor type and the measured instrumentation offset
+                if fn_addr == 1:
+                    arch_list.append("ARM")
+                    divide_factor = 1
+                elif fn_addr == 2:
+                    arch_list.append("DSP")
+                    divide_factor = 1
+                elif fn_addr == 3:
+                    arch_list.append("M4")
+                    # timer clock for m4 is running at twice the speed of processor speed i.e. 40 Mhz
+                    divide_factor = 2
+                else:
+                    arch_list.append("UNKNOWN")
+                if ref_addr == 1:
+                    # the first timestamp has already been taken so need to divide it specially
+                    # for the next case, it will be divided by the required factor automatically
+                    # as divide factor has been set correct value.
+                    instrumentation_entry_offset = timestamp/divide_factor
+                else:
+                    instrumentation_exit_offset = timestamp
+            elif is_enter == 3:
+                # The task switch log generated for handling the case of context 
+                # switch, so the inconsistancy between entry/exit hooks can be matched
+                if ref_addr == 0:
+                    task_stack_dict_inc[fn_addr] = stack_inc
+                    task_stack_dict_exc[fn_addr] = stack_exc
+                    task_timestamp_dict_inc[fn_addr] = timestamp
+                    task_timestamp_dict_exc[fn_addr] = timestamp
+                    task_timestamp_dict_idle[fn_addr] = cycle_count_idle
+                    task_timestamp_cycle_inc[fn_addr] = cycle_count_inc
+                else:
+                    if idle_time_flag != 0:
+                        cycle_count_idle = cycle_count_idle + timestamp - last_timestamp
+                        idle_time_flag = 0                        
+                    if (ref_addr in task_stack_dict_inc) and (ref_addr in task_stack_dict_exc):
+                        task_stack_dict_inc[ref_addr] = stack_inc
+                        task_stack_dict_exc[ref_addr] = stack_exc
+                        task_timestamp_dict_inc[ref_addr] = timestamp
+                        task_timestamp_dict_exc[ref_addr] = timestamp
+                        task_timestamp_dict_idle[ref_addr] = cycle_count_idle
+                        task_timestamp_cycle_inc[ref_addr] = cycle_count_inc
+                        stack_inc = deque([])
+                        stack_exc = deque([])
+
+                        if fn_addr in task_stack_dict_inc:
+                            stack_inc1 = task_stack_dict_inc[fn_addr]
+                            stack_exc1 = task_stack_dict_exc[fn_addr]
+                            old_timestamp = task_timestamp_dict_inc[fn_addr]
+                            cycle_count_idle = task_timestamp_dict_idle[fn_addr]
+                            cycle_count_inc = task_timestamp_cycle_inc[fn_addr]
+                            while True:
+                                try:
+                                    tempLog = stack_inc1.popleft()
+                                    tempLog.time = tempLog.time + timestamp - old_timestamp
+                                    stack_inc.append(tempLog) 
+                                except IndexError:
+                                    break
+                            while True:
+                                try:
+                                    tempLog = stack_exc1.popleft()
+                                    tempLog.time = tempLog.time + timestamp - old_timestamp
+                                    stack_exc.append(tempLog) 
+                                except IndexError:
+                                    break  
+                            if len(stack_inc) == 0:
+                                idle_time_flag = 1
+                                last_timestamp = timestamp                
+                        else:
+                            idle_time_flag = 1
+                            last_timestamp = timestamp
+                            cycle_count_idle = 0
+                            cycle_count_inc = 0
+
+                        task_stack_dict_inc[fn_addr] = deque([])
+                        task_stack_dict_exc[fn_addr] = deque([])
+                        task_timestamp_dict_idle[fn_addr] = 0    
+                        task_timestamp_cycle_inc[fn_addr] = 0
+                    else:
+                        print("Inconsistency error. Current task is not in the task list")
+                    
+    # Note: For consistency, the remaining enter entries that have not been
+    #    matched with an exit entry are counted for consistency. This is because
+    #    some functions, such as main, may never reach an entry hook at runtime
+    if len(stack_inc) != 0:
+        if should_log:
+            print("Parsing remaining function calls that are missing exit hooks:")
+        while not len(stack_inc) == 0:
+            tempstring, temp_count, idle_time_flag = log_exit(log_list,print_list,timestamp,stack_exc,stack_inc,instrumentation_entry_offset,instrumentation_exit_offset)
+            cycle_count_inc = cycle_count_inc + temp_count
+            cycle_count_offset += instrumentation_exit_offset+instrumentation_entry_offset
+            out_buffer += tempstring+"\n"
+    cycle_count_inc1 = cycle_count_inc1 + cycle_count_inc
+    cycle_count_idle1 = cycle_count_idle1 + cycle_count_idle
+    for stck in task_stack_dict_inc:
+        stack_inc = task_stack_dict_inc[stck]
+        stack_exc = task_stack_dict_exc[stck]
+        cycle_count_idle = task_timestamp_dict_idle[stck]
+        cycle_count_inc = task_timestamp_cycle_inc[stck]
+        if len(stack_inc) != 0:
+            timestamp = task_timestamp_dict_exc[stck]
+            if should_log:
+                print("Parsing remaining function calls that are missing exit hooks:")
+            while not len(stack_inc) == 0:
+                tempstring, temp_count, idle_time_flag = log_exit(log_list,print_list,timestamp,stack_exc,stack_inc,instrumentation_entry_offset,instrumentation_exit_offset)
+                cycle_count_inc = cycle_count_inc + temp_count
+                cycle_count_offset += instrumentation_exit_offset+instrumentation_entry_offset
+                out_buffer += tempstring+"\n"
+        cycle_count_inc1 = cycle_count_inc1 + cycle_count_inc
+        cycle_count_idle1 = cycle_count_idle1 + cycle_count_idle
+    cycle_count_inc1 = cycle_count_inc1 ++ cycle_count_idle1
+    print_list.append(PrintNode("Idle cycle", overall_label, cycle_count_idle1,
+                                cycle_count_idle1, 0, 0, 1))
+    if len(print_list) == 0:
+        print("No parsable logs found. Check enter and exit keywords and/or whether the program has the correct format.")
+        exit()
+    if len(arch_list) == arch_list_size:
+        arch_list.append("UNKNOWN")
+    return print_list,log_list,out_buffer,cycle_count_inc1,cycle_count_offset
+
+## @brief Get Dwarf
+# Reads the ELF and DWARF information of the given executable
+def get_dwarf(func):
+    if should_log:
+        print("")
+        print("Reading ELF from "+func+"...")
+    if func[0:2] == "./":
+        func = func[2:]
+    with open(func, 'rb') as stream:
+        elffile = ELFFile(stream)
+        section = elffile.get_section_by_name('.symtab')
+        if not section:
+            print("No Symbol Table found in ELF. Perhaps you didn't include the function instrumentation flag(s) when compiling?")
+        elif not elffile.has_dwarf_info():
+            print("No DWARF info found in ELF. Perhaps you didn't include -g when compiling?")
+        else:
+            dwarfinfo = elffile.get_dwarf_info()
+            return dwarfinfo
+    return None
+
+## @brief Verify Values
+# Verifies the values of the processing function by:
+#    * Comparing the sum of all exclusive time values with the total
+#      (inclusive) time value of main, the lowest-level function
+def verify_values(print_list,cycle_count_inc,cycle_count_offset):
+    if should_log:
+        print("Sanity-checking values...")
+    excsum = 0
+    for obj in print_list:
+        if separate_callsite and obj.ref_addr != overall_label:
+            excsum += obj.cycles_exc
+        elif not separate_callsite:
+            excsum += obj.cycles_exc
+    
+    excsum += cycle_count_offset
+    if should_log:
+        print("No of offset cycle :"+str(cycle_count_offset))
+
+    if excsum == cycle_count_inc:
+        if should_log:
+            print("Exclusive cycle count matches total cycle count")
+            print("exclusive cycle count      "+str(excsum))
+            print("inclusive cycle count      "+str(cycle_count_inc))
+        return True
+    else:
+        print("Exclusive cycle count does NOT match total cycle count. Check input for inconsistency")
+        print("exclusive cycle count      "+str(excsum))
+        print("inclusive cycle count      "+str(cycle_count_inc))
+        return True
+
+## @brief Tabulate Table
+# Organizes the total values into sorted lists that will be
+#    printed to the terminal, a text file, and to a .xlsx file, should the user
+#    choose to do so. The main goal of this function is to merge each node
+#    generated from each executable by function to be printed
+def tabulate_table(arch_list,print_list_cols):
+    tab_out_list = []
+    if should_log:
+        print("")
+        print("Final Report of "+executable+":")
+    i = 0
+    for print_list in print_list_cols:
+        if separate_callsite:
+            sorted_print_list = sorted(print_list, key=lambda obj: (
+                obj.cycles_exc/obj.iter,obj.ref_addr == overall_label,obj.fn_name))
+        else:
+            sorted_print_list = sorted(print_list, key=lambda obj: (obj.cycles_exc/obj.iter))
+        # Since the tabulate library uses a list of lists to form its table
+        # structure, the data set is filled as if it were a table traversing
+        # left, then down. As such, empty cells also need to be accounted for
+        # E.g. Example List: [[elem1, elem2],["",elem3],[elem4, elem5, elem6]]
+        #       Example Table:    attr1    attr2    attr3
+        #                        -----    -----    -----
+        #                        elem1    elem2    elem3
+        #                        elem4    elem5    elem6
+        for obj in sorted_print_list:
+            if separate_callsite:
+                funcitem = first(temp for temp in tab_out_list if (temp.fn_name == obj.fn_name and temp.ref_addr == obj.ref_addr))
+            else:
+                funcitem = first(temp for temp in tab_out_list if temp.fn_name == obj.fn_name)
+            if funcitem == None:
+                funcitem = PrintNode(obj.fn_name,obj.ref_addr,[""]*i + [obj.cycles_inc],[""]*i + [obj.cycles_exc],[""]*i + [obj.calls_inc],[""]*i + [obj.calls_exc],[0]*i + [obj.iter])
+                tab_out_list.append(funcitem)
+            else:
+                funcitem.cycles_inc.append(obj.cycles_inc)
+                funcitem.cycles_exc.append(obj.cycles_exc)
+                funcitem.calls_inc.append(obj.calls_inc)
+                funcitem.calls_exc.append(obj.calls_exc)
+                funcitem.iter.append(obj.iter)
+        # For programs that are missing the functions that are in another, empty
+        # Entries are added to the columns for consistency (see above)
+        for otherobj in [obj for obj in tab_out_list if len(obj.cycles_inc) == i]:
+            otherobj.cycles_inc.append("")
+            otherobj.cycles_exc.append("")
+            otherobj.calls_inc.append("")
+            otherobj.calls_exc.append("")
+            otherobj.iter.append(0)
+        i += 1
+    headerlist = [headers.pop(0)]
+    if separate_callsite:
+        # If the user opts to separate the function logs by call site, another
+        # column is added to distinguish one from another from the overall log
+        # of that function
+        headerlist.append(headers.pop(0))
+    preheader_size = len(headerlist)
+    for i in range(0,len(headers)):
+        # This is also a standard Python syntax: multiplying strings. This
+        # operator simply appends copies of the string passed, in this case,
+        # the table headers to represent each processor type
+        headerlist.extend([headers[i]]*(len(print_list_cols)))
+    for i in range(0,len(print_list_cols)*len(headers)):
+        j = i+preheader_size
+        headerlist[j]+=" "+arch_list[i%len(print_list_cols)]
+    return tab_out_list,headerlist
+
+## @brief Print Final
+# Uses the tabulated data list to create the final output table
+def print_final(tab_out_list,headerlist,parity,out_buffer,num_print_tries):
+    tabulated_list = []
+    # Checks if the filename specified already exists, to prevent overwriting
+    # data. If so, the name is incremented
+    if (os.path.isfile(xlfilename+".txt")):
+        num_print_tries += 1
+        while os.path.isfile(xlfilename+str(num_print_tries)+".txt"):
+            num_print_tries += 1
+    # The code below simply converts the merged print nodes into lists that
+    # can be processed by the tabulate library
+    for merged_node in tab_out_list:
+        temp = [merged_node.fn_name] #Initialize an array with the first element
+        if separate_callsite:
+            temp.append(merged_node.ref_addr)
+        # Append the Total Cycles (inc)
+        temp.extend(merged_node.cycles_inc)
+        # Append the Total Cycles (exc)
+        for i in range(0,len(merged_node.iter)):
+            if merged_node.cycles_exc[i] < 0:
+                # appending 0 in the situation where time interval is too small to benchmark
+                temp.extend("0")
+            else:
+                temp.extend(merged_node.cycles_exc)
+        # Append the Average Cycles (inc)
+        for i in range(0,len(merged_node.iter)):
+            if merged_node.iter[i] != 0:
+                temp.append(merged_node.cycles_inc[i]/merged_node.iter[i])
+            else:
+                temp.append("")
+        # Append the Average Cycles (exc)
+        for i in range(0,len(merged_node.iter)):
+            if merged_node.iter[i] != 0:
+                if merged_node.cycles_exc[i] < 0:
+                    temp.append("0")
+                else:
+                    temp.append(merged_node.cycles_exc[i]/merged_node.iter[i])
+            else:
+                temp.append("")
+        # Append the Total Calls
+        temp.extend(merged_node.calls_exc)
+        # Append the Iterations
+        temp.extend(merged_node.iter)
+        # Added space for safety when printing (consistent array lengths)
+        temp.append("")
+        # Append the function histogram
+        temp.extend(merged_node.histogram)
+        tabulated_list.append(temp)
+
+    text_table = tabulate(tabulated_list, headerlist, tablefmt="simple")
+    print(text_table)
+    if print_excel:
+        if should_log:
+            print("Writing to Excel...")
+        if num_print_tries == 0:
+            workbook = xlsxwriter.Workbook(xlfilename+".xlsx")
+        else:
+            workbook = xlsxwriter.Workbook(xlfilename+str(num_print_tries)+".xlsx")
+        worksheet = workbook.add_worksheet()
+        # Formats the text, such that:
+        #    * Column headers (first row) are bold and frozen
+        #    * Function names (first column) are bold and frozen
+        header_format = workbook.add_format(
+            {'bold': True, 'align': 'center', 'valign': 'vcenter'})
+        header_format.set_text_wrap()
+        worksheet.freeze_panes(1, 1)
+        #    * Attribute columns are 20 spaces wide
+        #    * Histogram columns are 10 spaces wide
+        #    * Notes column and beyond are 150 spaces wide
+        for i, col in enumerate(headerlist):
+            worksheet.write(0,i,col,header_format)
+            worksheet.set_column(i,i,20)
+            if (i > (parity*7)):
+                worksheet.set_column(i,i,10)
+            if (i > (parity*7)+histogram_bins+4):
+                worksheet.set_column(i,i,150)
+        #    * Function column is 35 spaces wide
+        worksheet.set_column(0,0,35)
+        #    * All attribute columns are colored by parity for easy-viewing.
+        #      There will likely be no more than four executables compared in
+        #      a given report, but in case there are, more colors can be added
+        for i, l in enumerate(tabulated_list):
+            for j, col in enumerate(l):
+                if (j < parity*7+1):
+                    if (j == 0):
+                        text_format = workbook.add_format({'bold':True})
+                    elif (j%parity == 0):
+                        text_format = workbook.add_format({'color':'blue'})
+                    elif (j%parity == 1):
+                        text_format = workbook.add_format({'color':'black'})
+                    elif (j%parity == 2):
+                        text_format = workbook.add_format({'color':'green'})
+                    elif (j%parity == 3):
+                        text_format = workbook.add_format({'color':'purple'})
+                else:
+                    text_format = workbook.add_format({'bold':False,'color':'black'})
+                worksheet.write(i+1,j,col,text_format)
+        try:
+            # XLSXWriter will attempt to write to the filename assigned above,
+            # in the same directory as the script. If the filename is already
+            # taken and cannot be overwritten, a number is appended to the
+            # filename
+            workbook.close()
+        except IOError:
+            print("Could not write to file. Close any open instances of the report file and try again.")
+            exit()
+    if print_csv:
+        if num_print_tries == 0:
+            csvNameString = xlfilename+".csv"
+        else:
+            csvNameString = xlfilename+str(num_print_tries)+".csv"
+        with open(csvNameString, 'wb') as csvfile:
+            csvwriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
+            csvwriter.writerow(headerlist)
+            for csvrow in tabulated_list:
+                csvwriter.writerow(csvrow)
+    if num_print_tries == 0:
+        reportfile = open(xlfilename+".txt", 'w')
+    else:
+        reportfile = open(xlfilename+str(num_print_tries)+".txt",'w')
+    reportfile.write(text_table+"\n"*2+out_buffer)
+    reportfile.close()
+
+## @brief Resolve File
+# Similar to the resolve function name function above, but instead
+# searches for the file and line number of the reference provided
+def resolve_file(dwarfinfo, addresshex):
+    address = addresshex
+    for CU in dwarfinfo.iter_CUs():
+        lineprog = dwarfinfo.line_program_for_CU(CU)
+        prevstate = None
+        for entry in lineprog.get_entries():
+            if entry.state is None or entry.state.end_sequence:
+                continue
+            if prevstate and prevstate.address <= address < entry.state.address:
+                filename = lineprog['file_entry'][prevstate.file - 1].name
+                line = prevstate.line
+                return filename, line
+            prevstate = entry.state
+    return None, None
+
+## @brief Tabulate Histogram
+# Uses the list values to create a histogram with the bin
+# count specified above
+def tabulate_histogram(printlist,log_pr_list,dwarfinfo,sym_dw_list,sym_ex_list):
+    parse_logs_combined = [j for i in log_pr_list for j in i]
+    if should_log:
+        print("")
+        print("Building Histogram...")
+    for printitem in printlist:
+        if printitem.iter[0] > 1:
+            # For every Print Node (function) a histogram is built if it has
+            # more than one reference in the log. This is used to determine the
+            # normalized scale and if there are any abnormally inefficient
+            # references
+            if separate_callsite and printitem.ref_addr != overall_label:
+                func_sublist = [func for func in parse_logs_combined if (func.fn_name ==
+                    printitem.fn_name and func.ref_addr == printitem.ref_addr)]
+            else:
+                func_sublist = [func for func in parse_logs_combined if func.fn_name ==
+                    printitem.fn_name]
+            maxvalue = max(obj.time for obj in func_sublist)
+            minvalue = min(obj.time for obj in func_sublist)
+            mintemp = minvalue
+            binsize = ((maxvalue-minvalue)/(histogram_bins-1))
+            frequencylist = []
+            bin_idx = 0
+            # The bucket frequency values are appended to the frequency list in
+            # the same manner they were populated in the tabulate function
+            if binsize > 0:
+                while bin_idx < histogram_bins-1:
+                    frequencylist.append(0)
+                    for obj in func_sublist:
+                        if minvalue <= obj.time < (minvalue + binsize):
+                            frequencylist[bin_idx] += 1
+                    bin_idx += 1
+                    minvalue += binsize
+                frequencylist.append(0)
+                for obj in func_sublist:
+                    if minvalue <= obj.time <= maxvalue:
+                        frequencylist[bin_idx] += 1
+            else:
+                for i in range(0,histogram_bins):
+                    frequencylist.append("")
+            # Append the min, max, and bin size values
+            frequencylist.append(mintemp)
+            frequencylist.append(maxvalue)
+            frequencylist.append(binsize)
+            # The outlier function (if there is one) is then resolved and added
+            # to the notes section of the report for debugging
+            if binsize > 0:
+                if dwarfinfo != None:
+                    bigfunc = max(func_sublist, key=attrgetter('time'))
+                    i = 0
+                    for parse_logs in log_pr_list:
+                        if bigfunc in parse_logs:
+                            break
+                        i += 1
+                    filename, line = resolve_file(dwarfinfo[i],bigfunc.fn_addr)
+                    if frequencylist[0] > sum(frequencylist[1:histogram_bins-1]):
+                        outliermsg = "High outlier function \""+bigfunc.fn_name+"\" "
+                        if bigfunc.ref_addr != None:
+                            outliermsg = outliermsg+"was referenced by \""+str(bigfunc.ref_addr)+"\" "
+                        if filename != None:
+                            outliermsg = outliermsg+"in "+filename+" "
+                            if line != None:
+                                outliermsg = outliermsg+": "+str(line)+" "
+                        frequencylist.append(outliermsg)
+            printitem.histogram = frequencylist
+
+# Program Main
+merged_list = [] # Merged lognodes for printing
+sym_dw_list = [] # Symbols processed from the DWARF symbol information
+sym_ex_list = [] # Symbols processed from the executable, itself
+log_pr_list = [] # Separate lognodes for processing histogram
+dtable_list = [] # List of DWARF symbol tables used for processing and resolution
+out_buffer = ""  # String buffer used to output the trace information and
+                 #    messages to the report text document
+arch_list = []     # Architecture list used to coordinate the architecture labels
+                 #    in the output files
+if len(files) == 0:
+    readerror()
+while len(files) > 0:
+    # Pops files off of the file list to be processed
+    dump_file = files.pop(0)
+    if len(files) == 2:
+        should_print_hist = True
+    executable = files.pop(0)
+    parse_logs = split(open(dump_file).read())
+    if os.path.isfile(executable) and os.access(executable, os.R_OK):
+        dinfo = get_dwarf(executable)
+        # In case the user adds the files in the wrong parity, the two files are
+        #    reversed to try again
+        if dinfo == None:
+            dinfo = get_dwarf(dump_file)
+            executable=dump_file
+        if dinfo != None:
+            dtable_list.append(dinfo)
+            sym_dw_list.append(parse_dwarf(dinfo))
+            sym_ex_list.append(parse_exec(executable))
+        else:
+            readerror()
+    # Determine whether the first entry in the log file is the memory headers,
+    #    which must be removed for processing
+    try:
+        header = int(parse_logs[0])
+    except ValueError:
+        header = None
+    if header != 0 and header != 1:
+        parse_logs.pop(0)
+
+    # For debugging purposes, verbose mode prints each log entry with its
+    #    resolved name and entry/exit
+    if should_log:
+        print_logs(
+            parse_logs,sym_dw_list[len(sym_dw_list)-1],
+            sym_ex_list[len(sym_ex_list)-1])
+
+    # Processes logs into:
+    #    * Print List: used to tabulate the final table for output
+    #    * Log List: used for tabulating the histogram
+    #    * Output Buffer: used to output trace information in the final report
+    # Output is then verified before appended to the final output lists
+    if len(sym_dw_list) == 0:
+        print("Found Zero.")
+
+    printlist,log_list,tempout_buffer,cycle_count_inc,cycle_count_offset = process_logs(arch_list,parse_logs,
+        sym_dw_list[len(sym_dw_list)-1],sym_ex_list[len(sym_ex_list)-1])
+
+    if verify_values(printlist,cycle_count_inc,cycle_count_offset):
+        merged_list.append(printlist)
+        log_pr_list.append(log_list)
+        out_buffer+=arch_list[len(arch_list)-1]+":\n"+tempout_buffer+"\n"*2
+
+if len(merged_list) > 0:
+    tabulated_list,headerlist = tabulate_table(arch_list,merged_list)
+    if should_print_hist:
+        # Histogram headers are added so that they appear in the table
+        headerlist.append(histogramlabel)
+        for i in range(0,histogram_bins):
+            headerlist.append("Bin "+str(i))
+        headerlist.extend(binlabels)
+        tabulate_histogram(
+            tabulated_list,log_pr_list,dtable_list,sym_dw_list,sym_ex_list)
+    else:
+        headerlist.append("")
+    print_final(tabulated_list,headerlist,len(merged_list),out_buffer,0)
+
+if should_log:
+    print("Complete.")
+## @}
diff --git a/packages/ti/utils/profiling/scripts/memXfer.js b/packages/ti/utils/profiling/scripts/memXfer.js
new file mode 100644 (file)
index 0000000..e85b8cc
--- /dev/null
@@ -0,0 +1,272 @@
+/**
+ * @memXfer.js - DSS Generic TI Loader include file that contains functions
+ * used by main.js for host to target memory data transfer.
+ */
+
+/**
+ * Load data from file(s) on host to target memory.
+ *
+ * @param {dssScriptEnv} DSS Scripting Environment object.
+ * @param {debugSession} Debug Session object.
+ * @param {loadRaw} Array of strings, where each string describes a raw file to
+ * memory transfer.
+ * @param {loadDat} Array of strings, where each string describes a text-based
+ * file to memory transfer.
+ */
+function memLoad(dssScriptEnv, debugSession, loadRaw, loadDat)
+{
+    var errCode = 0;
+    var xferNum = 0;
+
+    if (loadRaw.length > 0)
+    {
+               for (xferNum = 0; xferNum < loadRaw.length; xferNum++)
+               {
+                       errCode = loadRawData(dssScriptEnv, debugSession, loadRaw[xferNum]);
+               }
+    }
+
+    if (loadDat.length > 0)
+    {
+        for (xferNum = 0; xferNum < loadDat.length; xferNum++)
+        {
+            errCode = loadDatData(dssScriptEnv, debugSession, loadDat[xferNum]);
+        }
+    }
+
+    return errCode;
+}
+
+/**
+ * Save memory on target to a file(s) on the host.
+ *
+ * @param {dssScriptEnv} DSS Scripting Environment object.
+ * @param {debugSession} Debug Session object.
+ * @param {saveRaw} Array of strings, where each string describes a memory to
+ * raw file transfer.
+ * @param {saveDat} Array of strings, where each string describes a memory to
+ * text-based file transfer.
+ */
+function memSave(dssScriptEnv, debugSession, saveRaw, saveDat)
+{
+    var errCode = 0;
+    var xferNum = 0;
+
+    if (saveRaw.length > 0)
+    {
+               for (xferNum = 0; xferNum < saveRaw.length; xferNum++)
+               {
+                       errCode = saveRawData(dssScriptEnv, debugSession, saveRaw[xferNum]);
+               }
+    }
+
+    if (saveDat.length > 0)
+    {
+        for (xferNum = 0; xferNum < saveDat.length; xferNum++)
+        {
+            errCode = saveDatData(dssScriptEnv, debugSession, saveDat[xferNum]);
+        }
+    }
+
+    return errCode;
+}
+
+/**
+ * Load binary data from file on host to target memory.
+ *
+ * @param {dssScriptEnv} DSS Scripting Environment object.
+ * @param {debugSession} Debug Session object.
+ * @param {parameters} String containing parameters to the actual load, with
+ * format "[page],[address],[filename],[type_size],[byte_swap]".
+ */
+function loadRawData(dssScriptEnv, debugSession, parameters)
+{
+    var errCode = 0;
+
+    matchResult = parameters.match(/([0-4]|65535),(\w+),(.+),(8|16|32),(true|false)/);
+
+    if ((matchResult == null))
+    {
+        dssScriptEnv.traceWrite("--mem_load_raw parameters: " + parameters +
+                               " option are invalid! see loadti --help for parameter specification");
+        errCode = 1;
+    }
+       else
+       {
+        var nPage = parseInt(RegExp.$1);
+        var nAddress = parseInt(RegExp.$2);
+        var sFilename = RegExp.$3;
+        var nTypeSize = parseInt(RegExp.$4);
+        var bByteSwap = false;
+
+        if (RegExp.$5 == "true")
+        {
+            bByteSwap = true;
+        }
+
+        try
+               {
+            debugSession.memory.loadRaw(nPage, nAddress, sFilename, nTypeSize, bByteSwap);
+        }
+               catch (ex)
+               {
+                       errCode = getErrorCode(ex);
+            dssScriptEnv.traceWrite("Error code #" + errCode + ", could not load file " + sFilename +
+                                       " to target memory!");
+        }
+    }
+
+    return errCode;
+}
+
+/**
+ * Load text-based data from file on host to target memory.
+ *
+ * @param {dssScriptEnv} DSS Scripting Environment object.
+ * @param {debugSession} Debug Session object.
+ * @param {parameters} String containing parameters to the actual load, with
+ * format "[page],[address],[filename],[len]".
+ */
+function loadDatData(dssScriptEnv, debugSession, parameters)
+{
+    var errCode = 0;
+
+    matchResult = parameters.match(/([0-4]|65535),(\w+),(.+),(\w+)/);
+
+    if ((matchResult == null))
+    {
+        dssScriptEnv.traceWrite("--mem_load_dat parameters: " + parameters +
+                               " option are invalid! see loadti --help for parameter specification");
+        errCode = 1;
+    }
+       else
+       {
+        var nPage = parseInt(RegExp.$1);
+        var nAddress = parseInt(RegExp.$2);
+        var sFilename = RegExp.$3;
+        var nLength = parseInt(RegExp.$4);
+
+        try
+               {
+            debugSession.memory.loadData(nPage, nAddress, sFilename, nLength);
+        }
+               catch (ex)
+               {
+                       errCode = getErrorCode(ex);
+            dssScriptEnv.traceWrite("Error code #" + errCode + ", could not load file " + sFilename +
+                                       " to target memory!");
+        }
+    }
+
+    return errCode;
+}
+
+/**
+ * Save memory on target to a binary file on the host.
+ *
+ * @param {dssScriptEnv} DSS Scripting Environment object.
+ * @param {debugSession} Debug Session object.
+ * @param {parameters} String containing parameters to the actual save, with
+ * format "[page],[address],[filename],[len],[type_size],[byte_swap]".
+ */
+function saveRawData(dssScriptEnv, debugSession, parameters)
+{
+    var errCode = 0;
+
+    matchResult = parameters.match(/([0-4]|65535),(\w+),(.+),(\w+),(8|16|32),(true|false)/);
+
+    if ((matchResult == null))
+    {
+        dssScriptEnv.traceWrite("--mem_save_raw parameters: " + parameters +
+                               " option are invalid! see loadti --help for parameter specification");
+        errCode = 1;
+    }
+       else
+       {
+        var nPage = parseInt(RegExp.$1);
+        var nAddress = parseInt(RegExp.$2);
+        var sFilename = RegExp.$3;
+        var nLength = parseInt(RegExp.$4);
+        var nTypeSize = parseInt(RegExp.$5);
+        var bByteSwap = false;
+
+        if (RegExp.$6 == "true")
+        {
+            bByteSwap = true;
+        }
+
+        try
+               {
+            debugSession.memory.saveRaw(nPage, nAddress, sFilename, nLength, nTypeSize, bByteSwap);
+        }
+               catch (ex)
+               {
+                       errCode = getErrorCode(ex);
+            dssScriptEnv.traceWrite("Error code #" + errCode + ", could not save memory to host!");
+        }
+    }
+
+    return errCode;
+}
+
+/**
+ * Save memory on target to a text-based file on the host.
+ *
+ * @param {dssScriptEnv} DSS Scripting Environment object.
+ * @param {debugSession} Debug Session object.
+ * @param {parameters} String containing parameters to the actual save, with
+ * format "[page],[address],[filename],[len],[io_format],[append]".
+ */
+function isInteger(value)
+{
+    return !isNaN(value) && parseInt(Number(value)) == value && !isNaN(parseInt(value, 10));
+}
+function saveDatData(dssScriptEnv, debugSession, parameters)
+{
+    var errCode = 0;
+
+    matchResult = parameters.match(/([0-4]|65535),(\w+),(.+),(.+),([1-5]),(true|false)/);
+
+    if ((matchResult == null))
+    {
+        dssScriptEnv.traceWrite("--mem_save_dat parameters: " + parameters +
+                               " option are invalid! see loadti --help for parameter specification");
+        errCode = 1;
+    }
+       else
+       {
+        var nPage = parseInt(RegExp.$1);
+        var addrString = RegExp.$2;
+        if (isInteger(addrString)){
+          var nAddress = parseInt(addrString);
+        }else{
+          var nAddress = debugSession.symbol.getAddress(addrString);
+        }
+        var sFilename = RegExp.$3;
+        var lenString = RegExp.$4;
+        if (isInteger(lenString)){
+          var nLength = parseInt(lenString);
+        }else{
+          var nLength = debugSession.expression.evaluate(lenString);
+        }
+        var nIOFormat = parseInt(RegExp.$5);
+        var bAppend = false;
+
+        if (RegExp.$6 == "true")
+        {
+            bAppend = true;
+        }
+
+        try
+               {
+            debugSession.memory.saveData(nPage, nAddress, sFilename, nLength, nIOFormat, bAppend);
+        }
+               catch (ex)
+               {
+                       errCode = getErrorCode(ex);
+            dssScriptEnv.traceWrite("Error code #" + errCode + ", could not save memory to host!");
+        }
+    }
+
+    return errCode;
+}
diff --git a/packages/ti/utils/profiling/scripts/readelf.py b/packages/ti/utils/profiling/scripts/readelf.py
new file mode 100644 (file)
index 0000000..564ac12
--- /dev/null
@@ -0,0 +1,1171 @@
+#!C:\Python27\python.exe
+#-------------------------------------------------------------------------------
+# scripts/readelf.py
+#
+# A clone of 'readelf' in Python, based on the pyelftools library
+#
+# Eli Bendersky (eliben@gmail.com)
+# This code is in the public domain
+#-------------------------------------------------------------------------------
+import os, sys
+from optparse import OptionParser
+import string
+
+# For running from development directory. It should take precedence over the
+# installed pyelftools.
+sys.path.insert(0, '.')
+
+
+from elftools import __version__
+from elftools.common.exceptions import ELFError
+from elftools.common.py3compat import (
+        ifilter, byte2int, bytes2str, itervalues, str2bytes)
+from elftools.elf.elffile import ELFFile
+from elftools.elf.dynamic import DynamicSection, DynamicSegment
+from elftools.elf.enums import ENUM_D_TAG
+from elftools.elf.segments import InterpSegment, NoteSegment
+from elftools.elf.sections import SymbolTableSection
+from elftools.elf.gnuversions import (
+    GNUVerSymSection, GNUVerDefSection,
+    GNUVerNeedSection,
+    )
+from elftools.elf.relocation import RelocationSection
+from elftools.elf.descriptions import (
+    describe_ei_class, describe_ei_data, describe_ei_version,
+    describe_ei_osabi, describe_e_type, describe_e_machine,
+    describe_e_version_numeric, describe_p_type, describe_p_flags,
+    describe_sh_type, describe_sh_flags,
+    describe_symbol_type, describe_symbol_bind, describe_symbol_visibility,
+    describe_symbol_shndx, describe_reloc_type, describe_dyn_tag,
+    describe_ver_flags, describe_note
+    )
+from elftools.elf.constants import E_FLAGS
+from elftools.dwarf.dwarfinfo import DWARFInfo
+from elftools.dwarf.descriptions import (
+    describe_reg_name, describe_attr_value, set_global_machine_arch,
+    describe_CFI_instructions, describe_CFI_register_rule,
+    describe_CFI_CFA_rule,
+    )
+from elftools.dwarf.constants import (
+    DW_LNS_copy, DW_LNS_set_file, DW_LNE_define_file)
+from elftools.dwarf.callframe import CIE, FDE
+
+
+class ReadElf(object):
+    """ display_* methods are used to emit output into the output stream
+    """
+    def __init__(self, file, output):
+        """ file:
+                stream object with the ELF file to read
+
+            output:
+                output stream to write to
+        """
+        self.elffile = ELFFile(file)
+        self.output = output
+
+        # Lazily initialized if a debug dump is requested
+        self._dwarfinfo = None
+
+        self._versioninfo = None
+
+    def display_file_header(self):
+        """ Display the ELF file header
+        """
+        self._emitline('ELF Header:')
+        self._emit('  Magic:   ')
+        self._emitline(' '.join('%2.2x' % byte2int(b)
+                                    for b in self.elffile.e_ident_raw))
+        header = self.elffile.header
+        e_ident = header['e_ident']
+        self._emitline('  Class:                             %s' %
+                describe_ei_class(e_ident['EI_CLASS']))
+        self._emitline('  Data:                              %s' %
+                describe_ei_data(e_ident['EI_DATA']))
+        self._emitline('  Version:                           %s' %
+                describe_ei_version(e_ident['EI_VERSION']))
+        self._emitline('  OS/ABI:                            %s' %
+                describe_ei_osabi(e_ident['EI_OSABI']))
+        self._emitline('  ABI Version:                       %d' %
+                e_ident['EI_ABIVERSION'])
+        self._emitline('  Type:                              %s' %
+                describe_e_type(header['e_type']))
+        self._emitline('  Machine:                           %s' %
+                describe_e_machine(header['e_machine']))
+        self._emitline('  Version:                           %s' %
+                describe_e_version_numeric(header['e_version']))
+        self._emitline('  Entry point address:               %s' %
+                self._format_hex(header['e_entry']))
+        self._emit('  Start of program headers:          %s' %
+                header['e_phoff'])
+        self._emitline(' (bytes into file)')
+        self._emit('  Start of section headers:          %s' %
+                header['e_shoff'])
+        self._emitline(' (bytes into file)')
+        self._emitline('  Flags:                             %s%s' %
+                (self._format_hex(header['e_flags']),
+                self.decode_flags(header['e_flags'])))
+        self._emitline('  Size of this header:               %s (bytes)' %
+                header['e_ehsize'])
+        self._emitline('  Size of program headers:           %s (bytes)' %
+                header['e_phentsize'])
+        self._emitline('  Number of program headers:         %s' %
+                header['e_phnum'])
+        self._emitline('  Size of section headers:           %s (bytes)' %
+                header['e_shentsize'])
+        self._emitline('  Number of section headers:         %s' %
+                header['e_shnum'])
+        self._emitline('  Section header string table index: %s' %
+                header['e_shstrndx'])
+
+    def decode_flags(self, flags):
+        description = ""
+        if self.elffile['e_machine'] == "EM_ARM":
+            if flags & E_FLAGS.EF_ARM_HASENTRY:
+                description += ", has entry point"
+
+            version = flags & E_FLAGS.EF_ARM_EABIMASK
+            if version == E_FLAGS.EF_ARM_EABI_VER5:
+                description += ", Version5 EABI"
+        elif self.elffile['e_machine'] == "EM_MIPS":
+            if flags & E_FLAGS.EF_MIPS_NOREORDER:
+                description += ", noreorder"
+            if flags & E_FLAGS.EF_MIPS_CPIC:
+                description += ", cpic"
+            if not (flags & E_FLAGS.EF_MIPS_ABI2) and not (flags & E_FLAGS.EF_MIPS_ABI_ON32):
+                description += ", o32"
+            if (flags & E_FLAGS.EF_MIPS_ARCH) == E_FLAGS.EF_MIPS_ARCH_1:
+                description += ", mips1"
+
+        return description
+
+    def display_program_headers(self, show_heading=True):
+        """ Display the ELF program headers.
+            If show_heading is True, displays the heading for this information
+            (Elf file type is...)
+        """
+        self._emitline()
+        if self.elffile.num_segments() == 0:
+            self._emitline('There are no program headers in this file.')
+            return
+
+        elfheader = self.elffile.header
+        if show_heading:
+            self._emitline('Elf file type is %s' %
+                describe_e_type(elfheader['e_type']))
+            self._emitline('Entry point is %s' %
+                self._format_hex(elfheader['e_entry']))
+            # readelf weirness - why isn't e_phoff printed as hex? (for section
+            # headers, it is...)
+            self._emitline('There are %s program headers, starting at offset %s' % (
+                elfheader['e_phnum'], elfheader['e_phoff']))
+            self._emitline()
+
+        self._emitline('Program Headers:')
+
+        # Now comes the table of program headers with their attributes. Note
+        # that due to different formatting constraints of 32-bit and 64-bit
+        # addresses, there are some conditions on elfclass here.
+        #
+        # First comes the table heading
+        #
+        if self.elffile.elfclass == 32:
+            self._emitline('  Type           Offset   VirtAddr   PhysAddr   FileSiz MemSiz  Flg Align')
+        else:
+            self._emitline('  Type           Offset             VirtAddr           PhysAddr')
+            self._emitline('                 FileSiz            MemSiz              Flags  Align')
+
+        # Now the entries
+        #
+        for segment in self.elffile.iter_segments():
+            self._emit('  %-14s ' % describe_p_type(segment['p_type']))
+
+            if self.elffile.elfclass == 32:
+                self._emitline('%s %s %s %s %s %-3s %s' % (
+                    self._format_hex(segment['p_offset'], fieldsize=6),
+                    self._format_hex(segment['p_vaddr'], fullhex=True),
+                    self._format_hex(segment['p_paddr'], fullhex=True),
+                    self._format_hex(segment['p_filesz'], fieldsize=5),
+                    self._format_hex(segment['p_memsz'], fieldsize=5),
+                    describe_p_flags(segment['p_flags']),
+                    self._format_hex(segment['p_align'])))
+            else: # 64
+                self._emitline('%s %s %s' % (
+                    self._format_hex(segment['p_offset'], fullhex=True),
+                    self._format_hex(segment['p_vaddr'], fullhex=True),
+                    self._format_hex(segment['p_paddr'], fullhex=True)))
+                self._emitline('                 %s %s  %-3s    %s' % (
+                    self._format_hex(segment['p_filesz'], fullhex=True),
+                    self._format_hex(segment['p_memsz'], fullhex=True),
+                    describe_p_flags(segment['p_flags']),
+                    # lead0x set to False for p_align, to mimic readelf.
+                    # No idea why the difference from 32-bit mode :-|
+                    self._format_hex(segment['p_align'], lead0x=False)))
+
+            if isinstance(segment, InterpSegment):
+                self._emitline('      [Requesting program interpreter: %s]' %
+                    bytes2str(segment.get_interp_name()))
+
+        # Sections to segments mapping
+        #
+        if self.elffile.num_sections() == 0:
+            # No sections? We're done
+            return
+
+        self._emitline('\n Section to Segment mapping:')
+        self._emitline('  Segment Sections...')
+
+        for nseg, segment in enumerate(self.elffile.iter_segments()):
+            self._emit('   %2.2d     ' % nseg)
+
+            for section in self.elffile.iter_sections():
+                if (    not section.is_null() and
+                        segment.section_in_segment(section)):
+                    self._emit('%s ' % bytes2str(section.name))
+
+            self._emitline('')
+
+    def display_section_headers(self, show_heading=True):
+        """ Display the ELF section headers
+        """
+        elfheader = self.elffile.header
+        if show_heading:
+            self._emitline('There are %s section headers, starting at offset %s' % (
+                elfheader['e_shnum'], self._format_hex(elfheader['e_shoff'])))
+
+        self._emitline('\nSection Header%s:' % (
+            's' if elfheader['e_shnum'] > 1 else ''))
+
+        # Different formatting constraints of 32-bit and 64-bit addresses
+        #
+        if self.elffile.elfclass == 32:
+            self._emitline('  [Nr] Name              Type            Addr     Off    Size   ES Flg Lk Inf Al')
+        else:
+            self._emitline('  [Nr] Name              Type             Address           Offset')
+            self._emitline('       Size              EntSize          Flags  Link  Info  Align')
+
+        # Now the entries
+        #
+        for nsec, section in enumerate(self.elffile.iter_sections()):
+            self._emit('  [%2u] %-17.17s %-15.15s ' % (
+                nsec, bytes2str(section.name), describe_sh_type(section['sh_type'])))
+
+            if self.elffile.elfclass == 32:
+                self._emitline('%s %s %s %s %3s %2s %3s %2s' % (
+                    self._format_hex(section['sh_addr'], fieldsize=8, lead0x=False),
+                    self._format_hex(section['sh_offset'], fieldsize=6, lead0x=False),
+                    self._format_hex(section['sh_size'], fieldsize=6, lead0x=False),
+                    self._format_hex(section['sh_entsize'], fieldsize=2, lead0x=False),
+                    describe_sh_flags(section['sh_flags']),
+                    section['sh_link'], section['sh_info'],
+                    section['sh_addralign']))
+            else: # 64
+                self._emitline(' %s  %s' % (
+                    self._format_hex(section['sh_addr'], fullhex=True, lead0x=False),
+                    self._format_hex(section['sh_offset'],
+                        fieldsize=16 if section['sh_offset'] > 0xffffffff else 8,
+                        lead0x=False)))
+                self._emitline('       %s  %s %3s      %2s   %3s     %s' % (
+                    self._format_hex(section['sh_size'], fullhex=True, lead0x=False),
+                    self._format_hex(section['sh_entsize'], fullhex=True, lead0x=False),
+                    describe_sh_flags(section['sh_flags']),
+                    section['sh_link'], section['sh_info'],
+                    section['sh_addralign']))
+
+        self._emitline('Key to Flags:')
+        self._emit('  W (write), A (alloc), X (execute), M (merge), S (strings)')
+        if self.elffile['e_machine'] in ('EM_X86_64', 'EM_L10M'):
+            self._emitline(', l (large)')
+        else:
+            self._emitline()
+        self._emitline('  I (info), L (link order), G (group), T (TLS), E (exclude), x (unknown)')
+        self._emitline('  O (extra OS processing required) o (OS specific), p (processor specific)')
+
+    def display_symbol_tables(self):
+        """ Display the symbol tables contained in the file
+        """
+        self._init_versioninfo()
+
+        for section in self.elffile.iter_sections():
+            if not isinstance(section, SymbolTableSection):
+                continue
+
+            if section['sh_entsize'] == 0:
+                self._emitline("\nSymbol table '%s' has a sh_entsize of zero!" % (
+                    bytes2str(section.name)))
+                continue
+
+            self._emitline("\nSymbol table '%s' contains %s entries:" % (
+                bytes2str(section.name), section.num_symbols()))
+
+            if self.elffile.elfclass == 32:
+                self._emitline('   Num:    Value  Size Type    Bind   Vis      Ndx Name')
+            else: # 64
+                self._emitline('   Num:    Value          Size Type    Bind   Vis      Ndx Name')
+
+            for nsym, symbol in enumerate(section.iter_symbols()):
+
+                version_info = ''
+                # readelf doesn't display version info for Solaris versioning
+                if (section['sh_type'] == 'SHT_DYNSYM' and
+                        self._versioninfo['type'] == 'GNU'):
+                    version = self._symbol_version(nsym)
+                    if (version['name'] != bytes2str(symbol.name) and
+                        version['index'] not in ('VER_NDX_LOCAL',
+                                                 'VER_NDX_GLOBAL')):
+                        if version['filename']:
+                            # external symbol
+                            version_info = '@%(name)s (%(index)i)' % version
+                        else:
+                            # internal symbol
+                            if version['hidden']:
+                                version_info = '@%(name)s' % version
+                            else:
+                                version_info = '@@%(name)s' % version
+
+                # symbol names are truncated to 25 chars, similarly to readelf
+                self._emitline('%6d: %s %5d %-7s %-6s %-7s %4s %s%s' % (
+                    nsym,
+                    self._format_hex(
+                        symbol['st_value'], fullhex=True, lead0x=False),
+                    symbol['st_size'],
+                    describe_symbol_type(symbol['st_info']['type']),
+                    describe_symbol_bind(symbol['st_info']['bind']),
+                    describe_symbol_visibility(symbol['st_other']['visibility']),
+                    describe_symbol_shndx(symbol['st_shndx']),
+                    bytes2str(symbol.name),
+                    version_info))
+
+    def display_dynamic_tags(self):
+        """ Display the dynamic tags contained in the file
+        """
+        has_dynamic_sections = False
+        for section in self.elffile.iter_sections():
+            if not isinstance(section, DynamicSection):
+                continue
+
+            has_dynamic_sections = True
+            self._emitline("\nDynamic section at offset %s contains %s entries:" % (
+                self._format_hex(section['sh_offset']),
+                section.num_tags()))
+            self._emitline("  Tag        Type                         Name/Value")
+
+            padding = 20 + (8 if self.elffile.elfclass == 32 else 0)
+            for tag in section.iter_tags():
+                if tag.entry.d_tag == 'DT_NEEDED':
+                    parsed = 'Shared library: [%s]' % bytes2str(tag.needed)
+                elif tag.entry.d_tag == 'DT_RPATH':
+                    parsed = 'Library rpath: [%s]' % bytes2str(tag.rpath)
+                elif tag.entry.d_tag == 'DT_RUNPATH':
+                    parsed = 'Library runpath: [%s]' % bytes2str(tag.runpath)
+                elif tag.entry.d_tag == 'DT_SONAME':
+                    parsed = 'Library soname: [%s]' % bytes2str(tag.soname)
+                elif tag.entry.d_tag.endswith(('SZ', 'ENT')):
+                    parsed = '%i (bytes)' % tag['d_val']
+                elif tag.entry.d_tag.endswith(('NUM', 'COUNT')):
+                    parsed = '%i' % tag['d_val']
+                elif tag.entry.d_tag == 'DT_PLTREL':
+                    s = describe_dyn_tag(tag.entry.d_val)
+                    if s.startswith('DT_'):
+                        s = s[3:]
+                    parsed = '%s' % s
+                else:
+                    parsed = '%#x' % tag['d_val']
+
+                self._emitline(" %s %-*s %s" % (
+                    self._format_hex(ENUM_D_TAG.get(tag.entry.d_tag, tag.entry.d_tag),
+                        fullhex=True, lead0x=True),
+                    padding,
+                    '(%s)' % (tag.entry.d_tag[3:],),
+                    parsed))
+        if not has_dynamic_sections:
+            # readelf only prints this if there is at least one segment
+            if self.elffile.num_segments():
+                self._emitline("\nThere is no dynamic section in this file.")
+
+    def display_notes(self):
+        """ Display the notes contained in the file
+        """
+        for segment in self.elffile.iter_segments():
+            if isinstance(segment, NoteSegment):
+                for note in segment.iter_notes():
+                      self._emitline(
+                          "\nDisplaying notes found at file offset "
+                          "%s with length %s:" % (
+                              self._format_hex(note['n_offset'], fieldsize=8),
+                              self._format_hex(note['n_size'], fieldsize=8)))
+                      self._emitline('  Owner                 Data size        Description')
+                      self._emitline('  %s%s %s\t%s' % (
+                          note['n_name'], ' ' * (20 - len(note['n_name'])),
+                          self._format_hex(note['n_descsz'], fieldsize=8),
+                          describe_note(note)))
+
+    def display_relocations(self):
+        """ Display the relocations contained in the file
+        """
+        has_relocation_sections = False
+        for section in self.elffile.iter_sections():
+            if not isinstance(section, RelocationSection):
+                continue
+
+            has_relocation_sections = True
+            self._emitline("\nRelocation section '%s' at offset %s contains %s entries:" % (
+                bytes2str(section.name),
+                self._format_hex(section['sh_offset']),
+                section.num_relocations()))
+            if section.is_RELA():
+                self._emitline("  Offset          Info           Type           Sym. Value    Sym. Name + Addend")
+            else:
+                self._emitline(" Offset     Info    Type            Sym.Value  Sym. Name")
+
+            # The symbol table section pointed to in sh_link
+            symtable = self.elffile.get_section(section['sh_link'])
+
+            for rel in section.iter_relocations():
+                hexwidth = 8 if self.elffile.elfclass == 32 else 12
+                self._emit('%s  %s %-17.17s' % (
+                    self._format_hex(rel['r_offset'],
+                        fieldsize=hexwidth, lead0x=False),
+                    self._format_hex(rel['r_info'],
+                        fieldsize=hexwidth, lead0x=False),
+                    describe_reloc_type(
+                        rel['r_info_type'], self.elffile)))
+
+                if rel['r_info_sym'] == 0:
+                    self._emitline()
+                    continue
+
+                symbol = symtable.get_symbol(rel['r_info_sym'])
+                # Some symbols have zero 'st_name', so instead what's used is
+                # the name of the section they point at
+                if symbol['st_name'] == 0:
+                    symsec = self.elffile.get_section(symbol['st_shndx'])
+                    symbol_name = symsec.name
+                else:
+                    symbol_name = symbol.name
+                self._emit(' %s %s%22.22s' % (
+                    self._format_hex(
+                        symbol['st_value'],
+                        fullhex=True, lead0x=False),
+                    '  ' if self.elffile.elfclass == 32 else '',
+                    bytes2str(symbol_name)))
+                if section.is_RELA():
+                    self._emit(' %s %x' % (
+                        '+' if rel['r_addend'] >= 0 else '-',
+                        abs(rel['r_addend'])))
+                self._emitline()
+
+        if not has_relocation_sections:
+            self._emitline('\nThere are no relocations in this file.')
+
+    def display_version_info(self):
+        """ Display the version info contained in the file
+        """
+        self._init_versioninfo()
+
+        if not self._versioninfo['type']:
+            self._emitline("\nNo version information found in this file.")
+            return
+
+        for section in self.elffile.iter_sections():
+            if isinstance(section, GNUVerSymSection):
+                self._print_version_section_header(
+                    section, 'Version symbols', lead0x=False)
+
+                num_symbols = section.num_symbols()
+
+                # Symbol version info are printed four by four entries
+                for idx_by_4 in range(0, num_symbols, 4):
+
+                    self._emit('  %03x:' % idx_by_4)
+
+                    for idx in range(idx_by_4, min(idx_by_4 + 4, num_symbols)):
+
+                        symbol_version = self._symbol_version(idx)
+                        if symbol_version['index'] == 'VER_NDX_LOCAL':
+                            version_index = 0
+                            version_name = '(*local*)'
+                        elif symbol_version['index'] == 'VER_NDX_GLOBAL':
+                            version_index = 1
+                            version_name = '(*global*)'
+                        else:
+                            version_index = symbol_version['index']
+                            version_name = '(%(name)s)' % symbol_version
+
+                        visibility = 'h' if symbol_version['hidden'] else ' '
+
+                        self._emit('%4x%s%-13s' % (
+                            version_index, visibility, version_name))
+
+                    self._emitline()
+
+            elif isinstance(section, GNUVerDefSection):
+                self._print_version_section_header(
+                    section, 'Version definition', indent=2)
+
+                offset = 0
+                for verdef, verdaux_iter in section.iter_versions():
+                    verdaux = next(verdaux_iter)
+
+                    name = verdaux.name
+                    if verdef['vd_flags']:
+                        flags = describe_ver_flags(verdef['vd_flags'])
+                        # Mimic exactly the readelf output
+                        flags += ' '
+                    else:
+                        flags = 'none'
+
+                    self._emitline('  %s: Rev: %i  Flags: %s  Index: %i'
+                                   '  Cnt: %i  Name: %s' % (
+                            self._format_hex(offset, fieldsize=6,
+                                             alternate=True),
+                            verdef['vd_version'], flags, verdef['vd_ndx'],
+                            verdef['vd_cnt'], bytes2str(name)))
+
+                    verdaux_offset = (
+                            offset + verdef['vd_aux'] + verdaux['vda_next'])
+                    for idx, verdaux in enumerate(verdaux_iter, start=1):
+                        self._emitline('  %s: Parent %i: %s' %
+                            (self._format_hex(verdaux_offset, fieldsize=4),
+                                              idx, bytes2str(verdaux.name)))
+                        verdaux_offset += verdaux['vda_next']
+
+                    offset += verdef['vd_next']
+
+            elif isinstance(section, GNUVerNeedSection):
+                self._print_version_section_header(section, 'Version needs')
+
+                offset = 0
+                for verneed, verneed_iter in section.iter_versions():
+
+                    self._emitline('  %s: Version: %i  File: %s  Cnt: %i' % (
+                            self._format_hex(offset, fieldsize=6,
+                                             alternate=True),
+                            verneed['vn_version'], bytes2str(verneed.name),
+                            verneed['vn_cnt']))
+
+                    vernaux_offset = offset + verneed['vn_aux']
+                    for idx, vernaux in enumerate(verneed_iter, start=1):
+                        if vernaux['vna_flags']:
+                            flags = describe_ver_flags(vernaux['vna_flags'])
+                            # Mimic exactly the readelf output
+                            flags += ' '
+                        else:
+                            flags = 'none'
+
+                        self._emitline(
+                            '  %s:   Name: %s  Flags: %s  Version: %i' % (
+                                self._format_hex(vernaux_offset, fieldsize=4),
+                                bytes2str(vernaux.name), flags,
+                                vernaux['vna_other']))
+
+                        vernaux_offset += vernaux['vna_next']
+
+                    offset += verneed['vn_next']
+
+    def display_hex_dump(self, section_spec):
+        """ Display a hex dump of a section. section_spec is either a section
+            number or a name.
+        """
+        section = self._section_from_spec(section_spec)
+        if section is None:
+            self._emitline("Section '%s' does not exist in the file!" % (
+                section_spec))
+            return
+
+        self._emitline("\nHex dump of section '%s':" % bytes2str(section.name))
+        self._note_relocs_for_section(section)
+        addr = section['sh_addr']
+        data = section.data()
+        dataptr = 0
+
+        while dataptr < len(data):
+            bytesleft = len(data) - dataptr
+            # chunks of 16 bytes per line
+            linebytes = 16 if bytesleft > 16 else bytesleft
+
+            self._emit('  %s ' % self._format_hex(addr, fieldsize=8))
+            for i in range(16):
+                if i < linebytes:
+                    self._emit('%2.2x' % byte2int(data[dataptr + i]))
+                else:
+                    self._emit('  ')
+                if i % 4 == 3:
+                    self._emit(' ')
+
+            for i in range(linebytes):
+                c = data[dataptr + i : dataptr + i + 1]
+                if byte2int(c[0]) >= 32 and byte2int(c[0]) < 0x7f:
+                    self._emit(bytes2str(c))
+                else:
+                    self._emit(bytes2str(b'.'))
+
+            self._emitline()
+            addr += linebytes
+            dataptr += linebytes
+
+        self._emitline()
+
+    def display_string_dump(self, section_spec):
+        """ Display a strings dump of a section. section_spec is either a
+            section number or a name.
+        """
+        section = self._section_from_spec(section_spec)
+        if section is None:
+            self._emitline("Section '%s' does not exist in the file!" % (
+                section_spec))
+            return
+
+        self._emitline("\nString dump of section '%s':" % bytes2str(section.name))
+
+        found = False
+        data = section.data()
+        dataptr = 0
+
+        while dataptr < len(data):
+            while ( dataptr < len(data) and
+                    not (32 <= byte2int(data[dataptr]) <= 127)):
+                dataptr += 1
+
+            if dataptr >= len(data):
+                break
+
+            endptr = dataptr
+            while endptr < len(data) and byte2int(data[endptr]) != 0:
+                endptr += 1
+
+            found = True
+            self._emitline('  [%6x]  %s' % (
+                dataptr, bytes2str(data[dataptr:endptr])))
+
+            dataptr = endptr
+
+        if not found:
+            self._emitline('  No strings found in this section.')
+        else:
+            self._emitline()
+
+    def display_debug_dump(self, dump_what):
+        """ Dump a DWARF section
+        """
+        self._init_dwarfinfo()
+        if self._dwarfinfo is None:
+            return
+
+        set_global_machine_arch(self.elffile.get_machine_arch())
+
+        if dump_what == 'info':
+            self._dump_debug_info()
+        elif dump_what == 'decodedline':
+            self._dump_debug_line_programs()
+        elif dump_what == 'frames':
+            self._dump_debug_frames()
+        elif dump_what == 'frames-interp':
+            self._dump_debug_frames_interp()
+        else:
+            self._emitline('debug dump not yet supported for "%s"' % dump_what)
+
+    def _format_hex(self, addr, fieldsize=None, fullhex=False, lead0x=True,
+                    alternate=False):
+        """ Format an address into a hexadecimal string.
+
+            fieldsize:
+                Size of the hexadecimal field (with leading zeros to fit the
+                address into. For example with fieldsize=8, the format will
+                be %08x
+                If None, the minimal required field size will be used.
+
+            fullhex:
+                If True, override fieldsize to set it to the maximal size
+                needed for the elfclass
+
+            lead0x:
+                If True, leading 0x is added
+
+            alternate:
+                If True, override lead0x to emulate the alternate
+                hexadecimal form specified in format string with the #
+                character: only non-zero values are prefixed with 0x.
+                This form is used by readelf.
+        """
+        if alternate:
+            if addr == 0:
+                lead0x = False
+            else:
+                lead0x = True
+                fieldsize -= 2
+
+        s = '0x' if lead0x else ''
+        if fullhex:
+            fieldsize = 8 if self.elffile.elfclass == 32 else 16
+        if fieldsize is None:
+            field = '%x'
+        else:
+            field = '%' + '0%sx' % fieldsize
+        return s + field % addr
+
+    def _print_version_section_header(self, version_section, name, lead0x=True,
+                                      indent=1):
+        """ Print a section header of one version related section (versym,
+            verneed or verdef) with some options to accomodate readelf
+            little differences between each header (e.g. indentation
+            and 0x prefixing).
+        """
+        if hasattr(version_section, 'num_versions'):
+            num_entries = version_section.num_versions()
+        else:
+            num_entries = version_section.num_symbols()
+
+        self._emitline("\n%s section '%s' contains %s entries:" %
+            (name, bytes2str(version_section.name), num_entries))
+        self._emitline('%sAddr: %s  Offset: %s  Link: %i (%s)' % (
+            ' ' * indent,
+            self._format_hex(
+                version_section['sh_addr'], fieldsize=16, lead0x=lead0x),
+            self._format_hex(
+                version_section['sh_offset'], fieldsize=6, lead0x=True),
+            version_section['sh_link'],
+            bytes2str(
+                self.elffile.get_section(version_section['sh_link']).name)
+            )
+        )
+
+    def _init_versioninfo(self):
+        """ Search and initialize informations about version related sections
+            and the kind of versioning used (GNU or Solaris).
+        """
+        if self._versioninfo is not None:
+            return
+
+        self._versioninfo = {'versym': None, 'verdef': None,
+                             'verneed': None, 'type': None}
+
+        for section in self.elffile.iter_sections():
+            if isinstance(section, GNUVerSymSection):
+                self._versioninfo['versym'] = section
+            elif isinstance(section, GNUVerDefSection):
+                self._versioninfo['verdef'] = section
+            elif isinstance(section, GNUVerNeedSection):
+                self._versioninfo['verneed'] = section
+            elif isinstance(section, DynamicSection):
+                for tag in section.iter_tags():
+                    if tag['d_tag'] == 'DT_VERSYM':
+                        self._versioninfo['type'] = 'GNU'
+                        break
+
+        if not self._versioninfo['type'] and (
+                self._versioninfo['verneed'] or self._versioninfo['verdef']):
+            self._versioninfo['type'] = 'Solaris'
+
+    def _symbol_version(self, nsym):
+        """ Return a dict containing information on the
+                   or None if no version information is available
+        """
+        self._init_versioninfo()
+
+        symbol_version = dict.fromkeys(('index', 'name', 'filename', 'hidden'))
+
+        if (not self._versioninfo['versym'] or
+                nsym >= self._versioninfo['versym'].num_symbols()):
+            return None
+
+        symbol = self._versioninfo['versym'].get_symbol(nsym)
+        index = symbol.entry['ndx']
+        if not index in ('VER_NDX_LOCAL', 'VER_NDX_GLOBAL'):
+            index = int(index)
+
+            if self._versioninfo['type'] == 'GNU':
+                # In GNU versioning mode, the highest bit is used to
+                # store wether the symbol is hidden or not
+                if index & 0x8000:
+                    index &= ~0x8000
+                    symbol_version['hidden'] = True
+
+            if (self._versioninfo['verdef'] and
+                    index <= self._versioninfo['verdef'].num_versions()):
+                _, verdaux_iter = \
+                        self._versioninfo['verdef'].get_version(index)
+                symbol_version['name'] = bytes2str(next(verdaux_iter).name)
+            else:
+                verneed, vernaux = \
+                        self._versioninfo['verneed'].get_version(index)
+                symbol_version['name'] = bytes2str(vernaux.name)
+                symbol_version['filename'] = bytes2str(verneed.name)
+
+        symbol_version['index'] = index
+        return symbol_version
+
+    def _section_from_spec(self, spec):
+        """ Retrieve a section given a "spec" (either number or name).
+            Return None if no such section exists in the file.
+        """
+        try:
+            num = int(spec)
+            if num < self.elffile.num_sections():
+                return self.elffile.get_section(num)
+            else:
+                return None
+        except ValueError:
+            # Not a number. Must be a name then
+            return self.elffile.get_section_by_name(str2bytes(spec))
+
+    def _note_relocs_for_section(self, section):
+        """ If there are relocation sections pointing to the givne section,
+            emit a note about it.
+        """
+        for relsec in self.elffile.iter_sections():
+            if isinstance(relsec, RelocationSection):
+                info_idx = relsec['sh_info']
+                if self.elffile.get_section(info_idx) == section:
+                    self._emitline('  Note: This section has relocations against it, but these have NOT been applied to this dump.')
+                    return
+
+    def _init_dwarfinfo(self):
+        """ Initialize the DWARF info contained in the file and assign it to
+            self._dwarfinfo.
+            Leave self._dwarfinfo at None if no DWARF info was found in the file
+        """
+        if self._dwarfinfo is not None:
+            return
+
+        if self.elffile.has_dwarf_info():
+            self._dwarfinfo = self.elffile.get_dwarf_info()
+        else:
+            self._dwarfinfo = None
+
+    def _dump_debug_info(self):
+        """ Dump the debugging info section.
+        """
+        self._emitline('Contents of the .debug_info section:\n')
+
+        # Offset of the .debug_info section in the stream
+        section_offset = self._dwarfinfo.debug_info_sec.global_offset
+
+        for cu in self._dwarfinfo.iter_CUs():
+            self._emitline('  Compilation Unit @ offset %s:' %
+                self._format_hex(cu.cu_offset))
+            self._emitline('   Length:        %s (%s)' % (
+                self._format_hex(cu['unit_length']),
+                '%s-bit' % cu.dwarf_format()))
+            self._emitline('   Version:       %s' % cu['version']),
+            self._emitline('   Abbrev Offset: %s' % (
+                self._format_hex(cu['debug_abbrev_offset']))),
+            self._emitline('   Pointer Size:  %s' % cu['address_size'])
+
+            # The nesting depth of each DIE within the tree of DIEs must be
+            # displayed. To implement this, a counter is incremented each time
+            # the current DIE has children, and decremented when a null die is
+            # encountered. Due to the way the DIE tree is serialized, this will
+            # correctly reflect the nesting depth
+            #
+            die_depth = 0
+            for die in cu.iter_DIEs():
+                self._emitline(' <%s><%x>: Abbrev Number: %s%s' % (
+                    die_depth,
+                    die.offset,
+                    die.abbrev_code,
+                    (' (%s)' % die.tag) if not die.is_null() else ''))
+                if die.is_null():
+                    die_depth -= 1
+                    continue
+
+                for attr in itervalues(die.attributes):
+                    name = attr.name
+                    # Unknown attribute values are passed-through as integers
+                    if isinstance(name, int):
+                        name = 'Unknown AT value: %x' % name
+                    self._emitline('    <%2x>   %-18s: %s' % (
+                        attr.offset,
+                        name,
+                        describe_attr_value(
+                            attr, die, section_offset)))
+
+                if die.has_children:
+                    die_depth += 1
+
+        self._emitline()
+
+    def _dump_debug_line_programs(self):
+        """ Dump the (decoded) line programs from .debug_line
+            The programs are dumped in the order of the CUs they belong to.
+        """
+        self._emitline('Decoded dump of debug contents of section .debug_line:\n')
+
+        for cu in self._dwarfinfo.iter_CUs():
+            lineprogram = self._dwarfinfo.line_program_for_CU(cu)
+
+            cu_filename = bytes2str(lineprogram['file_entry'][0].name)
+            if len(lineprogram['include_directory']) > 0:
+                dir_index = lineprogram['file_entry'][0].dir_index
+                if dir_index > 0:
+                    dir = lineprogram['include_directory'][dir_index - 1]
+                else:
+                    dir = b'.'
+                cu_filename = '%s/%s' % (bytes2str(dir), cu_filename)
+
+            self._emitline('CU: %s:' % cu_filename)
+            self._emitline('File name                            Line number    Starting address')
+
+            # Print each state's file, line and address information. For some
+            # instructions other output is needed to be compatible with
+            # readelf.
+            for entry in lineprogram.get_entries():
+                state = entry.state
+                if state is None:
+                    # Special handling for commands that don't set a new state
+                    if entry.command == DW_LNS_set_file:
+                        file_entry = lineprogram['file_entry'][entry.args[0] - 1]
+                        if file_entry.dir_index == 0:
+                            # current directory
+                            self._emitline('\n./%s:[++]' % (
+                                bytes2str(file_entry.name)))
+                        else:
+                            self._emitline('\n%s/%s:' % (
+                                bytes2str(lineprogram['include_directory'][file_entry.dir_index - 1]),
+                                bytes2str(file_entry.name)))
+                    elif entry.command == DW_LNE_define_file:
+                        self._emitline('%s:' % (
+                            bytes2str(lineprogram['include_directory'][entry.args[0].dir_index])))
+                elif not state.end_sequence:
+                    # readelf doesn't print the state after end_sequence
+                    # instructions. I think it's a bug but to be compatible
+                    # I don't print them too.
+                    self._emitline('%-35s  %11d  %18s' % (
+                        bytes2str(lineprogram['file_entry'][state.file - 1].name),
+                        state.line,
+                        '0' if state.address == 0 else
+                               self._format_hex(state.address)))
+                if entry.command == DW_LNS_copy:
+                    # Another readelf oddity...
+                    self._emitline()
+
+    def _dump_debug_frames(self):
+        """ Dump the raw frame information from .debug_frame
+        """
+        if not self._dwarfinfo.has_CFI():
+            return
+        self._emitline('Contents of the .debug_frame section:')
+
+        for entry in self._dwarfinfo.CFI_entries():
+            if isinstance(entry, CIE):
+                self._emitline('\n%08x %s %s CIE' % (
+                    entry.offset,
+                    self._format_hex(entry['length'], fullhex=True, lead0x=False),
+                    self._format_hex(entry['CIE_id'], fullhex=True, lead0x=False)))
+                self._emitline('  Version:               %d' % entry['version'])
+                self._emitline('  Augmentation:          "%s"' % bytes2str(entry['augmentation']))
+                self._emitline('  Code alignment factor: %u' % entry['code_alignment_factor'])
+                self._emitline('  Data alignment factor: %d' % entry['data_alignment_factor'])
+                self._emitline('  Return address column: %d' % entry['return_address_register'])
+                self._emitline()
+            else: # FDE
+                self._emitline('\n%08x %s %s FDE cie=%08x pc=%s..%s' % (
+                    entry.offset,
+                    self._format_hex(entry['length'], fullhex=True, lead0x=False),
+                    self._format_hex(entry['CIE_pointer'], fullhex=True, lead0x=False),
+                    entry.cie.offset,
+                    self._format_hex(entry['initial_location'], fullhex=True, lead0x=False),
+                    self._format_hex(
+                        entry['initial_location'] + entry['address_range'],
+                        fullhex=True, lead0x=False)))
+
+            self._emit(describe_CFI_instructions(entry))
+        self._emitline()
+
+    def _dump_debug_frames_interp(self):
+        """ Dump the interpreted (decoded) frame information from .debug_frame
+        """
+        if not self._dwarfinfo.has_CFI():
+            return
+
+        self._emitline('Contents of the .debug_frame section:')
+
+        for entry in self._dwarfinfo.CFI_entries():
+            if isinstance(entry, CIE):
+                self._emitline('\n%08x %s %s CIE "%s" cf=%d df=%d ra=%d' % (
+                    entry.offset,
+                    self._format_hex(entry['length'], fullhex=True, lead0x=False),
+                    self._format_hex(entry['CIE_id'], fullhex=True, lead0x=False),
+                    bytes2str(entry['augmentation']),
+                    entry['code_alignment_factor'],
+                    entry['data_alignment_factor'],
+                    entry['return_address_register']))
+                ra_regnum = entry['return_address_register']
+            else: # FDE
+                self._emitline('\n%08x %s %s FDE cie=%08x pc=%s..%s' % (
+                    entry.offset,
+                    self._format_hex(entry['length'], fullhex=True, lead0x=False),
+                    self._format_hex(entry['CIE_pointer'], fullhex=True, lead0x=False),
+                    entry.cie.offset,
+                    self._format_hex(entry['initial_location'], fullhex=True, lead0x=False),
+                    self._format_hex(entry['initial_location'] + entry['address_range'],
+                        fullhex=True, lead0x=False)))
+                ra_regnum = entry.cie['return_address_register']
+
+            # Print the heading row for the decoded table
+            self._emit('   LOC')
+            self._emit('  ' if entry.structs.address_size == 4 else '          ')
+            self._emit(' CFA      ')
+
+            # Decode the table nad look at the registers it describes.
+            # We build reg_order here to match readelf's order. In particular,
+            # registers are sorted by their number, and the register matching
+            # ra_regnum is always listed last with a special heading.
+            decoded_table = entry.get_decoded()
+            reg_order = sorted(ifilter(
+                lambda r: r != ra_regnum,
+                decoded_table.reg_order))
+            if len(decoded_table.reg_order):
+
+                # Headings for the registers
+                for regnum in reg_order:
+                    self._emit('%-6s' % describe_reg_name(regnum))
+                self._emitline('ra      ')
+
+                # Now include ra_regnum in reg_order to print its values similarly
+                # to the other registers.
+                reg_order.append(ra_regnum)
+            else:
+                self._emitline()
+
+            for line in decoded_table.table:
+                self._emit(self._format_hex(
+                    line['pc'], fullhex=True, lead0x=False))
+                self._emit(' %-9s' % describe_CFI_CFA_rule(line['cfa']))
+
+                for regnum in reg_order:
+                    if regnum in line:
+                        s = describe_CFI_register_rule(line[regnum])
+                    else:
+                        s = 'u'
+                    self._emit('%-6s' % s)
+                self._emitline()
+        self._emitline()
+
+    def _emit(self, s=''):
+        """ Emit an object to output
+        """
+        self.output.write(str(s))
+
+    def _emitline(self, s=''):
+        """ Emit an object to output, followed by a newline
+        """
+        self.output.write(str(s) + '\n')
+
+
+SCRIPT_DESCRIPTION = 'Display information about the contents of ELF format files'
+VERSION_STRING = '%%prog: based on pyelftools %s' % __version__
+
+
+def main(stream=None):
+    # parse the command-line arguments and invoke ReadElf
+    optparser = OptionParser(
+            usage='usage: %prog [options] <elf-file>',
+            description=SCRIPT_DESCRIPTION,
+            add_help_option=False, # -h is a real option of readelf
+            prog='readelf.py',
+            version=VERSION_STRING)
+    optparser.add_option('-d', '--dynamic',
+            action='store_true', dest='show_dynamic_tags',
+            help='Display the dynamic section')
+    optparser.add_option('-H', '--help',
+            action='store_true', dest='help',
+            help='Display this information')
+    optparser.add_option('-h', '--file-header',
+            action='store_true', dest='show_file_header',
+            help='Display the ELF file header')
+    optparser.add_option('-l', '--program-headers', '--segments',
+            action='store_true', dest='show_program_header',
+            help='Display the program headers')
+    optparser.add_option('-S', '--section-headers', '--sections',
+            action='store_true', dest='show_section_header',
+            help="Display the sections' headers")
+    optparser.add_option('-e', '--headers',
+            action='store_true', dest='show_all_headers',
+            help='Equivalent to: -h -l -S')
+    optparser.add_option('-s', '--symbols', '--syms',
+            action='store_true', dest='show_symbols',
+            help='Display the symbol table')
+    optparser.add_option('-n', '--notes',
+            action='store_true', dest='show_notes',
+            help='Display the core notes (if present)')
+    optparser.add_option('-r', '--relocs',
+            action='store_true', dest='show_relocs',
+            help='Display the relocations (if present)')
+    optparser.add_option('-x', '--hex-dump',
+            action='store', dest='show_hex_dump', metavar='<number|name>',
+            help='Dump the contents of section <number|name> as bytes')
+    optparser.add_option('-p', '--string-dump',
+            action='store', dest='show_string_dump', metavar='<number|name>',
+            help='Dump the contents of section <number|name> as strings')
+    optparser.add_option('-V', '--version-info',
+            action='store_true', dest='show_version_info',
+            help='Display the version sections (if present)')
+    optparser.add_option('--debug-dump',
+            action='store', dest='debug_dump_what', metavar='<what>',
+            help=(
+                'Display the contents of DWARF debug sections. <what> can ' +
+                'one of {info,decodedline,frames,frames-interp}'))
+
+    options, args = optparser.parse_args()
+
+    if options.help or len(args) == 0:
+        optparser.print_help()
+        sys.exit(0)
+
+    if options.show_all_headers:
+        do_file_header = do_section_header = do_program_header = True
+    else:
+        do_file_header = options.show_file_header
+        do_section_header = options.show_section_header
+        do_program_header = options.show_program_header
+
+    with open(args[0], 'rb') as file:
+        try:
+            readelf = ReadElf(file, stream or sys.stdout)
+            if do_file_header:
+                readelf.display_file_header()
+            if do_section_header:
+                readelf.display_section_headers(
+                        show_heading=not do_file_header)
+            if do_program_header:
+                readelf.display_program_headers(
+                        show_heading=not do_file_header)
+            if options.show_dynamic_tags:
+                readelf.display_dynamic_tags()
+            if options.show_symbols:
+                readelf.display_symbol_tables()
+            if options.show_notes:
+                readelf.display_notes()
+            if options.show_relocs:
+                readelf.display_relocations()
+            if options.show_version_info:
+                readelf.display_version_info()
+            if options.show_hex_dump:
+                readelf.display_hex_dump(options.show_hex_dump)
+            if options.show_string_dump:
+                readelf.display_string_dump(options.show_string_dump)
+            if options.debug_dump_what:
+                readelf.display_debug_dump(options.debug_dump_what)
+        except ELFError as ex:
+            sys.stderr.write('ELF error: %s\n' % ex)
+            sys.exit(1)
+
+
+def profile_main():
+    # Run 'main' redirecting its output to readelfout.txt
+    # Saves profiling information in readelf.profile
+    PROFFILE = 'readelf.profile'
+    import cProfile
+    cProfile.run('main(open("readelfout.txt", "w"))', PROFFILE)
+
+    # Dig in some profiling stats
+    import pstats
+    p = pstats.Stats(PROFFILE)
+    p.sort_stats('cumulative').print_stats(25)
+
+
+#-------------------------------------------------------------------------------
+if __name__ == '__main__':
+    main()
+    #profile_main()
diff --git a/packages/ti/utils/profiling/src/Module.xs b/packages/ti/utils/profiling/src/Module.xs
new file mode 100644 (file)
index 0000000..78bc339
--- /dev/null
@@ -0,0 +1,76 @@
+/******************************************************************************
+ * FILE PURPOSE: Processor SDK Utilities Source Module specification file.
+ ******************************************************************************
+ * FILE NAME: module.xs
+ *
+ * DESCRIPTION:
+ *  This file contains the module specification for the Processor SDK Utilities
+ *
+ * Copyright (C) 2015 Texas Instruments, Inc.
+ *****************************************************************************/
+
+/* Load the library utility. */
+var libUtility = xdc.loadCapsule ("../build/buildlib.xs");
+
+/* List of all the Profiling Hook Files */
+var profilingHookFiles = [
+    "src/profilingHooksArmV7_A.c",
+    "src/profilingHooksArmV7_AAssembly.asm",
+    "src/profilingHooksM4.c",
+    "src/profilingHooksC66.c",
+    "src/profilingHooksArmV8_A.c",
+    "src/profilingHooksR5.c"
+];
+
+/**************************************************************************
+ * FUNCTION NAME : modBuild
+ **************************************************************************
+ * DESCRIPTION   :
+ *  The function is used to build the Processor SDK Utilities
+ **************************************************************************/
+function modBuild()
+{
+    if (socs.length != 0)
+    {
+        /* Build the device independent libraries for all the targets specified. */
+        for (var targets=0; targets < socs["all"].targets.length; targets++)
+        {
+            var profilingBaseFile = [];
+            var libOptions = {
+                copts: socs["all"].copts,
+                incs: lldIncludePath,
+            };
+
+            if ((Build.targets[targets].name == "A15F" ) ||
+                (Build.targets[targets].name == "A8F" ) ||
+                (Build.targets[targets].name == "A9F" )) {
+                profilingBaseFile[0] = profilingHookFiles[0];
+            } else if (Build.targets[targets].name == "M4") {
+                profilingBaseFile[0] = profilingHookFiles[1];
+            } else {
+                profilingBaseFile[0] = profilingHookFiles[2];
+            }
+            libUtility.buildLibrary ("",  "false", "false", libOptions, Pkg.name, socs["all"].targets[targets], profilingBaseFile);
+        }
+    }
+
+    /* Add all the .c files to the release package. */
+    var testFiles = libUtility.listAllFiles (".c", "src", true);
+    for (var k = 0 ; k < testFiles.length; k++)
+        Pkg.otherFiles[Pkg.otherFiles.length++] = testFiles[k];
+
+    /* Add all the .h files to the release package. */
+    var testFiles = libUtility.listAllFiles (".h", "src", true);
+    for (var k = 0 ; k < testFiles.length; k++)
+        Pkg.otherFiles[Pkg.otherFiles.length++] = testFiles[k];
+
+    /* Add all the .mk files to the release package. */
+    var mkFiles = libUtility.listAllFiles (".mk", "src", true);
+    for (var k = 0 ; k < mkFiles.length; k++)
+        Pkg.otherFiles[Pkg.otherFiles.length++] = mkFiles[k];
+
+    /* Add all the .asm files to the release package. */
+    var testFiles = libUtility.listAllFiles (".asm", "src", true);
+    for (var k = 0 ; k < testFiles.length; k++)
+        Pkg.otherFiles[Pkg.otherFiles.length++] = testFiles[k];
+}
diff --git a/packages/ti/utils/profiling/src/profilingHooksArmV7_A.c b/packages/ti/utils/profiling/src/profilingHooksArmV7_A.c
new file mode 100644 (file)
index 0000000..26274f2
--- /dev/null
@@ -0,0 +1,160 @@
+/*
+ * Copyright (c) 2015, Texas Instruments Incorporated
+ * 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 Texas Instruments Incorporated nor the names of
+ *    its contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+ * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+ * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+/**
+ *  @file    profilingHooksArmV7_A.c
+ *
+ *  @brief   ARM Implementations of the runtime programming hooks of the Processor SDK Profiling Tool.
+ *
+ *  For more information, see:
+ *  - @subpage profCCS
+ *  - @subpage profDSS
+ *
+ *  ## Usage ##
+ *
+ *  Applications that are included in a profiling session must  set these
+ *  compiler flags for the desired platform:
+ *    - ARM: `-finstrument-functions -gdwarf-3 -g`
+ *    - DSP: `--entry_parm=address --exit_hook=ti_utils_exit --exit_parm=address --entry_hook=ti_utils_entry -g`
+ *    - M4: `--entry_parm=address --exit_hook=ti_utils_exit --exit_parm=address --entry_hook=ti_utils_entry -g`
+ *
+ *  For best results, ensure that the optimization levels are consistent between
+ *  the library and the project (typically -O3, or optimization level 3).
+ *
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdint.h>
+#include "profilingHooks.h"
+#include "profiling_osal.h"
+
+
+int32_t CurrentTaskHookSetId, MaxTaskHookSetId;
+
+/*!
+ *  @brief    Maximum log count
+ *
+ *  This is a predefined value to indicate when the instrumentation hooks should
+ *  stop logging data. This is important for applications that have long polling
+ *  loops or a device that has a small cache.
+ */
+#define MAX_LOG (1U*1024U*1024U)
+
+uint32_t log_idx = 0;
+
+/*!
+ *  @brief    Utils profiling log structure
+ *
+ *  Utils log elements have a predefined structure of four words (to avoid the
+ *  need of malloc) and are stored in an array of predefined length, `elemlog`.
+ */
+typedef struct{
+    /*! Indicates either enter or exit */
+    int32_t isEnter;
+    /*! Pointer address of the function in current context */
+    int32_t this_fn;
+    /*! Optional: Pointer address of calling function in current context */
+    int32_t call_site;
+    /*! Timestamp of the entry or exit */
+    uint32_t timestamp;
+}utilsProfilingElem;
+
+utilsProfilingElem elemlog[MAX_LOG] = {{0}};
+
+/*!
+ *  @brief    Empty function for time adjustment
+ *
+ *  @ingroup pdk_profiling_hooks
+ *
+ *  Nothing more than an empty function that is referenced to measure the time
+ *  used by the instrumentation functions themselves. This is recorded and
+ *  passed into post-processing for a more accurate result.
+ */
+void __attribute__ ((noinline)) empty_fn(void); /*for misra warnings*/
+void __attribute__ ((noinline)) empty_fn(void){
+}
+
+
+/*!
+ *  @brief    ARMv7 GCC Utils init function
+ *
+ *  @ingroup pdk_profiling_hooks
+ *
+ *  Instruments the entry point and then calculate the entry and exit offset,
+ *  the offset are stored in the first 2 elements of elem_log.
+ *
+ *  @param    none
+ *
+ */
+void __attribute__((no_instrument_function))profiling_init(void){
+    uint32_t entry_offset = 0;
+    uint32_t exit_offset = 0;
+    log_idx++;
+    log_idx++;
+    int32_t i;
+    for (i = 0; i < 10; i++){
+        empty_fn();
+    }
+    elemlog[0].isEnter = 2;
+    elemlog[0].this_fn = 1;
+    elemlog[0].call_site = 1;
+    /*Taking 10 sample and subtracting (exit_log - entry log) of present for calculating the entry offset*/
+    for(i=1;i<=10;i++)
+    {
+        entry_offset += (elemlog[(2*i)+1].timestamp - elemlog[(2*i)].timestamp);
+    }
+    /* Saving the average of 10 sample */
+    elemlog[0].timestamp = entry_offset/10U;
+    elemlog[1].isEnter = 2;
+    elemlog[1].this_fn = 1;
+    elemlog[1].call_site = 2;
+    /* Taking 9 sample and subtracting (entry_log of next - exit_log of present) for calculating the exit offset*/
+    for(i=2;i<=10;i++)
+    {
+        exit_offset += (elemlog[(2*i)].timestamp - elemlog[(2*i)-1].timestamp);
+    }
+    /* Saving the average of 9 sample */
+    elemlog[1].timestamp = exit_offset/9U;
+    log_idx = 2U;
+}
+
+void __attribute__((no_instrument_function))TaskRegisterId(int32_t hookSetId); /*for misra warnings*/
+void __attribute__((no_instrument_function))TaskRegisterId(int32_t hookSetId)
+{
+       CurrentTaskHookSetId = hookSetId;
+    if(MaxTaskHookSetId < CurrentTaskHookSetId)
+    {
+        MaxTaskHookSetId = CurrentTaskHookSetId;
+    }
+}
+
+
diff --git a/packages/ti/utils/profiling/src/profilingHooksArmV7_AAssembly.asm b/packages/ti/utils/profiling/src/profilingHooksArmV7_AAssembly.asm
new file mode 100644 (file)
index 0000000..48b1944
--- /dev/null
@@ -0,0 +1,161 @@
+@******************************************************************************
+@
+@ \file   profilingHooksArmV7_AAssembly.asm
+@
+@ \brief  proliling hooks function.
+@
+@******************************************************************************
+@ Copyright (C) 2017 Texas Instruments Incorporated - http://www.ti.com/
+@
+@
+@  Redistribution and use in source and binary forms, with or without
+@  modification, are permitted provided that the following conditions
+@  are met:
+@
+@    Redistributions of source code must retain the above copyright
+@    notice, this list of conditions and the following disclaimer.
+@
+@    Redistributions in binary form must reproduce the above copyright
+@    notice, this list of conditions and the following disclaimer in the
+@    documentation and/or other materials provided with the
+@    distribution.
+@
+@    Neither the name of Texas Instruments Incorporated nor the names of
+@    its contributors may be used to endorse or promote products derived
+@    from this software without specific prior written permission.
+@
+@  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+@  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+@  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+@  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+@  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+@  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+@  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+@  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+@  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+@  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+@  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+@
+@******************************************************************************
+
+@******************************************************************************
+@*                               INCLUDE FILES
+@******************************************************************************
+
+@******************************************************************************
+@*                                  SYMBOLS
+@****************************************************************************** 
+
+        .global        __cyg_profile_func_enter
+        .global        __cyg_profile_func_exit
+        .global        mySwitch
+        .global        elemlog
+        .global        log_idx
+
+@******************************************************************************
+@*                                 CODE SECTION
+@******************************************************************************
+        .text
+
+        @ This code is assembled for ARM instructions
+        .code 32
+
+@******************************************************************************
+@*                                 ASSEMBLY ROUTINES
+@******************************************************************************     
+
+@*****************************************************************************
+@ This API logs the entry hooks.
+@*****************************************************************************
+__cyg_profile_func_enter:
+       mov     ip, sp
+       stmfd   sp!, {r4, r5, r6, r7, fp, ip, lr, pc}
+       sub     fp, ip, #4
+       mov     r7, r0
+       mov     r6, r1
+       MRC     p15, 0, r5, c9, c13, 0  
+       movw    r4, #:lower16:log_idx
+       movt    r4, #:upper16:log_idx
+       ldr     r3, [r4]
+       cmp     r3, #0
+       beq     .L5
+.L2:
+       cmp     r3, #1048576
+       bcs     .L1
+       movw    r2, #:lower16:elemlog
+       mov     r0, #1
+       movt    r2, #:upper16:elemlog
+       add     r1, r3, r0
+       add     ip, r2, r3, asl #4
+       str     r0, [r2, r3, asl #4]
+       str     r1, [r4]
+       str     r7, [ip, #4]
+       str     r6, [ip, #8]
+       str     r5, [ip, #12]
+.L1:
+       sub     sp, fp, #28
+       ldmfd   sp, {r4, r5, r6, r7, fp, sp, pc}
+.L5:
+       bl      profiling_init
+       ldr     r3, [r4]
+       b       .L2
+
+@*****************************************************************************
+@ This API logs the exit hooks. 
+@*****************************************************************************
+__cyg_profile_func_exit:
+       stmfd   sp!, {r4, r5, lr}
+       MRC p15, 0, lr, c9, c13, 0      
+       movw    r3, #:lower16:log_idx
+       movt    r3, #:upper16:log_idx
+       ldr     r2, [r3]
+       cmp     r2, #1048576
+       bcs     .L17
+       movw    r1, #:lower16:elemlog
+       mov     r5, #0
+       movt    r1, #:upper16:elemlog
+       add     r4, r2, #1
+       add     ip, r1, r2, asl #4
+       str     r5, [r1, r2, asl #4]
+       str     r4, [r3]
+       str     r0, [ip, #4]
+       str     lr, [ip, #12]
+.L17:
+       ldrd    r4, [sp]
+       add     sp, sp, #8
+       ldr     pc, [sp], #4
+
+
+@*****************************************************************************
+@ This API logs the task switch hooks. 
+@*****************************************************************************
+mySwitch:
+       stmfd   sp!, {r4, r5, r6, lr}
+       MRC p15, 0, r4, c9, c13, 0      
+       movw    r3, #:lower16:log_idx
+       movt    r3, #:upper16:log_idx
+       ldr     r2, [r3]
+       cmp     r2, #1048576
+       bcs     .L21
+       movw    ip, #:lower16:elemlog
+       mov     r6, #3
+       movt    ip, #:upper16:elemlog
+       add     r5, r2, #1
+       add     lr, ip, r2, asl #4
+       str     r6, [ip, r2, asl #4]
+       str     r5, [r3]
+       str     r1, [lr, #4]
+       str     r0, [lr, #8]
+       str     r4, [lr, #12]
+.L21:
+       ldrd    r4, [sp]
+       ldr     r6, [sp, #8]
+       add     sp, sp, #12
+       ldr     pc, [sp], #4
+
+@******************************************************************************
+@*                                   LABELS
+@******************************************************************************    
+
+    .end
+
diff --git a/packages/ti/utils/profiling/src/profilingHooksArmV8.c b/packages/ti/utils/profiling/src/profilingHooksArmV8.c
new file mode 100644 (file)
index 0000000..f00be23
--- /dev/null
@@ -0,0 +1,223 @@
+/*
+ * Copyright (c) 2018, Texas Instruments Incorporated
+ * 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 Texas Instruments Incorporated nor the names of
+ *    its contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+ * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+ * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+/**
+ *  @file    profilingHooksA15.c
+ *
+ *  @brief   ARM Implementations of the runtime programming hooks of the Processor SDK Profiling Tool.
+ *
+ *  For more information, see:
+ *  - @subpage profCCS
+ *  - @subpage profDSS
+ *
+ *  ## Usage ##
+ *
+ *  Applications that are included in a profiling session must  set these
+ *  compiler flags for the desired platform:
+ *    - ARM: `-finstrument-functions -gdwarf-3 -g`
+ *    - DSP: `--entry_parm=address --exit_hook=ti_utils_exit --exit_parm=address --entry_hook=ti_utils_entry -g`
+ *    - M4: `--entry_parm=address --exit_hook=ti_utils_exit --exit_parm=address --entry_hook=ti_utils_entry -g`
+ *
+ *  For best results, ensure that the optimization levels are consistent between
+ *  the library and the project (typically -O3, or optimization level 3).
+ *
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdint.h>
+#include "profilingHooks.h"
+#include "profiling_osal.h"
+
+
+int32_t CurrentTaskHookSetId, MaxTaskHookSetId;
+
+/*!
+ *  @brief    Maximum log count
+ *
+ *  This is a predefined value to indicate when the instrumentation hooks should
+ *  stop logging data. This is important for applications that have long polling
+ *  loops or a device that has a small cache.
+ */
+#define MAX_LOG (1U*1024U*1024U)
+
+uint32_t log_idx = 0;
+
+/*!
+ *  @brief    Utils profiling log structure
+ *
+ *  Utils log elements have a predefined structure of four words (to avoid the
+ *  need of malloc) and are stored in an array of predefined length, `elemlog`.
+ */
+typedef struct{
+    /*! Indicates either enter or exit */
+    int32_t isEnter;
+    /*! Pointer address of the function in current context */
+    uintptr_t this_fn;
+    /*! Optional: Pointer address of calling function in current context */
+    uintptr_t call_site;
+    /*! Timestamp of the entry or exit */
+    uint32_t timestamp;
+}utilsProfilingElem;
+
+utilsProfilingElem elemlog[MAX_LOG] = {{0}};
+
+/*!
+ *  @brief    Empty function for time adjustment
+ *
+ *  @ingroup pdk_profiling_hooks
+ *
+ *  Nothing more than an empty function that is referenced to measure the time
+ *  used by the instrumentation functions themselves. This is recorded and
+ *  passed into post-processing for a more accurate result.
+ */
+void __attribute__ ((noinline)) empty_fn(void); /*for misra warnings*/
+void __attribute__ ((noinline)) empty_fn(void){
+}
+
+/*!
+ *  @brief    ARMv7 GCC Utils Entry Hook
+ *
+ *  @ingroup pdk_profiling_hooks
+ *
+ *  Instruments the entry point, call site and timestamp of the current function
+ *  into memory. Note that this is a standard GCC library prototype function and
+ *  is automatically referenced at the entry of every function by GCC.
+ *
+ *  @param    *this_fn    Function Assembly Address (Hexadecimal)
+ *  @param    *call_site  Call Site Assembly Address (Hexadecimal)
+ *
+ *  TODO: The Hardware Interrupt Disable functions are disabled because there
+ *        are still issues with OSAL that need to be resolved. Using these
+ *        functions causes memory corruption.
+ */
+void __attribute__((no_instrument_function))__cyg_profile_func_enter(const void *this_fn, const void *call_site){
+    uint32_t val;
+
+    asm volatile("mrs %0, pmccntr_el0" : "=r" (val));
+
+    if (log_idx == 0){
+        uint32_t entry_offset = 0;
+        uint32_t exit_offset = 0;
+        log_idx++;
+        log_idx++;
+        int32_t i;
+        for (i = 0; i < 10; i++){
+            empty_fn();
+        }
+        elemlog[0].isEnter = 2;
+        elemlog[0].this_fn = 1;
+        elemlog[0].call_site = 1;
+        /*Taking 10 sample and subtracting (exit_log - entry log) of present for calculating the entry offset*/
+        for(i=1;i<=10;i++)
+        {
+            entry_offset += (elemlog[(2*i)+1].timestamp - elemlog[(2*i)].timestamp);
+        }
+        /* Saving the average of 10 sample */
+        elemlog[0].timestamp = entry_offset/10U;
+        elemlog[1].isEnter = 2;
+        elemlog[1].this_fn = 1;
+        elemlog[1].call_site = 2;
+        /* Taking 9 sample and subtracting (entry_log of next - exit_log of present) for calculating the exit offset*/
+        for(i=2;i<=10;i++)
+        {
+            exit_offset += (elemlog[(2*i)].timestamp - elemlog[(2*i)-1].timestamp);
+        }
+        /* Saving the average of 9 sample */
+        elemlog[1].timestamp = exit_offset/9U;
+        log_idx = 2U;
+    }
+    if (log_idx < MAX_LOG){
+        elemlog[log_idx].isEnter = 1;
+        elemlog[log_idx].this_fn = (uintptr_t)this_fn;
+        elemlog[log_idx].call_site = (uintptr_t)call_site;
+        elemlog[log_idx].timestamp = (int32_t)val;
+        log_idx++;
+    }
+}
+
+/*!
+ *  @brief    ARMv7 GCC Utils Exit Hook
+ *
+ *  @ingroup pdk_profiling_hooks
+ *
+ *  Instruments the entry point, call site and timestamp of the current function
+ *  into memory. Note that this is a standard GCC library prototype function and
+ *  is automatically referenced at the entry of every function by GCC.
+ *
+ *  @param    *this_fn    Function Assembly Address (Hexadecimal)
+ *  @param    *call_site  Call Site Assembly Address (Hexadecimal)
+ *
+ *  TODO: The Hardware Interrupt Disable functions are disabled because there
+ *        are still issues with OSAL that need to be resolved. Using these
+ *        functions causes memory corruption.
+ */
+void __attribute__((no_instrument_function))__cyg_profile_func_exit(const void *this_fn, void *call_site){
+    uint32_t val;
+
+    asm volatile("mrs %0, pmccntr_el0" : "=r" (val));
+
+    if (log_idx < MAX_LOG){
+        elemlog[log_idx].isEnter = 0;
+        elemlog[log_idx].this_fn = (uintptr_t)this_fn;
+        elemlog[log_idx].timestamp = (int32_t)val;
+        log_idx++;
+    }
+}
+void __attribute__((no_instrument_function))TaskRegisterId(int32_t hookSetId); /*for misra warnings*/
+void __attribute__((no_instrument_function))TaskRegisterId(int32_t hookSetId)
+{
+       CurrentTaskHookSetId = hookSetId;
+    if(MaxTaskHookSetId < CurrentTaskHookSetId)
+    {
+        MaxTaskHookSetId = CurrentTaskHookSetId;
+    }
+}
+
+/* ======== mySwitch ========
+* invoked whenever a Task switch occurs/is made ready to run */
+void __attribute__((no_instrument_function))mySwitch(const void* prev, const void* next); /*for misra warnings*/
+void __attribute__((no_instrument_function))mySwitch(const void* prev, const void* next)
+{
+    uint32_t val;
+
+
+    asm volatile("mrs %0, pmccntr_el0" : "=r" (val));
+
+    if (log_idx < MAX_LOG){
+        elemlog[log_idx].isEnter = 3;
+        elemlog[log_idx].this_fn = (uintptr_t)next;
+        elemlog[log_idx].call_site = (uintptr_t)prev;
+        elemlog[log_idx].timestamp = (int32_t)val;
+        log_idx++;
+    }
+}
+
diff --git a/packages/ti/utils/profiling/src/profilingHooksC66.c b/packages/ti/utils/profiling/src/profilingHooksC66.c
new file mode 100644 (file)
index 0000000..25b163f
--- /dev/null
@@ -0,0 +1,233 @@
+/*
+ * Copyright (c) 2015 - 2018, Texas Instruments Incorporated
+ * 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 Texas Instruments Incorporated nor the names of
+ *    its contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+ * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+ * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+/**
+ *  @file    profilingHooksC66.c
+ *
+ *  @brief   DSP Implementations of the runtime programming hooks of the Processor SDK Profiling Tool.
+ *
+ *  ## Usage ##
+ *
+ *  For more information, see:
+ *  - @subpage profCCS
+ *  - @subpage profDSS
+ *
+ *  Applications that are included in a profiling session must  set these
+ *  compiler flags for the desired platform:
+ *    - ARM: `-finstrument-functions -gdwarf-3 -g`
+ *    - DSP: `--entry_parm=address --exit_hook=ti_utils_exit --exit_parm=address --entry_hook=ti_utils_entry -g`
+ *    - M4: `--entry_parm=address --exit_hook=ti_utils_exit --exit_parm=address --entry_hook=ti_utils_entry -g`
+ *
+ *  For best results, ensure that the optimization levels are consistent between
+ *  the library and the project (typically -O3, or optimization level 3).
+ *
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdint.h>
+#include "profilingHooks.h"
+#include <ti/csl/csl_chip.h>
+
+int32_t CurrentTaskHookSetId, MaxTaskHookSetId;
+
+/*!
+ *  @brief    Maximum log count
+ *
+ *  This is a predefined value to indicate when the instrumentation hooks should
+ *  stop logging data. This is important for applications that have long polling
+ *  loops or a device that has a small cache.
+ */
+#define MAX_LOG (4U*1024U*1024U)
+#define MAX_CORES (8U)
+
+uint32_t log_idx = 0;
+uint32_t waddress = 0;
+uint32_t lvl = 0;
+
+/*!
+ *  @brief    Utils profiling log structure
+ *
+ *  Utils log elements have a predefined structure of four words (to avoid the
+ *  need of malloc) and are stored in an array of predefined length, `elemlog`.
+ */
+typedef struct{
+    /*! Indicates either enter or exit */
+    int32_t isEnter;
+    /*! Pointer address of the function in current context */
+    int32_t this_fn;
+    /*! Optional: Pointer address of calling function in current context */
+    int32_t call_site;
+    /*! Timestamp of the entry or exit */
+    uint32_t timestamp;
+}utilsProfilingElem;
+
+#ifdef __cplusplus
+#pragma DATA_SECTION (".fardata:benchmarking")
+#else
+#pragma DATA_SECTION (elemlog, ".fardata:benchmarking");
+#endif
+utilsProfilingElem elemlog[MAX_LOG] = {{0}};
+utilsProfilingElem *pElemLog;
+
+/*!
+ *  @brief    Empty function for time adjustment
+ *
+ *  Nothing more than an empty function that is referenced to measure the time
+ *  used by the instrumentation functions themselves. This is recorded and
+ *  passed into post-processing for a more accurate result.
+ */
+
+#ifdef __cplusplus
+#pragma FUNC_CANNOT_INLINE
+#else
+#pragma FUNC_CANNOT_INLINE(empty_fn);
+#endif
+void empty_fn(void); /*for misra warnings*/
+void empty_fn(void){
+}
+
+extern cregister volatile uint32_t TSCL;
+
+/*!
+ *  @brief    TI Toolchain Utils Entry Hook
+ *
+ *  @ingroup pdk_profiling_hooks
+ *
+ *  Instruments the entry point and timestamp of the current function into
+ *  memory. Note that this function is automatically referenced at entry of
+ *  every function by TI Toolchain.
+ *
+ *  @param    *func_addr  Function Assembly Address (Hexadecimal)
+ */
+void ti_utils_entry(void (* func_addr)(void)){
+    if (log_idx == 0){
+        TSCL = 0;
+        uint32_t val = TSCL;
+        uint32_t entry_offset = 0;
+        uint32_t exit_offset = 0;
+        waddress = DNUM*MAX_LOG/MAX_CORES;
+        pElemLog = &elemlog[waddress];
+        log_idx++;
+        log_idx++;
+        int32_t i;
+        for (i = 0; i < 10; i++){
+            empty_fn();
+        }
+        pElemLog[0].isEnter = 2;
+        pElemLog[0].this_fn = 2;
+        pElemLog[0].call_site = 1;
+        /*Taking 10 sample and subtracting (exit_log - entry log) of present for calculating the entry offset*/
+        for(i=1;i<=10;i++)
+        {
+            entry_offset += (pElemLog[(2*i)+1].timestamp - pElemLog[(2*i)].timestamp);
+        }
+        /* Saving the average of 10 sample */
+        pElemLog[0].timestamp = entry_offset/10U;
+        pElemLog[1].isEnter = 2;
+        pElemLog[1].this_fn = 2;
+        pElemLog[1].call_site = 2;
+        /* Taking 9 sample and subtracting (entry_log of next - exit_log of present) for calculating the exit offset*/
+        for(i=2;i<=10;i++)
+        {
+            exit_offset += (pElemLog[(2*i)].timestamp - pElemLog[(2*i)-1].timestamp);
+        }
+        /* Saving the average of 9 sample */
+        pElemLog[1].timestamp = exit_offset/9U;
+        log_idx = 2U;
+    }
+    uint32_t uiOldGIE = _disable_interrupts();
+    if (log_idx < MAX_LOG){
+        pElemLog[log_idx].isEnter = 1;
+        pElemLog[log_idx].this_fn = (int32_t)func_addr;
+        pElemLog[log_idx].timestamp = TSCL;
+      log_idx++;
+    }
+    _restore_interrupts(uiOldGIE);
+}
+
+/*!
+ *  @brief    TI Toolchain Utils Exit Hook
+ *
+ *  @ingroup pdk_profiling_hooks
+ *
+ *  Instruments the exit point and timestamp of the current function into
+ *  memory. Note that this function is automatically referenced at end of
+ *  every function by TI Toolchain.
+ *
+ *  @param    *func_addr  Function Assembly Address (Hexadecimal)
+ */
+void ti_utils_exit(void (* func_addr)(void)){
+    uint32_t uiOldGIE = _disable_interrupts();
+    if (log_idx < MAX_LOG){
+        pElemLog[log_idx].isEnter = 0;
+        pElemLog[log_idx].this_fn = (int32_t)func_addr;
+        pElemLog[log_idx].timestamp = TSCL;
+        log_idx++;
+    }
+    _restore_interrupts(uiOldGIE);
+}
+
+void TaskRegisterId(int32_t hookSetId); /*for misra warnings*/
+#ifdef __cplusplus
+#pragma NO_HOOKS
+#else
+#pragma NO_HOOKS (TaskRegisterId)
+#endif
+void TaskRegisterId(int32_t hookSetId)
+{
+       CurrentTaskHookSetId = hookSetId;
+    if(MaxTaskHookSetId < CurrentTaskHookSetId)
+    {
+        MaxTaskHookSetId = CurrentTaskHookSetId;
+    }
+}
+
+/* ======== mySwitch ========
+* invoked whenever a Task switch occurs/is made ready to run */
+void mySwitch(const void* prev, const void* next); /*for misra warnings*/
+#ifdef __cplusplus
+#pragma NO_HOOKS
+#else
+#pragma NO_HOOKS (mySwitch)
+#endif
+void mySwitch(const void* prev, const void* next)
+{
+    if (log_idx < MAX_LOG){
+        pElemLog[log_idx].isEnter = 3;
+        pElemLog[log_idx].this_fn = (int32_t)next;
+        pElemLog[log_idx].call_site = (int32_t)prev;
+        pElemLog[log_idx].timestamp = TSCL;
+        log_idx++;
+    }
+}
+
+
diff --git a/packages/ti/utils/profiling/src/profilingHooksM4.c b/packages/ti/utils/profiling/src/profilingHooksM4.c
new file mode 100644 (file)
index 0000000..0e31760
--- /dev/null
@@ -0,0 +1,232 @@
+/*
+ * Copyright (c) 2015 - 2018, Texas Instruments Incorporated
+ * 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 Texas Instruments Incorporated nor the names of
+ *    its contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+ * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+ * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+/**
+ *  @file    profilingHooksM4.c
+ *
+ *  @brief   M4 Implementations of the runtime programming hooks of the Processor SDK Profiling Tool.
+ *
+ *  For more information, see:
+ *  - @subpage profCCS
+ *  - @subpage profDSS
+ *
+ *  ## Usage ##
+ *
+ *  Applications that are included in a profiling session must  set these
+ *  compiler flags for the desired platform:
+ *    - ARM: `-finstrument-functions -gdwarf-3 -g`
+ *    - DSP: `--entry_parm=address --exit_hook=ti_utils_exit --exit_parm=address --entry_hook=ti_utils_entry -g`
+ *    - M4: `--entry_parm=address --exit_hook=ti_utils_exit --exit_parm=address --entry_hook=ti_utils_entry -g`
+ *
+ *  The `_ENABLE_BM` flag is used to indicate in a class at compiletime whether
+ *  or not profiling is being used.
+ *
+ *  For best results, ensure that the optimization levels are consistent between
+ *  the library and the project (typically -O3, or optimization level 3).
+ *
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdint.h>
+#include "profilingHooks.h"
+
+int32_t CurrentTaskHookSetId, MaxTaskHookSetId;
+
+/*!
+ *  @brief    Maximum log count
+ *
+ *  This is a predefined value to indicate when the instrumentation hooks should
+ *  stop logging data. This is important for applications that have long polling
+ *  loops or a device that has a small cache.
+ */
+#define MAX_LOG (1U*1024U*1024U)
+
+uint32_t log_idx = 0;
+uint32_t lvl = 0;
+
+/*!
+ *  @brief    Utils profiling log structure
+ *
+ *  Utils log elements have a predefined structure of four words (to avoid the
+ *  need of malloc) and are stored in an array of predefined length, `elemlog`.
+ */
+typedef struct{
+    /*! Indicates either enter or exit */
+    int32_t isEnter;
+    /*! Pointer address of the function in current context */
+    int32_t this_fn;
+    /*! Optional: Pointer address of calling function in current context */
+    int32_t call_site;
+    /*! Timestamp of the entry or exit */
+    uint32_t timestamp;
+}utilsProfilingElem;
+
+utilsProfilingElem elemlog[MAX_LOG] = {{0}};
+
+/*!
+ *  @brief    Empty function for time adjustment
+ *
+ *  @ingroup pdk_profiling_hooks
+ *
+ *  Nothing more than an empty function that is referenced to measure the time
+ *  used by the instrumentation functions themselves. This is recorded and
+ *  passed into post-processing for a more accurate result.
+ */
+#ifdef __cplusplus
+#pragma FUNC_CANNOT_INLINE
+#else
+#pragma FUNC_CANNOT_INLINE(empty_fn);
+#endif
+void empty_fn(void); /*for misra warnings*/
+void empty_fn(void){
+}
+
+/* IPU UNICACHE SCTM Registers:
+ * Note that there are multiple counters that can be enabled, but for simplicity
+ * only the first registers are used. (eg. CACHE_SCTM_CTCR_WOT_j is stored at
+ * addresses 0x0000 0108 + 0x4*i for i = 0 to 1) For others, see TRM
+ * reference 7.4.3 */
+volatile uint32_t *CACHE_SCTM_CTCR_WOT_j = (uint32_t *)0x55080508;
+volatile uint32_t *CACHE_SCTM_CTCNTL = (uint32_t *)0x55080400;
+volatile uint32_t *CACHE_SCTM_CTCNTR_k = (uint32_t *)0x055080588;
+
+/*!
+ *  @brief    TI Toolchain Utils Entry Hook
+ *
+ *  @ingroup pdk_profiling_hooks
+ *
+ *  Instruments the entry point and timestamp of the current function into
+ *  memory. Note that this function is automatically referenced at entry of
+ *  every function by TI Toolchain.
+ *
+ *  @param    *func_addr  Function Assembly Address (Hexadecimal)
+ */
+void ti_utils_entry(void (* func_addr)(void)){
+    if (log_idx == 0){
+        /* SCTM Global Enable: Assign CACHE_SCTM_CTCNTL[0] = 1 to enable all
+         * individual counters. Must be enabled for ANY counter to be configured */
+        *CACHE_SCTM_CTCNTL = *CACHE_SCTM_CTCNTL | (uint32_t)1;
+        /* Counter Enable: Assign CACHE_SCTM_CTCR_WOT_j[0] = 1 to increment */
+        *CACHE_SCTM_CTCR_WOT_j = *CACHE_SCTM_CTCR_WOT_j | (uint32_t)1;
+        /* Counter Value: Register containing the value of the configured counter */
+        uint32_t val = *CACHE_SCTM_CTCNTR_k;
+        uint32_t entry_offset = 0;
+        uint32_t exit_offset = 0;
+        log_idx++;
+        log_idx++;
+        int32_t i;
+        for (i = 0; i < 10; i++){
+            empty_fn();
+        }
+        elemlog[0].isEnter = 2;
+        elemlog[0].this_fn = 3;
+        elemlog[0].call_site = 1;
+        /*Taking 10 sample and subtracting (exit_log - entry log) of present for calculating the entry offset*/
+        for(i=1;i<=10;i++)
+        {
+            entry_offset += (elemlog[(2*i)+1].timestamp - elemlog[(2*i)].timestamp);
+        }
+        /* Saving the average of 10 sample */
+        elemlog[0].timestamp = entry_offset/10U;
+        elemlog[1].isEnter = 2;
+        elemlog[1].this_fn = 3;
+        elemlog[1].call_site = 2;
+        /* Taking 9 sample and subtracting (entry_log of next - exit_log of present) for calculating the exit offset*/
+        for(i=2;i<=10;i++)
+        {
+            exit_offset += (elemlog[(2*i)].timestamp - elemlog[(2*i)-1].timestamp);
+        }
+        /* Saving the average of 9 sample */
+        elemlog[1].timestamp = exit_offset/9U;
+        log_idx = 2U;
+    }
+    if (log_idx < MAX_LOG){
+        elemlog[log_idx].isEnter = 1;
+        elemlog[log_idx].this_fn = (int32_t)func_addr;
+        elemlog[log_idx].timestamp = *CACHE_SCTM_CTCNTR_k;
+      log_idx++;
+    }
+}
+
+/*!
+ *  @brief    TI Toolchain Utils Exit Hook
+ *
+ *  @ingroup pdk_profiling_hooks
+ *
+ *  Instruments the exit point and timestamp of the current function into
+ *  memory. Note that this function is automatically referenced at end of
+ *  every function by TI Toolchain.
+ *
+ *  @param    *func_addr  Function Assembly Address (Hexadecimal)
+ */
+void ti_utils_exit(void (* func_addr)(void)){
+    if (log_idx < MAX_LOG){
+        elemlog[log_idx].isEnter = 0;
+        elemlog[log_idx].this_fn = (int32_t)func_addr;
+        elemlog[log_idx].timestamp = *CACHE_SCTM_CTCNTR_k;
+        log_idx++;
+    }
+}
+
+void TaskRegisterId(int32_t hookSetId); /*for misra warnings*/
+#ifdef __cplusplus
+#pragma NO_HOOKS
+#else
+#pragma NO_HOOKS (TaskRegisterId)
+#endif
+void TaskRegisterId(int32_t hookSetId)
+{
+       CurrentTaskHookSetId = hookSetId;
+    if(MaxTaskHookSetId < CurrentTaskHookSetId)
+    {
+        MaxTaskHookSetId = CurrentTaskHookSetId;
+    }
+}
+
+/* ======== mySwitch ========
+* invoked whenever a Task switch occurs/is made ready to run */
+void mySwitch(const void* prev, const void* next); /*for misra warnings*/
+#ifdef __cplusplus
+#pragma NO_HOOKS
+#else
+#pragma NO_HOOKS (mySwitch)
+#endif
+void mySwitch(const void* prev, const void* next)
+{
+    if (log_idx < MAX_LOG){
+        elemlog[log_idx].isEnter = 3;
+        elemlog[log_idx].this_fn = (int32_t)next;
+        elemlog[log_idx].call_site = (int32_t)prev;
+        elemlog[log_idx].timestamp = *CACHE_SCTM_CTCNTR_k;
+        log_idx++;
+    }
+}
diff --git a/packages/ti/utils/profiling/src/profilingHooksR5.c b/packages/ti/utils/profiling/src/profilingHooksR5.c
new file mode 100644 (file)
index 0000000..6defed3
--- /dev/null
@@ -0,0 +1,205 @@
+/*
+ * Copyright (c) 2018-2019, Texas Instruments Incorporated
+ * 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 Texas Instruments Incorporated nor the names of
+ *    its contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+ * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+ * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+ * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+ * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+/**
+ *  @file    profilingHooksR5.c
+ *
+ *  @brief   R5 Implementations of the runtime programming hooks of the Processor SDK Profiling Tool.
+ *
+ *  For more information, see:
+ *  - @subpage profCCS
+ *  - @subpage profDSS
+ *
+ *  ## Usage ##
+ *
+ *  Applications that are included in a profiling session must  set these
+ *  compiler flags for the desired platform:
+ *    - ARM: `-finstrument-functions -gdwarf-3 -g`
+ *    - DSP: `--entry_parm=address --exit_hook=ti_utils_exit --exit_parm=address --entry_hook=ti_utils_entry -g`
+ *    - M4: `--entry_parm=address --exit_hook=ti_utils_exit --exit_parm=address --entry_hook=ti_utils_entry -g`
+ *
+ *  The `_ENABLE_BM` flag is used to indicate in a class at compiletime whether
+ *  or not profiling is being used.
+ *
+ *  For best results, ensure that the optimization levels are consistent between
+ *  the library and the project (typically -O3, or optimization level 3).
+ *
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdint.h>
+#include "profilingHooks.h"
+#include <ti/csl/arch/r5/csl_arm_r5_pmu.h>
+
+int32_t CurrentTaskHookSetId, MaxTaskHookSetId;
+
+/*!
+ *  @brief    Maximum log count
+ *
+ *  This is a predefined value to indicate when the instrumentation hooks should
+ *  stop logging data. This is important for applications that have long polling
+ *  loops or a device that has a small cache.
+ */
+#define MAX_LOG (1U*1024U*1024U)
+
+uint32_t log_idx = 0;
+uint32_t lvl = 0;
+
+/*!
+ *  @brief    Utils profiling log structure
+ *
+ *  Utils log elements have a predefined structure of four words (to avoid the
+ *  need of malloc) and are stored in an array of predefined length, `elemlog`.
+ */
+typedef struct{
+    /*! Indicates either enter or exit */
+    int32_t isEnter;
+    /*! Pointer address of the function in current context */
+    int32_t this_fn;
+    /*! Optional: Pointer address of calling function in current context */
+    int32_t call_site;
+    /*! Timestamp of the entry or exit */
+    uint32_t timestamp;
+}utilsProfilingElem;
+
+utilsProfilingElem elemlog[MAX_LOG] = {{0}};
+
+/*!
+ *  @brief    Empty function for time adjustment
+ *
+ *  @ingroup pdk_profiling_hooks
+ *
+ *  Nothing more than an empty function that is referenced to measure the time
+ *  used by the instrumentation functions themselves. This is recorded and
+ *  passed into post-processing for a more accurate result.
+ */
+#pragma FUNC_CANNOT_INLINE(empty_fn);
+void empty_fn(void); /*for misra warnings*/
+void empty_fn(void){
+}
+
+/*!
+ *  @brief    TI Toolchain Utils Entry Hook
+ *
+ *  @ingroup pdk_profiling_hooks
+ *
+ *  Instruments the entry point and timestamp of the current function into
+ *  memory. Note that this function is automatically referenced at entry of
+ *  every function by TI Toolchain.
+ *
+ *  @param    *func_addr  Function Assembly Address (Hexadecimal)
+ */
+void ti_utils_entry(void (* func_addr)(void)){
+    if (log_idx == 0){
+        uint32_t entry_offset = 0;
+        uint32_t exit_offset = 0;
+        log_idx++;
+        log_idx++;
+        int32_t i;
+        for (i = 0; i < 10; i++){
+            empty_fn();
+        }
+        elemlog[0].isEnter = 2;
+        elemlog[0].this_fn = 3;
+        elemlog[0].call_site = 1;
+        /*Taking 10 sample and subtracting (exit_log - entry log) of present for calculating the entry offset*/
+        for(i=1;i<=10;i++)
+        {
+            entry_offset += (elemlog[(2*i)+1].timestamp - elemlog[(2*i)].timestamp);
+        }
+        /* Saving the average of 10 sample */
+        elemlog[0].timestamp = entry_offset/10U;
+        elemlog[1].isEnter = 2;
+        elemlog[1].this_fn = 3;
+        elemlog[1].call_site = 2;
+        /* Taking 9 sample and subtracting (entry_log of next - exit_log of present) for calculating the exit offset*/
+        for(i=2;i<=10;i++)
+        {
+            exit_offset += (elemlog[(2*i)].timestamp - elemlog[(2*i)-1].timestamp);
+        }
+        /* Saving the average of 9 sample */
+        elemlog[1].timestamp = exit_offset/9U;
+        log_idx = 2U;
+    }
+    if (log_idx < MAX_LOG){
+        elemlog[log_idx].isEnter = 1;
+        elemlog[log_idx].this_fn = (int32_t)func_addr;
+        elemlog[log_idx].timestamp = CSL_armR5PmuReadCntr(CSL_ARM_R5_PMU_CYCLE_COUNTER_NUM);
+      log_idx++;
+    }
+}
+
+/*!
+ *  @brief    TI Toolchain Utils Exit Hook
+ *
+ *  @ingroup pdk_profiling_hooks
+ *
+ *  Instruments the exit point and timestamp of the current function into
+ *  memory. Note that this function is automatically referenced at end of
+ *  every function by TI Toolchain.
+ *
+ *  @param    *func_addr  Function Assembly Address (Hexadecimal)
+ */
+void ti_utils_exit(void (* func_addr)(void)){
+    if (log_idx < MAX_LOG){
+        elemlog[log_idx].isEnter = 0;
+        elemlog[log_idx].this_fn = (int32_t)func_addr;
+        elemlog[log_idx].timestamp = CSL_armR5PmuReadCntr(CSL_ARM_R5_PMU_CYCLE_COUNTER_NUM);
+        log_idx++;
+    }
+}
+
+#pragma NO_HOOKS (TaskRegisterId)
+void TaskRegisterId(int32_t hookSetId); /*for misra warnings*/
+void TaskRegisterId(int32_t hookSetId)
+{
+       CurrentTaskHookSetId = hookSetId;
+    if(MaxTaskHookSetId < CurrentTaskHookSetId)
+    {
+        MaxTaskHookSetId = CurrentTaskHookSetId;
+    }
+}
+
+/* ======== mySwitch ========
+* invoked whenever a Task switch occurs/is made ready to run */
+#pragma NO_HOOKS (mySwitch)
+void mySwitch(const void* prev, const void* next); /*for misra warnings*/
+void mySwitch(const void* prev, const void* next)
+{
+    if (log_idx < MAX_LOG){
+        elemlog[log_idx].isEnter = 3;
+        elemlog[log_idx].this_fn = (int32_t)next;
+        elemlog[log_idx].call_site = (int32_t)prev;
+        elemlog[log_idx].timestamp = CSL_armR5PmuReadCntr(CSL_ARM_R5_PMU_CYCLE_COUNTER_NUM);
+        log_idx++;
+    }
+}
diff --git a/packages/ti/utils/trace/.gitignore b/packages/ti/utils/trace/.gitignore
new file mode 100644 (file)
index 0000000..5f4fca7
--- /dev/null
@@ -0,0 +1,19 @@
+*.swp
+*~
+*.bak
+*.orig
+.dlls
+.executables
+.interfaces
+.libraries
+.xdcenv.mak
+Settings.h
+Settings.xdc
+docs/Doxyfile
+docs/doxygen/
+docs/rmDocs.chm
+lib/
+package.mak
+package/
+packages/
+install/
diff --git a/packages/ti/utils/trace/Settings.xdc.xdt b/packages/ti/utils/trace/Settings.xdc.xdt
new file mode 100644 (file)
index 0000000..744bc63
--- /dev/null
@@ -0,0 +1,36 @@
+
+%%{
+/*!
+ *  This template implements the Settings.xdc
+ */
+  /* Versioning */
+  var ver = this;
+  for each(i=0;i<ver.length;i++)
+  {
+      if(String(ver[i]).length < 2)
+      {
+        ver[i]="0"+ver[i];
+      }
+  }
+
+  var packageVersion = "\""+ver[0]+"."+ver[1]+"."+ver[2]+"."+ver[3]+"\"";
+
+%%}
+
+module Settings
+{
+    config string traceversionString = `packageVersion`;
+       
+    /*! This variable is to control the device library type selection.
+     * By default this variable is set to release.
+     * 
+     * To use CSL to use the debug/release library, add the following lines to config
+     * file and set the library profile accordingly:
+     * 
+     *      var Uart Settings = xdc.useModule ('ti.Uart.Settings');
+     *      UartSettings.libProfile = "debug";
+     * 
+     */
+    metaonly config string libProfile = "release";     
+
+}
diff --git a/packages/ti/utils/trace/build/buildlib.xs b/packages/ti/utils/trace/build/buildlib.xs
new file mode 100644 (file)
index 0000000..80faf01
--- /dev/null
@@ -0,0 +1,608 @@
+/******************************************************************************
+ * FILE PURPOSE: Build Library Utilities
+ ******************************************************************************
+ * FILE NAME: buildlib.xs
+ *
+ * DESCRIPTION:
+ *  This file contains common routines that are used by the various utilities.
+ *
+ * Copyright (C) 2019, Texas Instruments, Inc.
+ *****************************************************************************/
+
+/**************************************************************************
+ * FUNCTION NAME : listAllFiles
+ **************************************************************************
+ * DESCRIPTION   :
+ *  Utility function which lists all files with a specific extension
+ *  present in a directory and any directory inside it.
+ **************************************************************************/
+function listAllFiles(ext, dir, recurse)
+{
+    var srcFile = [];
+    var d;
+
+    /* If recurse parameter is not specified we default to recursive search. */
+    if (recurse == null)
+        recurse = true;
+
+    if (dir == undefined)
+          d = ".";
+    else
+      d = dir;
+
+    /* Get access to the current directory. */
+    var file = new java.io.File(d);
+
+    /* Check if the file exists and it is a directory. */
+    if (file.exists() && file.isDirectory())
+    {
+        /* Get a list of all files in the specific directory. */
+        var fileList = file.listFiles();
+        for (var i = 0; i < fileList.length; i++)
+        {
+            /* Dont add the generated directory 'package' and any of its files
+             * to the list here. */
+            if (fileList[i].getName().matches("package") == false)
+            {
+                /* Check if the detected file is a directory */
+                if (fileList[i].isDirectory())
+                {
+                    /* We will recurse into the subdirectory only if required to do so. */
+                    if (recurse == true)
+                    {
+                        /* Generate the directory Name in which we will recurse. */
+                        var directoryName = d + "/" + fileList[i].getName();
+
+                        /* Get a list of all files in this directory */
+                        var fileListing = listAllFiles (ext, directoryName, recurse);
+                        if (fileListing != null)
+                        {
+                            /* Return a list of all file names in the directory. */
+                            for (var j = 0 ; j < fileListing.length; j++)
+                                srcFile[srcFile.length++] = fileListing[j];
+                        }
+                    }
+                }
+                else
+                {
+                    /* This was a file. Check if the file name matches the extension */
+                    if (fileList[i].getName().endsWith(ext) == true)
+                        srcFile[srcFile.length++] = d + "/" + fileList[i].getName();
+                }
+            }
+        }
+
+        return srcFile;
+    }
+    return null;
+}
+
+
+function createMake(makefile)
+{
+    /* Create the main make file */
+    var fileModule = xdc.module('xdc.services.io.File');
+    if(makefile==undefined)
+    {
+      try{
+          makefile = fileModule.open("makefile", "w");
+         } catch (ex)
+         {
+           print("makefile cannot be written to. Please check Writing Permissions.");
+           java.lang.System.exit(1);
+         }
+
+      Pkg.makePrologue += "\ninclude makefile\n";
+
+      Pkg.makeEpilogue += "\nclean::\n\t-$(RM)  makefile\n";
+      makefile.writeLine("#*******************************************************************************");
+      makefile.writeLine("#* FILE PURPOSE: Top level makefile for Creating Component Libraries");
+      makefile.writeLine("#*******************************************************************************");
+      makefile.writeLine("#* FILE NAME: makefile");
+      makefile.writeLine("#*");
+      makefile.writeLine("#* DESCRIPTION: Defines Compiler tools paths, libraries , Build Options ");
+      makefile.writeLine("#*");
+      makefile.writeLine("#*");
+      makefile.writeLine("#*******************************************************************************");
+      makefile.writeLine("#*");
+      makefile.writeLine("# (Mandatory) Specify where various tools are installed.");
+
+      var file = xdc.module('xdc.services.io.File');
+
+
+      makefile.writeLine("\n# Output for prebuilt generated libraries");
+      makefile.writeLine("export LIBDIR ?= ./lib");
+      /* use sectti from path */
+      makefile.writeLine("export SECTTI ?= sectti");
+
+      /* Create INCDIR from XDCPATH */
+
+      /* copy the environment array from the current environment */
+      var env   = java.lang.System.getenv();
+      var getxdcpath=String(java.lang.System.getenv("XDCPATH"));
+      getxdcpath= getxdcpath.replace(/\\/g,"/");
+      var keys  = env.keySet().toArray();
+      var key;
+      var stat={};
+      var env_j=[];
+      var listxdcpath = new Array();
+      for (var i = 0; i < keys.length; i++) {
+           key = String(keys[i]);
+           if((key.match("INSTALL_PATH")) || (key.match("INSTALLDIR")))
+           {
+             var keyPath=String(env.get(key));
+             keyPath=keyPath.replace(/\\/g,"/");
+             var file = xdc.module('xdc.services.io.File');
+             keyPath=file.getDOSPath(keyPath);
+             if(getxdcpath.toString().match(keyPath))
+             {
+                 listxdcpath.push({keyname: key,keypath: keyPath});
+                 while(getxdcpath.toString().match(keyPath))
+                 {
+                   getxdcpath=getxdcpath.toString().replace(keyPath,"$("+key+")");
+                 }
+             }
+           }
+
+     }
+       var pkgroot="..";
+       for (var i = Pkg.name.split('.').length; i > 1; i--) {
+              pkgroot+="/..";
+          }
+
+      makefile.writeLine("\n# ROOT Directory");
+      makefile.writeLine("export ROOTDIR := "+pkgroot);
+
+      makefile.writeLine("\n# INCLUDE Directory");
+      makefile.writeLine("export INCDIR := "+getxdcpath+";$(ROOTDIR)");
+
+      makefile.writeLine("\n# Common Macros used in make");
+      makefile.writeLine("\nifndef RM");
+      makefile.writeLine("export RM = rm -f");
+      makefile.writeLine("endif");
+
+      makefile.writeLine("\nifndef CP");
+      makefile.writeLine("export CP = cp -p");
+      makefile.writeLine("endif");
+
+      makefile.writeLine("\nexport MKDIR = mkdir -p");
+
+      makefile.writeLine("\nifndef RMDIR");
+      makefile.writeLine("export RMDIR = rm -rf");
+      makefile.writeLine("endif");
+
+      makefile.writeLine("\nifndef SED");
+      makefile.writeLine("export SED = sed");
+      makefile.writeLine("endif");
+
+      makefile.writeLine("\nifndef MAKE");
+      makefile.writeLine("export MAKE = make");
+      makefile.writeLine("endif");
+
+      makefile.writeLine("\n# PHONY Targets");
+      makefile.writeLine(".PHONY: all clean cleanall ");
+
+      makefile.writeLine("\n# FORCE Targets");
+      makefile.writeLine("FORCE: ");
+
+      makefile.writeLine("\n# all rule");
+      makefile.writeLine("all: .executables");
+      makefile.writeLine(".executables: .libraries");
+      makefile.writeLine(".libraries:");
+
+      makefile.writeLine("\n# Clean Rule");
+      makefile.writeLine("clean:: clean_package");
+      makefile.writeLine("# Clean Top Level Object Directory ");
+      makefile.writeLine("clean_package :\n\t$(RMDIR) $(LIBDIR)/*/");
+      makefile.writeLine("\t$(RMDIR) package/cfg");
+   }
+   else
+   {
+     try{
+          makefile = fileModule.open("makefile", "a");
+         } catch (ex)
+         {
+           print("makefile cannot be written to. Please check Writing Permissions.");
+           java.lang.System.exit(1);
+         }
+
+    }
+
+ return makefile;
+}
+
+function createLibMake(device, objExtDir, makelibname,targetname, objectPath)
+{
+   var tooldir;
+   var cmdprefix;
+   var targetDir;
+   var stringname=String(targetname).replace("(xdc.bld.ITarget.Module)","");
+
+   switch(stringname)
+   {
+    case String(C66LE):
+      tooldir="C6X_GEN_INSTALL_PATH";
+      cmdprefix="";
+      targetDir="c66/release";
+      targetname=C66LE;
+      break;
+    case String(C66BE):
+      tooldir="C6X_GEN_INSTALL_PATH";
+      cmdprefix="";
+      targetDir="c66/release";
+      targetname=C66BE;
+      break;
+    case String(A15LE):
+      tooldir="TOOLCHAIN_PATH_A15";
+      cmdprefix="CROSS_TOOL_PRFX";
+      targetDir="a15/release";
+      targetname=A15LE;
+      break;
+    case String(A9LE):
+      tooldir="TOOLCHAIN_PATH_A9";
+      cmdprefix="CROSS_TOOL_PRFX";
+      targetDir="a9/release";
+      targetname=A9LE;
+      break;
+    case String(A8LE):
+      tooldir="TOOLCHAIN_PATH_A8";
+      cmdprefix="CROSS_TOOL_PRFX";
+      targetDir="a8/release";
+      targetname=A8LE;
+      break;
+    case String(M4LE):
+      tooldir="TOOLCHAIN_PATH_M4";
+      cmdprefix="";
+      targetDir="m4/release";
+      targetname=M4LE;
+      break;
+   }
+
+    var fileModule = xdc.module('xdc.services.io.File');
+    try{
+     var dstFile = new java.io.File(makelibname);
+     dstFile.getParentFile().mkdirs();
+     libmakefile = fileModule.open(makelibname, "w");
+     /* Add to Archive list */
+    } catch (ex)
+    {
+     print(makelibname+" cannot be written to. Please check Writing Permissions.");
+     java.lang.System.exit(1);
+    }
+    libmakefile.writeLine("#*******************************************************************************");
+    libmakefile.writeLine("#* FILE PURPOSE: Lower level makefile for Creating Component Libraries");
+    libmakefile.writeLine("#*******************************************************************************");
+    libmakefile.writeLine("#* FILE NAME: "+makelibname);
+    libmakefile.writeLine("#*");
+    libmakefile.writeLine("#* DESCRIPTION: Defines Source Files, Compilers flags and build rules");
+    libmakefile.writeLine("#*");
+    libmakefile.writeLine("#*");
+    libmakefile.writeLine("#*******************************************************************************");
+    libmakefile.writeLine("#");
+    libmakefile.writeLine("");
+    libmakefile.writeLine("#");
+    libmakefile.writeLine("# Macro definitions referenced below");
+    libmakefile.writeLine("#");
+    libmakefile.writeLine("empty =");
+    libmakefile.writeLine("space =$(empty) $(empty)");
+
+    if ((targetname.name == "A15F") || (targetname.name == "A9F") || (targetname.name == "A8F"))
+    {
+
+        if(stringname.match("gnu.targets"))
+        {
+            libmakefile.writeLine("CC = $("+tooldir+")/bin/$("+cmdprefix+")gcc");
+            libmakefile.writeLine("AC = $("+tooldir+")/bin/$("+cmdprefix+")as");
+            libmakefile.writeLine("ARIN = $("+tooldir+")/bin/$("+cmdprefix+")ar");
+            libmakefile.writeLine("LD = $("+tooldir+")/bin/$("+cmdprefix+")gcc");
+        }
+        else
+        {
+            print("Error: Non-GNU targets are not currently supported ");
+            java.lang.System.exit(1);
+
+        }
+
+        libmakefile.writeLine("INCS = -I. -I$(strip $(subst ;, -I,$(subst $(space),\\$(space),$(INCDIR)))) -I$("+tooldir+")/include");
+        libmakefile.writeLine("OBJEXT = o"+targetname.suffix);
+        libmakefile.writeLine("AOBJEXT = s"+targetname.suffix);
+        libmakefile.writeLine("CFLAGS_INTERNAL = " +targetname.ccOpts.prefix+" "+targetname.cc.opts);
+        libmakefile.writeLine("ASFLAGS_INTERNAL = " +targetname.asmOpts.prefix+" "+targetname.asm.opts);
+        libmakefile.writeLine("ARFLAGS_INTERNAL = " +targetname.ar.opts);
+        libmakefile.writeLine("LNKFLAGS_INTERNAL = " +targetname.lnk.opts);
+        libmakefile.writeLine("INTERNALDEFS = -MD -MF $@.dep");
+        libmakefile.writeLine("INTERNALLINKDEFS = -o $@ -m $@.map");  /* TBD */
+        libmakefile.writeLine("OBJDIR =  ./obj/obj_" +targetname.suffix +"/" + device.toString() + "/" + targetDir +"/obj" + "/" + objExtDir);
+
+    }
+    else
+    {
+
+        if(stringname.match("ti.targets"))
+        {
+
+            var rtslibtemp = targetname.lnkOpts.suffix.toString().split("/");
+            var rtslib;
+            for(n=0;n<rtslibtemp.length;n++)
+            {
+                if(rtslibtemp[n].match(".lib"))
+                {
+                    rtslib=rtslibtemp[n];
+                }
+            }
+
+            libmakefile.writeLine("CC = $("+tooldir+")/bin/"+targetname.cc.cmd);
+            libmakefile.writeLine("AC = $("+tooldir+")/bin/"+targetname.asm.cmd);
+            libmakefile.writeLine("ARIN = $("+tooldir+")/bin/"+targetname.ar.cmd);
+            libmakefile.writeLine("LD = $("+tooldir+")/bin/"+targetname.lnk.cmd);
+            libmakefile.writeLine("RTSLIB = -l $("+tooldir+")/lib/"+rtslib);
+        }
+        else
+        {
+            print("Error: Non-TI targets are not currently supported ");
+            java.lang.System.exit(1);
+
+        }
+
+        libmakefile.writeLine("INCS = -I. -I$(strip $(subst ;, -I,$(subst $(space),\\$(space),$(INCDIR)))) -I$("+tooldir+")/include");
+        libmakefile.writeLine("OBJEXT = o"+targetname.suffix);
+        libmakefile.writeLine("AOBJEXT = s"+targetname.suffix);
+        libmakefile.writeLine("CFLAGS_INTERNAL = " +targetname.ccOpts.prefix+" "+targetname.cc.opts);
+        libmakefile.writeLine("ASFLAGS_INTERNAL = " +targetname.asmOpts.prefix+" "+targetname.asm.opts);
+        libmakefile.writeLine("ARFLAGS_INTERNAL = " +targetname.ar.opts);
+        libmakefile.writeLine("LNKFLAGS_INTERNAL = " +targetname.lnk.opts);
+        /* libmakefile.writeLine("INTERNALDEFS = -D"+stringname.replace(/\./g,"_")+" -Dxdc_target_types__=ti/targets/std.h -DMAKEFILE_BUILD -eo.$(OBJEXT) -ea.$(AOBJEXT) -fr=$(@D) -fs=$(@D) -ppa -ppd=$@.dep");*/
+        libmakefile.writeLine("INTERNALDEFS = -D"+stringname.replace(/\./g,"_")+"  -DMAKEFILE_BUILD -eo.$(OBJEXT) -ea.$(AOBJEXT) -fr=$(@D) -fs=$(@D) -ppa -ppd=$@.dep");
+        libmakefile.writeLine("INTERNALLINKDEFS = -o $@ -m $@.map");
+        libmakefile.writeLine("OBJDIR =  ./obj/obj_" +targetname.suffix +"/" + device.toString() + "/" + targetDir +"/obj" + "/" + objExtDir);
+    }
+
+ return libmakefile;
+
+}
+
+function makeAddObjects(srcString, makefilename, srcfiles, flags,fileExt, targetName, objDir)
+{
+  var  sourcestring = (srcString + fileExt).toString().toUpperCase();
+  var  compileflagstring = sourcestring + "FLAGS";
+  var  objectliststring = sourcestring + "OBJS";
+  /* List all the source files */
+  makefilename.writeLine("\n#List the "+srcString+" Files");
+  makefilename.writeLine(sourcestring + "= \\");
+  for(var i=0;i<srcfiles.length-1;i++)
+  {
+    makefilename.writeLine("    "+srcfiles[i]+"\\");
+  }
+    makefilename.writeLine("    "+srcfiles[i]+"\n");
+
+ /* Flags for the source files */
+ makefilename.writeLine("# FLAGS for the "+srcString+" Files");
+ var compileflags="";
+ if(fileExt == "asm" && flags.aopts != undefined)
+ {
+   compileflags+=" "+flags.aopts;
+ }
+ else if((fileExt == "c" || fileExt == "sa")&& flags.copts != undefined)
+ {
+   compileflags+=" "+flags.copts;
+ }
+
+ if(flags.incs != undefined)
+ {
+   compileflags+=" "+flags.incs;
+ }
+
+
+ makefilename.writeLine(compileflagstring+" = "+compileflags +" \n");
+ makefilename.writeLine("# Make Rule for the "+srcString+" Files");
+
+ makefilename.writeLine(objectliststring +" = $(patsubst %."+fileExt+", "+objDir+"/%.$(OBJEXT), $(" + sourcestring + "))");
+ makefilename.writeLine("\n$("+objectliststring+"): "+objDir+"/%.$(OBJEXT): %."+fileExt);
+ if(fileExt == "c")
+ {
+   makefilename.writeLine("\t-@echo cl"+targetName.suffix +" $< ...");
+ }
+ else
+ {
+   makefilename.writeLine("\t-@echo asm"+targetName.suffix +" $< ...");
+ }
+ makefilename.writeLine("\tif [ ! -d $(@D) ]; then $(MKDIR) $(@D) ; fi;");
+
+ if(fileExt == "c")
+ {
+   if ((targetName.name == "A15F") || (targetName.name == "A9F") || (targetName.name == "A8F"))
+   {
+    makefilename.writeLine("\t$(RM) $@.dep");
+    makefilename.writeLine("\t$(CC) $(CFLAGS_INTERNAL) $("+compileflagstring+") $(INTERNALDEFS) $(INCS) $< -o $@");
+   /*
+    TBD
+   */
+   }
+   else
+   {
+    makefilename.writeLine("\t$(RM) $@.dep");
+    makefilename.writeLine("\t$(CC) $(CFLAGS_INTERNAL) $("+compileflagstring+") $(INTERNALDEFS) $(INCS) -fc $< ");
+    makefilename.writeLine("\t-@$(CP) $@.dep $@.pp; \\");
+    makefilename.writeLine("         $(SED) -e 's/#.*//' -e 's/^[^:]*: *//' -e 's/ *\\\\$$//' \\");
+    makefilename.writeLine("             -e '/^$$/ d' -e 's/$$/ :/' < $@.pp >> $@.dep; \\");
+    makefilename.writeLine("         $(RM) $@.pp ");
+   }
+ }
+ else if(fileExt == "asm")
+ {
+   makefilename.writeLine("\t$(AC) $(ASFLAGS_INTERNAL) $("+compileflagstring+") $(INTERNALDEFS) $(INCS) -fa $< ");
+ }
+ else if(fileExt == "sa")
+ {
+   makefilename.writeLine("\t$(AC) $(ASFLAGS_INTERNAL) $("+compileflagstring+") $(INTERNALDEFS) $(INCS) $< ");
+ }
+
+ makefilename.writeLine("\n#Create Empty rule for dependency");
+ makefilename.writeLine("$("+objectliststring+"):"+makefilename.$private.fd);
+ makefilename.writeLine(makefilename.$private.fd+":");
+ makefilename.writeLine("\n#Include Depedency for "+srcString+" Files");
+ makefilename.writeLine("ifneq (clean,$(MAKECMDGOALS))");
+ makefilename.writeLine(" -include $("+objectliststring+":%.$(OBJEXT)=%.$(OBJEXT).dep)");
+ makefilename.writeLine("endif");
+
+}
+
+/**************************************************************************
+ * FUNCTION NAME : buildLibrary
+ **************************************************************************
+ * DESCRIPTION   :
+ *  Utility function which will build a specific library
+ **************************************************************************/
+var makefilelocal;
+function buildLibrary (socName, isDmaSoc, isSoc, libOptions, libName, target, libFiles)
+{
+    var targetDir;
+    var objExtDir;
+
+    if (target.name == "A15F")
+    {
+        targetDir = "a15/release";
+    }
+    else if (target.name == "A9F")
+    {
+        targetDir = "a9/release";
+    }
+    else if (target.name == "A8F")
+    {
+        targetDir = "a8/release";
+    }
+    else if (target.name == "M4")
+    {
+        targetDir = "m4/release";
+    }
+    else
+    {
+        targetDir = "c66/release";
+    }
+
+    /* Derive the operating system and soc names */
+    if (isDmaSoc == "true") {
+        var libNameExp = libName+".dma";
+        targetDir = socName+"/"+targetDir;
+        objExtDir ="dma";
+    }
+    else if (isSoc == "true") {
+        var libNameExp = libName;
+        targetDir = socName+"/"+targetDir;
+        objExtDir = "soc";
+    }
+    else  {
+        var libNameExp = libName;
+        objExtDir = "all";
+    }
+
+    var lldFullLibraryPath = "./lib/" + targetDir +"/" + libNameExp;
+    var lldFullBuildPath = "./build/" + targetDir +"/" + libNameExp;
+    var lldFullLibraryPathMake = "$(LIBDIR)/" + targetDir +"/" + libNameExp;
+
+    /* Create Main make file in the root of package folder */
+    makefilelocal = createMake(makefilelocal);
+
+    /* Write the rule to make library in main makefile */
+    lib = lldFullBuildPath+".a"+target.suffix;
+    libMake = lldFullLibraryPathMake+".a"+target.suffix;
+    var objectPath= "./package/"+lldFullBuildPath;
+
+    makefilelocal.writeLine("\n\n# Make rule to create "+libMake+" library");
+    makefilelocal.writeLine(".libraries: "+ libMake);
+    makefilelocal.writeLine(libMake+": FORCE\n\t$(MAKE) -f "+lib+".mk $@");
+
+    /* Create Library make file in the lib folder */
+    var makefilelib= createLibMake(socName, objExtDir, lib+".mk",target,objectPath);
+
+    /* Rule to clean library in main makefile */
+    makefilelocal.writeLine("# Rule to clean "+libMake+" library");
+    makefilelocal.writeLine("clean ::\n\t$(RM) "+ libMake);
+    librule="\n\n"+libMake+" :";
+
+    /* Add files to be compiled */
+    /* Separate out the C and assembly files */
+    var cfiles= new Array();
+    var afiles= new Array();
+    var safiles= new Array();
+    for each(var srcFile in libFiles)
+    {
+        var srcFile=String(srcFile);
+        var dot = srcFile.lastIndexOf(".");
+        var extension = srcFile.substr(dot,srcFile.length);
+        if(extension == ".c")
+        {
+            cfiles.push(srcFile);
+        }
+        else if(extension == ".sa")
+        {
+            safiles.push(srcFile);
+        }
+        else if(extension == ".asm")
+        {
+            afiles.push(srcFile);
+        }
+        else
+        {
+            print("ERROR: Unsupported file extension");
+            java.lang.System.exit(1);
+        }
+    }
+    if(cfiles.length > 0)
+    {
+      makeAddObjects("COMMONSRC",makefilelib,cfiles,libOptions,"c",target, "$(OBJDIR)");
+      librule += " $(COMMONSRCCOBJS)";
+    }
+    if(afiles.length > 0)
+    {
+      makeAddObjects("COMMONSRC",makefilelib,afiles,libOptions,"asm",target, "$(OBJDIR)");
+      librule += " $(COMMONSRCASMOBJS)";
+    }
+    if(safiles.length > 0)
+    {
+      makeAddObjects("COMMONSRC",makefilelib,safiles,libOptions,"sa",target, "$(OBJDIR)");
+      librule += " $(COMMONSRCSAOBJS)";
+    }
+
+    makefilelib.writeLine(librule);
+    makefilelib.writeLine("\t@echo archiving $? into $@ ...");
+    makefilelib.writeLine("\tif [ ! -d $(LIBDIR)/"+targetDir+" ]; then $(MKDIR) $(LIBDIR)/"+targetDir+" ; fi;");
+       makefilelib.writeLine("\t$(ARIN) $(ARFLAGS_INTERNAL) $@ $?");
+       makefilelib.close();
+
+    /* Create the Epilogue; which executes after all the builds are completed.
+     * This is used to generate the benchmark information for the built library.
+     * Also add the benchmarking information file to the package. */
+    /* Put the temp file in object directory since javascript doesn't have a built in tmpname, 
+     * and don't want --jobs=# with # > 1 to result in collisions */
+    var libFullName = lldFullLibraryPath + ".a" + target.suffix;
+    var tempFile = libFullName + ".xml";
+    Pkg.makeEpilogue += ".libraries: " + libFullName +  "_size.txt\n";
+    Pkg.makeEpilogue += libFullName +  "_size.txt: " + libFullName + "\n";
+    if ( java.lang.String(target.name).contains('66') )
+    {    
+        Pkg.makeEpilogue += "\n\t $(C6X_GEN_INSTALL_PATH)/bin/ofd6x -x " + libFullName + " > " + tempFile;
+        Pkg.makeEpilogue += "\n\t $(SECTTI) " + tempFile + " > " + libFullName +  "_size.txt";
+        Pkg.makeEpilogue += "\n\t $(RM) " + tempFile + "\n\n";
+    }   
+    else if (target.name == "M4")
+    {
+        Pkg.makeEpilogue += "\n\t $(TOOLCHAIN_PATH_M4)/bin/armofd -x " + libFullName + " > " + tempFile;
+        Pkg.makeEpilogue += "\n\t $(SECTTI) " + tempFile + " > " + libFullName +  "_size.txt";
+        Pkg.makeEpilogue += "\n\t $(RM) " + tempFile + "\n\n";
+    }
+    else
+    {
+        Pkg.makeEpilogue += "\n\t $(TOOLCHAIN_PATH_A15)/bin/$(CROSS_TOOL_PRFX)size " + libFullName + " > " + libFullName + "_size.txt";
+    }                
+    Pkg.otherFiles[Pkg.otherFiles.length++] = lldFullLibraryPath + ".a" + target.suffix + "_size.txt";
+    Pkg.otherFiles[Pkg.otherFiles.length++] = lldFullBuildPath + ".a" + target.suffix + ".mk";
+    Pkg.otherFiles[Pkg.otherFiles.length++] = lldFullLibraryPath + ".a" + target.suffix;
+
+    /* We need to clean after ourselves; extend the 'clean' target to take care of this. */
+    Pkg.makeEpilogue += "\nclean::\n";
+    Pkg.makeEpilogue += "\t$(RM) " + lldFullBuildPath + ".a" + target.suffix + "_size.txt\n";
+    Pkg.makeEpilogue += "\t$(RMDIR) " + "$(LIBDIR)/" + targetDir + "/ \n\n";
+
+    return lib;
+}
diff --git a/packages/ti/utils/trace/build/makefile_trace.mk b/packages/ti/utils/trace/build/makefile_trace.mk
new file mode 100644 (file)
index 0000000..cbf75ed
--- /dev/null
@@ -0,0 +1,60 @@
+g
+# Copyright (c) 2019, Texas Instruments Incorporated
+# 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 Texas Instruments Incorporated nor the names of
+#    its contributors may be used to endorse or promote products derived
+#    from this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
+# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
+# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
+# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#
+
+include $(PDK_INSTALL_PATH)/ti/build/Rules.make
+
+MODULE_NAME = trace
+
+SRCDIR = . src
+INCDIR = . src
+
+# Common source files across all platforms and cores
+SRCS_COMMON =
+#SRCS_COMMON += trace.c
+
+
+# List all the external components/interfaces, whose interface header files
+#  need to be included for this component
+INCLUDE_EXTERNAL_INTERFACES = pdk
+
+PACKAGE_SRCS_COMMON = makefile trace_component.mk trace.h \
+                      build/makefile_trace.mk src/trace.c \
+                      
+# Include common make files
+ifeq ($(MAKERULEDIR), )
+#Makerule path not defined, define this and assume relative path from ROOTDIR
+  MAKERULEDIR := $(ROOTDIR)/ti/build/makerules
+  export MAKERULEDIR
+endif
+include $(MAKERULEDIR)/common.mk
+
+# Nothing beyond this point
diff --git a/packages/ti/utils/trace/config.bld b/packages/ti/utils/trace/config.bld
new file mode 100644 (file)
index 0000000..fd97aa1
--- /dev/null
@@ -0,0 +1,303 @@
+/******************************************************************************
+ * FILE PURPOSE: Build configuration Script for the Utilities Library
+ ******************************************************************************
+ * FILE NAME: config.bld
+ *
+ * DESCRIPTION:
+ *  This file contains the build configuration script for the Utilities Library
+ *  and is responsible for configuration of the paths for the various tools
+ *  required to build the utility.
+ *
+ * Copyright (C) 2019, Texas Instruments, Inc.
+ *****************************************************************************/
+
+/* Get the Tools Base directory from the Environment Variable. */
+var c66ToolsBaseDir = java.lang.System.getenv("C6X_GEN_INSTALL_PATH");
+var m4ToolsBaseDir = java.lang.System.getenv("TOOLCHAIN_PATH_M4");
+var a15ToolsBaseDir = java.lang.System.getenv("TOOLCHAIN_PATH_A15");
+var a9ToolsBaseDir  = java.lang.System.getenv("TOOLCHAIN_PATH_A9");
+var a8ToolsBaseDir  = java.lang.System.getenv("TOOLCHAIN_PATH_A8");
+
+/* Get the extended debug flags for C66x, 
+ * did not change the name for backwards compatibilty */
+var extDbgFlags = java.lang.System.getenv("EXTDBGFLAGS");
+
+/* Get the extended debug flags for A15 */
+var extDbgFlags_a15 = java.lang.System.getenv("EXTDBGFLAGS_A15");
+
+/* Get the extended debug flags for A8 */
+var extDbgFlags_a8 = java.lang.System.getenv("EXTDBGFLAGS_A8");
+
+/* Get the extended debug flags for A9 */
+var extDbgFlags_a9 = java.lang.System.getenv("EXTDBGFLAGS_A9");
+
+/* Get the extended debug flags for M4 */
+var extDbgFlags_m4 = java.lang.System.getenv("EXTDBGFLAGS_M4");
+
+/* Get the base directory for the uart Socket Driver Package */
+var driverPath = new java.io.File(".//").getPath();
+
+/* Include Path */
+var lldIncludePath = " -I" + driverPath + "/src" + " -I" + driverPath;
+
+/* Configure Release Version Information */
+var driverReleaseVersion = (""+Pkg.version.replace(/\s/g, "")).split(',');
+
+/* Print the Compiler Options */
+var pOpts = 1;
+
+/* C66 ELF compiler configuration for Little Endian Mode. */
+var C66LE          = xdc.useModule('ti.targets.elf.C66');
+C66LE.rootDir       = c66ToolsBaseDir;
+C66LE.ccOpts.prefix  = "-mo -q -k -eo.o " + "--entry_parm=address --exit_hook=ti_utils_exit --exit_parm=address --entry_hook=ti_utils_entry -g -D_ENABLE_BM";
+if(extDbgFlags)     
+    C66LE.ccOpts.prefix = C66LE.ccOpts.prefix + " " + extDbgFlags; 
+
+/* C66 ELF compiler configuration for Big Endian Mode. */
+var C66BE          = xdc.useModule('ti.targets.elf.C66_big_endian');
+C66BE.rootDir       = c66ToolsBaseDir;
+C66BE.ccOpts.prefix  = "-mo -q -k -eo.o -DBIGENDIAN " + "--entry_parm=address --exit_hook=ti_utils_exit --exit_parm=address --entry_hook=ti_utils_entry -g -D_ENABLE_BM";
+if(extDbgFlags)     
+    C66BE.ccOpts.prefix = C66BE.ccOpts.prefix + " " + extDbgFlags;
+
+/* ARMv7 A15 compiler configuration */
+var A15LE            = xdc.useModule('gnu.targets.arm.A15F');
+A15LE.rootDir        = a15ToolsBaseDir;
+A15LE.ccOpts.prefix  = "-mno-unaligned-access -c -mtune=cortex-a15 -marm -DDRA7xx -g -gdwarf-3 -gstrict-dwarf -Wall -D__ARMv7 -D_LITTLE_ENDIAN=1 " + "-finstrument-functions -gdwarf-3 -g -D_ENABLE_BM";
+if(extDbgFlags_a15)     
+    A15LE.ccOpts.prefix = A15LE.ccOpts.prefix + " " + extDbgFlags_a15; 
+    
+/* ARMv7 A9 compiler configuration */
+var A9LE            = xdc.useModule('gnu.targets.arm.A9F');
+A9LE.rootDir        = a9ToolsBaseDir;
+A9LE.ccOpts.prefix  = "-mno-unaligned-access -c -mtune=cortex-a9 -marm -DDRA7xx -g -gdwarf-3 -gstrict-dwarf -Wall -D__ARMv7 -D_LITTLE_ENDIAN=1 " + "-finstrument-functions -gdwarf-3 -g -D_ENABLE_BM";
+if(extDbgFlags_a9)     
+    A9LE.ccOpts.prefix = A9LE.ccOpts.prefix + " " + extDbgFlags_a9; 
+
+/* ARMv7 A8 compiler configuration */
+var A8LE            = xdc.useModule('gnu.targets.arm.A8F');
+A8LE.rootDir        = a8ToolsBaseDir;
+A8LE.ccOpts.prefix  = "-mno-unaligned-access -c -mtune=cortex-a8 -marm -DDRA7xx -g -gdwarf-3 -gstrict-dwarf -Wall -D__ARMv7 -D_LITTLE_ENDIAN=1 " + "-finstrument-functions -gdwarf-3 -g -D_ENABLE_BM";
+if(extDbgFlags_a8)     
+    A8LE.ccOpts.prefix = A8LE.ccOpts.prefix + " " + extDbgFlags_a8; 
+
+/* M4 ELF compiler configuration for Little Endian Mode. */
+var M4LE            = xdc.useModule('ti.targets.arm.elf.M4');
+M4LE.rootDir        = m4ToolsBaseDir;
+M4LE.ccOpts.prefix  = "-qq -pdsw255 -DMAKEFILE_BUILD " + "--entry_parm=address --exit_hook=ti_utils_exit --exit_parm=address --entry_hook=ti_utils_entry -g -D_ENABLE_BM";
+if(extDbgFlags_m4)
+    M4LE.ccOpts.prefix = M4LE.ccOpts.prefix + " " + extDbgFlags_m4; 
+
+/* Create the SoC List  */
+var socs = { 
+    /* device independent libraries */
+    all :
+    {
+        /* Build this library */
+        build: "true",
+        /* SoC lib enabled */
+        socDevLib: "false",
+        /* Library options */
+        copts: "",
+        /* target lists, kept blank now, would be updated based on argument lists */
+        targets: []
+    },
+    am335x :
+    {
+        /* this variable would be reinitialized to true, if XDCARGS contains am335x */
+        build: "false",
+        /* SoC lib enabled */
+        socDevLib: "false",
+        /* Library options */
+        copts: " -DSOC_AM335x",
+        /* target list */
+        targets: [ A8LE ]
+    },
+    am437x :
+    {
+        /* this variable would be reinitialized to true, if XDCARGS contains am437x */
+        build: "false",       
+        /* SoC lib enabled */
+        socDevLib: "false",
+        /* Library options */
+        copts: " -DSOC_AM437x",
+        /* target list */
+        targets: [ A9LE ]
+   },
+   am572x :
+    {
+        /* this variable would be reinitialized to true, if XDCARGS contains am572x */
+        build: "false", 
+       /* SoC lib enabled */
+       socDevLib: "false",
+       /* Library options */
+       copts: " -DSOC_AM572x",
+ &nbs