[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Xen-devel] PATCH [base vtpm and libxl patches 1/6] Upgrade vtpmd from 0.5.1 to 0.7.4



Update vtpmd from 0.5.1 to 0.7.4. Also adds checks for cmake
and gmp to the configure script if vtpm is enabled.

Signed off by Matthew Fioravante matthew.fioravante@xxxxxxxxxx

---
Changed since previous:
* added checks for libgmp and gmp.h if vtpm is enabled
* small documentation updates

diff --git a/tools/configure.ac b/tools/configure.ac
--- a/tools/configure.ac
+++ b/tools/configure.ac
@@ -72,6 +72,7 @@ AC_ARG_VAR([AS86], [Path to as86 tool])
 AC_ARG_VAR([LD86], [Path to ld86 tool])
 AC_ARG_VAR([BCC], [Path to bcc tool])
 AC_ARG_VAR([IASL], [Path to iasl tool])
+AC_ARG_VAR([CMAKE], [Path to cmake binary])
 
 # Checks for programs.
 AC_PROG_CC
@@ -101,6 +102,9 @@ AS_IF([echo "$PYTHON" | grep -q "^/"], [
 AX_PATH_PROG_OR_FAIL([PYTHONPATH], [$PYTHON])
 AX_CHECK_PYTHON_VERSION([2], [3])
  AX_CHECK_PYTHON_DEVEL()
+AS_IF([test "x$vtpm" = "xy"], [
+    AX_PATH_PROG_OR_FAIL([CMAKE], [cmake])
+])
 AX_PATH_PROG_OR_FAIL([XGETTEXT], [xgettext])
 dnl as86, ld86, bcc and iasl are only required when the host system is
x86*.
 dnl "host" here means the platform on which the hypervisor and tools is
@@ -142,6 +146,10 @@ AC_CHECK_LIB([yajl], [yajl_alloc], [],
 AC_CHECK_LIB([z], [deflateCopy], [], [AC_MSG_ERROR([Could not find zlib])])
 AC_CHECK_LIB([iconv], [libiconv_open], [libiconv="y"], [libiconv="n"])
 AC_SUBST(libiconv)
+AS_IF([test "x$vtpm" = "xy"], [
+    AC_CHECK_HEADER([gmp.h], [], [AC_MSG_ERROR([Could not find gmp.h])])
+    AC_CHECK_LIB([gmp], [__gmpz_init], [], [AC_MSG_ERROR([Could not
find libgmp])])
+])
 
 # Checks for header files.
 AC_CHECK_HEADERS([yajl/yajl_version.h])
diff --git a/tools/vtpm/Makefile b/tools/vtpm/Makefile
--- a/tools/vtpm/Makefile
+++ b/tools/vtpm/Makefile
@@ -1,19 +1,15 @@
 XEN_ROOT = $(CURDIR)/../..
+include $(XEN_ROOT)/tools/Rules.mk
 
-# Base definitions and rules
-include $(XEN_ROOT)/tools/vtpm/Rules.mk
-
-# Dir name for emulator (as dom0 tpm driver)
-TPM_EMULATOR_DIR = tpm_emulator
 # Dir name for vtpm instance
 VTPM_DIR = vtpm
-ORIG_DIR = orig
 
 # Emulator tarball name
-TPM_EMULATOR_NAME = tpm_emulator-0.5.1
+TPM_EMULATOR_URL = http://download.berlios.de/tpm-emulator
+TPM_EMULATOR_NAME = tpm_emulator-0.7.4
 TPM_EMULATOR_TARFILE = $(TPM_EMULATOR_NAME).tar.gz
 
-GMP_HEADER = /usr/include/gmp.h
+VTPM_PATCH = vtpm-0.7.4.patch
 
 .PHONY: all
 all: build
@@ -23,52 +19,39 @@ build: build_sub
 
 .PHONY: install
 install: build
-    $(MAKE) -C $(VTPM_DIR) install-recursive
+    $(INSTALL_PROG) -m 0755 $(VTPM_DIR)/build/tpmd/unix/tpmd
$(DESTDIR)$(BINDIR)/vtpmd
 
 .PHONY: clean
 clean:
-    @if [ -d $(TPM_EMULATOR_DIR) ]; \
-        then $(MAKE) -C $(TPM_EMULATOR_DIR) clean; \
-    fi
-    @if [ -d $(VTPM_DIR) ]; \
-        then $(MAKE) -C $(VTPM_DIR) clean; \
+    @-if [ -d $(VTPM_DIR)/build ]; \
+        then $(MAKE) -C $(VTPM_DIR)/build clean; \
     fi
 
-.PHONY: mrproper
-mrproper:
-    rm -f $(TPM_EMULATOR_TARFILE) tpm_emulator.patch.old vtpm.patch.old
-    rm -rf $(TPM_EMULATOR_DIR) $(VTPM_DIR) $(ORIG_DIR)
+.PHONY: distclean
+mdistclean:
+    rm -f $(TPM_EMULATOR_TARFILE)
+    rm -rf $(VTPM_DIR) $(ORIG_DIR)
 
 # Download Swiss emulator
 $(TPM_EMULATOR_TARFILE):
-    wget http://download.berlios.de/tpm-emulator/$(TPM_EMULATOR_TARFILE)
+    wget $(TPM_EMULATOR_URL)/$(TPM_EMULATOR_TARFILE)
 
 # Create vtpm dirs
-$(VTPM_DIR)/tpmd/tpmd: $(TPM_EMULATOR_TARFILE) vtpm-0.5.1.patch
+$(VTPM_DIR)/build: $(TPM_EMULATOR_TARFILE) $(VTPM_PATCH)
     rm -rf $(VTPM_DIR)
     tar -xzf $(TPM_EMULATOR_TARFILE)
     mv $(TPM_EMULATOR_NAME) $(VTPM_DIR)
-
     set -e; cd $(VTPM_DIR); \
-    patch -p1 < ../vtpm-0.5.1.patch; \
-    patch -p1 < ../vtpm-0.5.1-LDLIBS.patch
+    patch -p1 < ../$(VTPM_PATCH);
+    mkdir $@
+    touch $@
 
-orig: $(TPM_EMULATOR_TARFILE)
-    mkdir $(ORIG_DIR);
-    set -e; cd $(ORIG_DIR); \
-    tar -xzf ../$(TPM_EMULATOR_TARFILE);
-
-updatepatches: clean orig
-    find $(VTPM_DIR) -name "*.orig" -print | xargs rm -f;
-    mv vtpm.patch vtpm.patch.old;
-    diff -uprN $(TPM_EMULATOR_DIR) $(VTPM_DIR) > vtpm.patch || true;
+$(VTPM_DIR)/build/Makefile: $(VTPM_DIR)/build
+    set -e; cd $(VTPM_DIR)/build; \
+    cmake -DCMAKE_INSTALL_PREFIX=${PREFIX} ..
+    touch $@
 
 .PHONY: build_sub
-build_sub: $(VTPM_DIR)/tpmd/tpmd
-    set -e; if [ -e $(GMP_HEADER) ]; then \
-        $(MAKE) -C $(VTPM_DIR) version; \
-        $(MAKE) -C $(VTPM_DIR) all-recursive; \
-    else \
-        echo "=== Unable to build VTPMs. libgmp could not be found."; \
-    fi
-
+build_sub: $(VTPM_DIR)/build/Makefile
+    set -e; \
+    cd $(VTPM_DIR)/build; $(MAKE) tpmd
diff --git a/tools/vtpm/README b/tools/vtpm/README
--- a/tools/vtpm/README
+++ b/tools/vtpm/README
@@ -1,27 +1,19 @@
 
 Directory Structure
 ===================
-tools/vtpm/tpm_emulator-0.2b.tar.gz    -> TPM Emulator downloaded at
build time that will
+tools/vtpm/tpm_emulator-0.7.4.tar.gz   -> TPM Emulator downloaded at
build time that will
                                           be patched and used for our vtpms
-tools/vtpm/vtpm.patch                  -> patch applied to tpm_emulator
to make vtpm
+tools/vtpm/vtpm-0.7.4.patch             -> patch applied to
tpm_emulator to make vtpm
 tools/vtpm/vtpm/                       -> (created on build)
tpm_emulator moved to ring 3,
                                           listens on a pair of fifos
for TPM commands,
                                           persistent state is sent via
named fifo to vtpm
                                             manager, which encrypts it
and protects it.
-tools/vtpm/tpm_emulator.patch          -> To allow for debugging and
testing on non-TPM
-                                          platforms, this patches the
emulator to allow
-                                          it to be inserted into the
dom0 kernel
-tools/vtpm/tpm_emulator-0.2            -> (created on build) directory
containing patched emulator
-
-Compile Flags
-===================
-VTPM_MULTI_VM                -> Defined (not finished): VTPMs run in
their own VMs
-                                Not Defined (default): VTPMs are processes
+tools/vtpm/tpm_emulator-0.7.4          -> (created on build) directory
containing patched emulator
 
 Requirements
 ============
 - xen-unstable
-- IBM frontend/backend vtpm driver patch
+- IBM frontend/backend vtpm driver patch for the linux kernel
 - vtpm_managerd
 - GNU MP Big number library (GMP)
 
@@ -42,4 +34,4 @@ vtpmd Flow (for vtpm_manager. vtpmd never run by default)
 
 tpm_emulator flow
 ==================
-Read documentation in tpm_emulator-0.2 directory
+Read documentation in tpm_emulator directory
diff --git a/tools/vtpm/Rules.mk b/tools/vtpm/Rules.mk
--- a/tools/vtpm/Rules.mk
+++ /dev/null
@@ -1,26 +0,0 @@
-# Base definitions and rules (XEN_ROOT must be defined in including
Makefile)
-include $(XEN_ROOT)/tools/Rules.mk
-
-#
-# Tool definitions
-#
-
-# General compiler flags
-CFLAGS   = -Werror -g3
-
-# Generic project files
-HDRS    = $(wildcard *.h)
-SRCS    = $(wildcard *.c)
-OBJS    = $(patsubst %.c,%.o,$(SRCS))
-
-# Generic (non-header) dependencies
-$(SRCS): Makefile $(XEN_ROOT)/tools/Rules.mk
$(XEN_ROOT)/tools/vtpm/Rules.mk
-
-$(OBJS): $(SRCS)
-
--include $(DEPS)
-
-BUILD_EMULATOR = y
-
-# Make sure these are just rules
-.PHONY : all build install clean
diff --git a/tools/vtpm/tpm_emulator.patch b/tools/vtpm/tpm_emulator.patch
--- a/tools/vtpm/tpm_emulator.patch
+++ /dev/null
@@ -1,1919 +0,0 @@
-diff -uprN orig/tpm_emulator-0.4/AUTHORS tpm_emulator/AUTHORS
---- orig/tpm_emulator-0.4/AUTHORS    2006-06-23 03:37:07.000000000 -0700
-+++ tpm_emulator/AUTHORS    2006-07-24 14:35:35.000000000 -0700
-@@ -1,2 +1,3 @@
- Mario Strasser <mast@xxxxxxx>
- Heiko Stamer <stamer@xxxxxxxx> [DAA]
-+INTEL Corp <> [Dropped to Ring3]
-diff -uprN orig/tpm_emulator-0.4/ChangeLog tpm_emulator/ChangeLog
---- orig/tpm_emulator-0.4/ChangeLog    2006-06-23 03:37:07.000000000 -0700
-+++ tpm_emulator/ChangeLog    2006-07-24 14:35:35.000000000 -0700
-@@ -1,3 +1,6 @@
-+????-??-?? Intel Corp
-+    * Moved module out of kernel to run as a ring 3 app
-+
- 2006-06-23  Mario Strasser <mast@xxxxxxx>
-     * tpm_startup.c: behaviour of ST_CLEAR and storage of
-         persistent data adapted
-diff -uprN orig/tpm_emulator-0.4/crypto/gmp_kernel_wrapper.c
tpm_emulator/crypto/gmp_kernel_wrapper.c
---- orig/tpm_emulator-0.4/crypto/gmp_kernel_wrapper.c    2006-06-23
03:37:07.000000000 -0700
-+++ tpm_emulator/crypto/gmp_kernel_wrapper.c    2006-07-24
14:35:35.000000000 -0700
-@@ -1,5 +1,6 @@
- /* Software-Based Trusted Platform Module (TPM) Emulator for Linux
-  * Copyright (C) 2004 Mario Strasser <mast@xxxxxxx>,
-+ * Copyright (C) 2005 INTEL Corp
-  *
-  * This module is free software; you can redistribute it and/or modify
-  * it under the terms of the GNU General Public License as published
-@@ -24,15 +25,10 @@ int __gmp_junk;
- void __attribute__ ((regparm(0))) __gmp_assert_fail(const char *filename,
-   int linenum, const char *expr)
- {
--  panic(KERN_CRIT TPM_MODULE_NAME "%s:%d: GNU MP assertion failed: %s\n",
-+  error("%s:%d: GNU MP assertion failed: %s\n",
-     filename, linenum, expr);
- }
-
--void __attribute__ ((regparm(0))) abort(void)
--{
--  panic(KERN_CRIT TPM_MODULE_NAME "GNU MP abort() was called\n");
--}
--
- /* overwrite GNU MP random functions (used by mpz/millerrabin.c) */
-
- void __attribute__ ((regparm(0))) gmp_randinit(gmp_randstate_t rstate,
-@@ -77,20 +73,19 @@ void __attribute__ ((regparm(0))) mpz_ur
-
- void __attribute__ ((regparm(0))) *kernel_allocate(size_t size)
- {
--  void *ret  = (void*)kmalloc(size, GFP_KERNEL);
--  if (!ret) panic(KERN_CRIT TPM_MODULE_NAME
--    "GMP: cannot allocate memory (size=%u)\n", size);
-+  void *ret  = (void*)malloc(size);
-+  if (!ret) error("GMP: cannot allocate memory (size=%Zu)\n", size);
-   return ret;
- }
-
- void __attribute__ ((regparm(0))) *kernel_reallocate(void *oldptr,
-   size_t old_size, size_t new_size)
- {
--  void *ret = (void*)kmalloc(new_size, GFP_KERNEL);
--  if (!ret) panic(KERN_CRIT TPM_MODULE_NAME "GMP: Cannot reallocate
memory "
--    "(old_size=%u new_size=%u)\n", old_size, new_size);
-+  void *ret = (void*)malloc(new_size);
-+  if (!ret) error("GMP: Cannot reallocate memory "
-+    "(old_size=%Zu new_size=%Zu)\n", old_size, new_size);
-   memcpy(ret, oldptr, old_size);
--  kfree(oldptr);
-+  free(oldptr);
-   return ret;
- }
-
-@@ -99,7 +94,7 @@ void __attribute__ ((regparm(0))) kernel
-   /* overwrite used memory */
-   if (blk_ptr != NULL) {
-     memset(blk_ptr, 0, blk_size);
--    kfree(blk_ptr);
-+    free(blk_ptr);
-   }
- }
-
-diff -uprN orig/tpm_emulator-0.4/crypto/rsa.c tpm_emulator/crypto/rsa.c
---- orig/tpm_emulator-0.4/crypto/rsa.c    2006-06-23 03:37:07.000000000
-0700
-+++ tpm_emulator/crypto/rsa.c    2006-07-24 14:35:35.000000000 -0700
-@@ -1,5 +1,6 @@
- /* Software-Based Trusted Platform Module (TPM) Emulator for Linux
-  * Copyright (C) 2004 Mario Strasser <mast@xxxxxxx>,
-+ * Copyright (C) 2005 INTEL Corp
-  *
-  * This module is free software; you can redistribute it and/or modify
-  * it under the terms of the GNU General Public License as published
-@@ -381,7 +382,7 @@ static int encode_message(int type, uint
-       msg[0] = 0x00;
-       get_random_bytes(&msg[1], SHA1_DIGEST_LENGTH);
-       sha1_init(&ctx);
--      sha1_update(&ctx, "TCPA", 4);
-+      sha1_update(&ctx, (uint8_t *) "TCPA", 4);
-       sha1_final(&ctx, &msg[1 + SHA1_DIGEST_LENGTH]);
-       memset(&msg[1 + 2 * SHA1_DIGEST_LENGTH], 0x00,
-         msg_len - data_len - 2 * SHA1_DIGEST_LENGTH - 2);
-@@ -429,7 +430,7 @@ static int decode_message(int type, uint
-       mask_generation(&msg[1], SHA1_DIGEST_LENGTH,
-         &msg[1 + SHA1_DIGEST_LENGTH], msg_len - SHA1_DIGEST_LENGTH - 1);
-       sha1_init(&ctx);
--      sha1_update(&ctx, "TCPA", 4);
-+      sha1_update(&ctx, (uint8_t *) "TCPA", 4);
-       sha1_final(&ctx, &msg[1]);
-       if (memcmp(&msg[1], &msg[1 + SHA1_DIGEST_LENGTH],
-           SHA1_DIGEST_LENGTH) != 0) return -1;
-diff -uprN orig/tpm_emulator-0.4/linux_module.c tpm_emulator/linux_module.c
---- orig/tpm_emulator-0.4/linux_module.c    2006-06-23
03:37:07.000000000 -0700
-+++ tpm_emulator/linux_module.c    1969-12-31 16:00:00.000000000 -0800
-@@ -1,195 +0,0 @@
--/* Software-Based Trusted Platform Module (TPM) Emulator for Linux
-- * Copyright (C) 2004 Mario Strasser <mast@xxxxxxx>,
-- *
-- * This module is free software; you can redistribute it and/or modify
-- * it under the terms of the GNU General Public License as published
-- * by the Free Software Foundation; either version 2 of the License,
-- * or (at your option) any later version. 
-- *
-- * This module is distributed in the hope that it will be useful,
-- * but WITHOUT ANY WARRANTY; without even the implied warranty of
-- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-- * GNU General Public License for more details.
-- *
-- * $Id: linux_module.c 91 2006-03-13 13:51:41Z mast $
-- */
--
--#include <linux/module.h>
--#include <linux/kernel.h>
--#include <linux/init.h>
--#include <linux/miscdevice.h>
--#include <linux/poll.h>
--#include "linux_module.h"
--#include "tpm/tpm_emulator.h"
--
--MODULE_LICENSE("GPL");
--MODULE_AUTHOR("Mario Strasser <mast@xxxxxxx>");
--MODULE_DESCRIPTION("Trusted Platform Module (TPM) Emulator");
--MODULE_SUPPORTED_DEVICE(TPM_DEVICE_NAME);
--
--/* module startup parameters */
--char *startup = "save";
--module_param(startup, charp, 0444);
--MODULE_PARM_DESC(startup, " Sets the startup mode of the TPM. "
--  "Possible values are 'clear', 'save' (default) and 'deactivated.");
--char *storage_file = "/var/tpm/tpm_emulator-1.2.0.2";
--module_param(storage_file, charp, 0644);
--MODULE_PARM_DESC(storage_file, " Sets the persistent-data storage "
--  "file of the TPM.");
--
--/* TPM lock */
--static struct semaphore tpm_mutex;
--
--/* TPM command response */
--static struct {
--  uint8_t *data;
--  uint32_t size;
--} tpm_response;
--
--/* module state */
--#define STATE_IS_OPEN 0
--static uint32_t module_state;
--static struct timespec old_time;
--
--static int tpm_open(struct inode *inode, struct file *file)
--{
--  debug("%s()", __FUNCTION__);
--  if (test_and_set_bit(STATE_IS_OPEN, (void*)&module_state)) return
-EBUSY;
--  return 0;
--}
--
--static int tpm_release(struct inode *inode, struct file *file)
--{
--  debug("%s()", __FUNCTION__);
--  clear_bit(STATE_IS_OPEN, (void*)&module_state);
--  down(&tpm_mutex);
--  if (tpm_response.data != NULL) {
--    kfree(tpm_response.data);
--    tpm_response.data = NULL;
--  }
--  up(&tpm_mutex);
--  return 0;
--}
--
--static ssize_t tpm_read(struct file *file, char *buf, size_t count,
loff_t *ppos)
--{
--  debug("%s(%d)", __FUNCTION__, count);
--  down(&tpm_mutex);
--  if (tpm_response.data != NULL) {
--    count = min(count, (size_t)tpm_response.size - (size_t)*ppos);
--    count -= copy_to_user(buf, &tpm_response.data[*ppos], count);
--    *ppos += count;
--    if ((size_t)tpm_response.size == (size_t)*ppos) {
--      kfree(tpm_response.data);
--      tpm_response.data = NULL;
--    }
--  } else {
--    count = 0;
--  }
--  up(&tpm_mutex);
--  return count;
--}
--
--static ssize_t tpm_write(struct file *file, const char *buf, size_t
count, loff_t *ppos)
--{
--  debug("%s(%d)", __FUNCTION__, count);
--  down(&tpm_mutex);
--  *ppos = 0;
--  if (tpm_response.data != NULL) kfree(tpm_response.data);
--  if (tpm_handle_command(buf, count, &tpm_response.data,
--                         &tpm_response.size) != 0) {
--    count = -EILSEQ;
--    tpm_response.data = NULL;
--  }
--  up(&tpm_mutex);
--  return count;
--}
--
--#define TPMIOC_CANCEL   _IO('T', 0x00)
--#define TPMIOC_TRANSMIT _IO('T', 0x01)
--
--static int tpm_ioctl(struct inode *inode, struct file *file, unsigned
int cmd, unsigned long arg)
--{
--  debug("%s(%d, %p)", __FUNCTION__, cmd, (char*)arg);
--  if (cmd == TPMIOC_TRANSMIT) {
--    uint32_t count = ntohl(*(uint32_t*)(arg + 2));
--    down(&tpm_mutex);
--    if (tpm_response.data != NULL) kfree(tpm_response.data);
--    if (tpm_handle_command((char*)arg, count, &tpm_response.data,
--                           &tpm_response.size) == 0) {
--      tpm_response.size -= copy_to_user((char*)arg, tpm_response.data,
--                            tpm_response.size);
--      kfree(tpm_response.data);
--      tpm_response.data = NULL;
--    } else {
--      tpm_response.size = 0;
--      tpm_response.data = NULL;
--    }
--    up(&tpm_mutex);
--    return tpm_response.size;
--  }
--  return -1;
--}
--
--struct file_operations fops = {
--  .owner   = THIS_MODULE,
--  .open    = tpm_open,
--  .release = tpm_release,
--  .read    = tpm_read,
--  .write   = tpm_write,
--  .ioctl   = tpm_ioctl,
--};
--
--static struct miscdevice tpm_dev = {
--  .minor      = TPM_DEVICE_MINOR,
--  .name       = TPM_DEVICE_NAME,
--  .fops       = &fops,
--};
--
--int __init init_tpm_module(void)
--{
--  int res = misc_register(&tpm_dev);
--  if (res != 0) {
--    error("misc_register() failed for minor %d\n", TPM_DEVICE_MINOR);
--    return res;
--  }
--  /* initialize variables */
--  sema_init(&tpm_mutex, 1);
--  module_state = 0;
--  tpm_response.data = NULL;
--  old_time = current_kernel_time();
--  /* initialize TPM emulator */
--  if (!strcmp(startup, "clear")) {
--    tpm_emulator_init(1);
--  } else if (!strcmp(startup, "save")) {
--    tpm_emulator_init(2);
--  } else if (!strcmp(startup, "deactivated")) {
--    tpm_emulator_init(3);
--  } else {
--    error("invalid startup mode '%s'; must be 'clear', "
--      "'save' (default) or 'deactivated", startup);
--    misc_deregister(&tpm_dev);
--    return -EINVAL;
--  }
--  return 0;
--}
--
--void __exit cleanup_tpm_module(void)
--{
--  tpm_emulator_shutdown();
--  misc_deregister(&tpm_dev);
--  if (tpm_response.data != NULL) kfree(tpm_response.data);
--}
--
--module_init(init_tpm_module);
--module_exit(cleanup_tpm_module);
--
--uint64_t tpm_get_ticks(void)
--{
--  struct timespec new_time = current_kernel_time();
--  uint64_t ticks = (uint64_t)(new_time.tv_sec - old_time.tv_sec) * 1000000
--                   + (new_time.tv_nsec - old_time.tv_nsec) / 1000;
--  old_time = new_time;
--  return (ticks > 0) ? ticks : 1;
--}
--
-diff -uprN orig/tpm_emulator-0.4/linux_module.h tpm_emulator/linux_module.h
---- orig/tpm_emulator-0.4/linux_module.h    2006-06-23
03:37:07.000000000 -0700
-+++ tpm_emulator/linux_module.h    2006-07-24 14:35:35.000000000 -0700
-@@ -1,5 +1,6 @@
- /* Software-Based Trusted Platform Module (TPM) Emulator for Linux
-  * Copyright (C) 2004 Mario Strasser <mast@xxxxxxx>,
-+ * Copyright (C) 2005 INTEL Corp
-  *
-  * This module is free software; you can redistribute it and/or modify
-  * it under the terms of the GNU General Public License as published
-@@ -17,54 +18,62 @@
- #ifndef _LINUX_MODULE_H_
- #define _LINUX_MODULE_H_
-
--#include <linux/version.h>
--#include <linux/kernel.h>
--#include <linux/slab.h>
-+#include <malloc.h>
-+#include <stdint.h>
-+#include <stdio.h>
-+#include <string.h>
- #include <linux/types.h>
--#include <linux/string.h>
--#include <linux/random.h>
--#include <linux/time.h>
--#include <asm/byteorder.h>
-
--/* module settings */
-+#include <endian.h>
-+#define __BYTEORDER_HAS_U64__
-+#ifdef LITTLE_ENDIAN
-+ #include <linux/byteorder/little_endian.h>
-+#else
-+ #include <linux/byteorder/big_endian.h>
-+#endif
-
-+/* module settings */
-+#define min(A,B) ((A)<(B)?(A):(B))
-+#ifndef STR
- #define STR(s) __STR__(s)
- #define __STR__(s) #s
-+#endif
- #include "tpm_version.h"
-
- #define TPM_DEVICE_MINOR  224
- #define TPM_DEVICE_NAME   "tpm"
- #define TPM_MODULE_NAME   "tpm_emulator"
-
--/* debug and log output functions */
--
- #ifdef DEBUG
--#define debug(fmt, ...) printk(KERN_DEBUG "%s %s:%d: Debug: " fmt "\n", \
--                        TPM_MODULE_NAME, __FILE__, __LINE__, ##
__VA_ARGS__)
-+#define debug(fmt, ...) printf("TPMD: %s:%d: Debug: " fmt "\n", \
-+                        __FILE__, __LINE__, ## __VA_ARGS__)
- #else
- #define debug(fmt, ...)
- #endif
--#define info(fmt, ...)  printk(KERN_INFO "%s %s:%d: Info: " fmt "\n", \
--                        TPM_MODULE_NAME, __FILE__, __LINE__, ##
__VA_ARGS__)
--#define error(fmt, ...) printk(KERN_ERR "%s %s:%d: Error: " fmt "\n", \
--                        TPM_MODULE_NAME, __FILE__, __LINE__, ##
__VA_ARGS__)
--#define alert(fmt, ...) printk(KERN_ALERT "%s %s:%d: Alert: " fmt "\n", \
--                        TPM_MODULE_NAME, __FILE__, __LINE__, ##
__VA_ARGS__)
-+#define info(fmt, ...)  printf("TPMD: %s:%d: Info: " fmt "\n", \
-+                        __FILE__, __LINE__, ## __VA_ARGS__)
-+#define error(fmt, ...) printf("TPMD: %s:%d: Error: " fmt "\n", \
-+                        __FILE__, __LINE__, ## __VA_ARGS__)
-+#define alert(fmt, ...) printf("TPMD: %s:%d: Alert: " fmt "\n", \
-+                        __FILE__, __LINE__, ## __VA_ARGS__)
-
- /* memory allocation */
-
- static inline void *tpm_malloc(size_t size)
- {
--  return kmalloc(size, GFP_KERNEL); 
-+  return malloc(size); 
- }
-
- static inline void tpm_free(const void *ptr)
- {
--  if (ptr != NULL) kfree(ptr);
-+  if (ptr != NULL) free( (void *) ptr);
- }
-
- /* random numbers */
-
-+//FIXME;
-+void get_random_bytes(void *buf, int nbytes);
-+
- static inline void tpm_get_random_bytes(void *buf, int nbytes)
- {
-   get_random_bytes(buf, nbytes);
-@@ -84,9 +93,9 @@ uint64_t tpm_get_ticks(void);
- #define CPU_TO_LE16(x) __cpu_to_le16(x)
-
- #define BE64_TO_CPU(x) __be64_to_cpu(x)
--#define LE64_TO_CPU(x) __be64_to_cpu(x)
-+#define LE64_TO_CPU(x) __le64_to_cpu(x)
- #define BE32_TO_CPU(x) __be32_to_cpu(x)
--#define LE32_TO_CPU(x) __be32_to_cpu(x)
-+#define LE32_TO_CPU(x) __le32_to_cpu(x)
- #define BE16_TO_CPU(x) __be16_to_cpu(x)
- #define LE16_TO_CPU(x) __le16_to_cpu(x)
-
-diff -uprN orig/tpm_emulator-0.4/Makefile tpm_emulator/Makefile
---- orig/tpm_emulator-0.4/Makefile    2006-06-23 03:37:07.000000000 -0700
-+++ tpm_emulator/Makefile    2006-07-24 14:35:35.000000000 -0700
-@@ -1,24 +1,40 @@
- # Software-Based Trusted Platform Module (TPM) Emulator for Linux
- # Copyright (C) 2004 Mario Strasser <mast@xxxxxxx>
-+# Copyright (C) 2006 INTEL Corp.
- #
- # $Id: Makefile 115 2006-06-23 10:36:44Z mast $
-
--# kernel settings
--KERNEL_RELEASE := $(shell uname -r)
--KERNEL_BUILD   := /lib/modules/$(KERNEL_RELEASE)/build
--MOD_SUBDIR     := misc
-+COMPILE_ARCH    ?= $(shell uname -m | sed -e s/i.86/x86_32/)
-
- # module settings
--MODULE_NAME    := tpm_emulator
-+BIN            := tpm_emulator
- VERSION_MAJOR  := 0
- VERSION_MINOR  := 4
- VERSION_BUILD  := $(shell date +"%s")
-
--# enable/disable DEBUG messages
--EXTRA_CFLAGS   += -Wall -DDEBUG -g 
-+# Installation program and options
-+INSTALL         = install
-+INSTALL_PROG    = $(INSTALL) -m0755
-+INSTALL_DIR     = $(INSTALL) -d -m0755
-+
-+# Xen tools installation directory
-+TOOLS_INSTALL_DIR = $(DESTDIR)/usr/bin
-+
-+CC      := gcc
-+CFLAGS  += -g -Wall $(INCLUDE) -DDEBUG
-+CFLAGS  += -I. -Itpm
-+
-+# Is the simulator running in it's own vm?
-+#CFLAGS += -DVTPM_MULTI_VM
-+
-+ifeq ($(COMPILE_ARCH),x86_64)
-+LIBDIR = lib64
-+else
-+LIBDIR = lib
-+endif
-
- # GNU MP configuration
--GMP_LIB        := /usr/lib/libgmp.a
-+GMP_LIB        := /usr/$(LIBDIR)/libgmp.a
- GMP_HEADER     := /usr/include/gmp.h
-
- # sources and objects
-@@ -27,38 +43,32 @@ DIRS           := . crypto tpm
- SRCS           := $(foreach dir, $(DIRS), $(wildcard $(src)/$(dir)/*.c))
- OBJS           := $(patsubst %.c, %.o, $(SRCS))
- SRCS           += $(foreach dir, $(DIRS), $(wildcard $(src)/$(dir)/*.h))
--DISTSRC        := ./README ./AUTHORS ./ChangeLog ./Makefile $(SRCS)
--DISTDIR        := tpm_emulator-$(VERSION_MAJOR).$(VERSION_MINOR)
-
--obj-m               := $(MODULE_NAME).o
--$(MODULE_NAME)-objs := $(patsubst $(src)/%.o, %.o, $(OBJS))
crypto/libgmp.a
-+obj-m               := $(BIN)
-+$(BIN)-objs := $(patsubst $(src)/%.o, %.o, $(OBJS)) crypto/libgmp.a
-
- EXTRA_CFLAGS   += -I$(src) -I$(src)/crypto -I$(src)/tpm
-
- # do not print "Entering directory ..."
- MAKEFLAGS      += --no-print-directory
-
--all:    $(src)/crypto/gmp.h $(src)/crypto/libgmp.a version
--    @$(MAKE) -C $(KERNEL_BUILD) M=$(CURDIR) modules
-+all: $(BIN)
-
--install:
--    @$(MAKE) -C $(KERNEL_BUILD) M=$(CURDIR) modules_install
--    test -d /var/tpm || mkdir /var/tpm
--    test -c /dev/tpm || mknod /dev/tpm c 10 224
--    chmod 666 /dev/tpm
--    depmod -a
-+$(BIN):    $(src)/crypto/gmp.h $(src)/crypto/libgmp.a version $(SRCS)
$(OBJS)
-+    $(CC) $(CFLAGS) $(OBJS) $(src)/crypto/libgmp.a -o $(BIN)
-+
-+%.o: %.c
-+    $(CC) $(CFLAGS) -c $< -o $@
-+
-+install: $(BIN)
-+    $(INSTALL_PROG) $(BIN) $(TOOLS_INSTALL_DIR)
-+    @if [ ! -d "/var/tpm" ]; then mkdir /var/tpm; fi
-
- clean:
--    @$(MAKE) -C $(KERNEL_BUILD) M=$(CURDIR) clean
--    rm -f $(src)/crypto/gmp.h $(src)/crypto/libgmp.a
-+    rm -f $(src)/crypto/gmp.h $(src)/crypto/libgmp.a $(OBJS)
-
--dist:    $(DISTSRC)
--    rm -rf $(DISTDIR)
--    mkdir $(DISTDIR)
--    cp --parents $(DISTSRC) $(DISTDIR)/
--    rm -f $(DISTDIR)/crypto/gmp.h
--    tar -chzf $(DISTDIR).tar.gz $(DISTDIR)
--    rm -rf $(DISTDIR)
-+mrproper: clean
-+    rm -f $(BIN) tpm_version.h
-
- $(src)/crypto/libgmp.a:
-     test -f $(src)/crypto/libgmp.a || ln -s $(GMP_LIB)
$(src)/crypto/libgmp.a
-@@ -88,4 +98,3 @@ version:
-     @echo "#endif /* _TPM_VERSION_H_ */" >> $(src)/tpm_version.h
-
- .PHONY: all install clean dist gmp version
--
-diff -uprN orig/tpm_emulator-0.4/README tpm_emulator/README
---- orig/tpm_emulator-0.4/README    2006-06-23 03:37:07.000000000 -0700
-+++ tpm_emulator/README    2006-07-24 14:35:35.000000000 -0700
-@@ -13,7 +13,8 @@ $Id: README 113 2006-06-18 12:38:13Z hst
- Copyright
- --------------------------------------------------------------------------
- Copyright (C) 2004 Mario Strasser <mast@xxxxxxx> and Swiss Federal
--Institute of Technology (ETH) Zurich.
-+                   Institute of Technology (ETH) Zurich.
-+Copyright (C) 2005 INTEL Corp
-              
- This program is free software; you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
-@@ -43,6 +44,12 @@ Example:
- GMP_LIB        := /usr/lib/libgmp.a
- GMP_HEADER     := /usr/include/gmp.h
-
-+GNU MP Library on 64 bit Systems
-+--------------------------------------------------------------------------
-+Some 64-bit kernels have problems with importing the user-space gmp
-+library (/usr/lib*/libgmp.a) into kernel space.  These kernels will
require
-+that the gmp library be recompiled for kernel space with -mcmodel=kernel.
-+
- Installation
- --------------------------------------------------------------------------
- The compilation and installation process uses the build environment for
-diff -uprN orig/tpm_emulator-0.4/tpm/tpm_capability.c
tpm_emulator/tpm/tpm_capability.c
---- orig/tpm_emulator-0.4/tpm/tpm_capability.c    2006-06-23
19:37:07.000000000 +0900
-+++ tpm_emulator/tpm/tpm_capability.c    2007-12-28 22:50:19.000000000
+0900
-@@ -701,7 +701,10 @@ TPM_RESULT TPM_GetCapabilityOwner(TPM_VE
-   TPM_RESULT res;
-  
-   info("TPM_GetCapabilityOwner()");
-- 
-+
-+  if (!tpmData.permanent.flags.owned) {
-+    return TPM_NOSRK;
-+  }
-   /* Verify owner authorization */
-   res = tpm_verify_auth(auth1, tpmData.permanent.data.ownerAuth,
TPM_KH_OWNER);
-   if (res != TPM_SUCCESS) return res;
-diff -uprN orig/tpm_emulator-0.4/tpm/tpm_cmd_handler.c
tpm_emulator/tpm/tpm_cmd_handler.c
---- orig/tpm_emulator-0.4/tpm/tpm_cmd_handler.c    2006-06-23
19:37:07.000000000 +0900
-+++ tpm_emulator/tpm/tpm_cmd_handler.c    2007-09-12 20:23:00.000000000
+0900
-@@ -565,7 +565,7 @@ static TPM_RESULT execute_TPM_Seal(TPM_R
-   if (tpm_unmarshal_TPM_KEY_HANDLE(&ptr, &len, &keyHandle)
-       || tpm_unmarshal_TPM_ENCAUTH(&ptr, &len, &encAuth)
-       || tpm_unmarshal_UINT32(&ptr, &len, &pcrInfoSize)
--      || tpm_unmarshal_TPM_PCR_INFO(&ptr, &len, &pcrInfo)
-+      || (pcrInfoSize >0 && tpm_unmarshal_TPM_PCR_INFO(&ptr, &len,
&pcrInfo))
-       || tpm_unmarshal_UINT32(&ptr, &len, &inDataSize)
-       || tpm_unmarshal_BLOB(&ptr, &len, &inData, inDataSize)
-       || len != 0) return TPM_BAD_PARAMETER;
-@@ -798,7 +798,7 @@ static TPM_RESULT execute_TPM_Sealx(TPM_
-   if (tpm_unmarshal_TPM_KEY_HANDLE(&ptr, &len, &keyHandle)
-       || tpm_unmarshal_TPM_ENCAUTH(&ptr, &len, &encAuth)
-       || tpm_unmarshal_UINT32(&ptr, &len, &pcrInfoSize)
--      || tpm_unmarshal_TPM_PCR_INFO(&ptr, &len, &pcrInfo)
-+      || (pcrInfoSize > 0 && tpm_unmarshal_TPM_PCR_INFO(&ptr, &len,
&pcrInfo))
-       || tpm_unmarshal_UINT32(&ptr, &len, &inDataSize)
-       || tpm_unmarshal_BLOB(&ptr, &len, &inData, inDataSize)
-       || len != 0) return TPM_BAD_PARAMETER;
-diff -uprN orig/tpm_emulator-0.4/tpm/tpm_credentials.c
tpm_emulator/tpm/tpm_credentials.c
---- orig/tpm_emulator-0.4/tpm/tpm_credentials.c    2006-06-23
19:37:07.000000000 +0900
-+++ tpm_emulator/tpm/tpm_credentials.c    2007-09-12 20:23:30.000000000
+0900
-@@ -47,20 +47,20 @@ int tpm_compute_pubkey_checksum(TPM_NONC
-
- TPM_RESULT tpm_get_pubek(TPM_PUBKEY *pubEndorsementKey)
- {
--  UINT32 key_length;
-+  size_t key_length;
-   if (!tpmData.permanent.data.endorsementKey.size) return
TPM_NO_ENDORSEMENT;
-   /* setup TPM_PUBKEY structure */
--  key_length = tpmData.permanent.data.endorsementKey.size;
--  pubEndorsementKey->pubKey.keyLength = key_length >> 3;
-+  pubEndorsementKey->pubKey.keyLength =
tpmData.permanent.data.endorsementKey.size >> 3;
-   pubEndorsementKey->pubKey.key =
tpm_malloc(pubEndorsementKey->pubKey.keyLength);
-   if (pubEndorsementKey->pubKey.key == NULL) return TPM_FAIL;
-   rsa_export_modulus(&tpmData.permanent.data.endorsementKey,
--    pubEndorsementKey->pubKey.key,
--    &pubEndorsementKey->pubKey.keyLength);
-+             pubEndorsementKey->pubKey.key,
-+             &key_length);
-+  pubEndorsementKey->pubKey.keyLength = key_length;
-   pubEndorsementKey->algorithmParms.algorithmID = TPM_ALG_RSA;
-   pubEndorsementKey->algorithmParms.encScheme =
TPM_ES_RSAESOAEP_SHA1_MGF1;
-   pubEndorsementKey->algorithmParms.sigScheme = TPM_SS_NONE;
--  pubEndorsementKey->algorithmParms.parms.rsa.keyLength = key_length;
-+  pubEndorsementKey->algorithmParms.parms.rsa.keyLength = key_length << 3;
-   pubEndorsementKey->algorithmParms.parms.rsa.numPrimes = 2;
-   pubEndorsementKey->algorithmParms.parms.rsa.exponentSize = 0;
-   pubEndorsementKey->algorithmParms.parms.rsa.exponent = NULL;
-@@ -175,6 +175,7 @@ TPM_RESULT TPM_OwnerReadInternalPub(TPM_
- {
-   TPM_RESULT res;
-   TPM_KEY_DATA *srk = &tpmData.permanent.data.srk;
-+  size_t key_length;
-   info("TPM_OwnerReadInternalPub()");
-   /* verify authorization */
-   res = tpm_verify_auth(auth1, tpmData.permanent.data.ownerAuth,
TPM_KH_OWNER);
-@@ -186,7 +187,8 @@ TPM_RESULT TPM_OwnerReadInternalPub(TPM_
-     publicPortion->pubKey.key =
tpm_malloc(publicPortion->pubKey.keyLength);
-     if (publicPortion->pubKey.key == NULL) return TPM_FAIL;
-     rsa_export_modulus(&srk->key, publicPortion->pubKey.key,
--      &publicPortion->pubKey.keyLength);
-+      &key_length);
-+    publicPortion->pubKey.keyLength = key_length;
-     publicPortion->algorithmParms.algorithmID = TPM_ALG_RSA;
-     publicPortion->algorithmParms.encScheme = srk->encScheme;
-     publicPortion->algorithmParms.sigScheme = srk->sigScheme;
-diff -uprN orig/tpm_emulator-0.4/tpm/tpm_crypto.c
tpm_emulator/tpm/tpm_crypto.c
---- orig/tpm_emulator-0.4/tpm/tpm_crypto.c    2006-06-23
03:37:07.000000000 -0700
-+++ tpm_emulator/tpm/tpm_crypto.c    2006-07-24 14:35:35.000000000 -0700
-@@ -182,7 +182,8 @@ TPM_RESULT TPM_CertifyKey(TPM_KEY_HANDLE
-   TPM_KEY_DATA *cert, *key;
-   sha1_ctx_t sha1_ctx;
-   BYTE *buf, *p;
--  UINT32 length;
-+  UINT32 length32;
-+  size_t length;
-   info("TPM_CertifyKey()");
-   /* get keys */
-   cert = tpm_get_key(certHandle);
-@@ -264,14 +265,15 @@ TPM_RESULT TPM_CertifyKey(TPM_KEY_HANDLE
-   /* compute the digest of the CERTIFY_INFO[2] structure and sign it */
-   length = sizeof_TPM_CERTIFY_INFO((*certifyInfo));
-   p = buf = tpm_malloc(length);
-+  length32=(UINT32) length;
-   if (buf == NULL
--      || tpm_marshal_TPM_CERTIFY_INFO(&p, &length, certifyInfo)) {
-+      || tpm_marshal_TPM_CERTIFY_INFO(&p, &length32, certifyInfo)) {
-     free_TPM_KEY_PARMS(certifyInfo->algorithmParms);
-     return TPM_FAIL;
-   }
-   length = sizeof_TPM_CERTIFY_INFO((*certifyInfo));
-   sha1_init(&sha1_ctx);
--  sha1_update(&sha1_ctx, buf, length);
-+  sha1_update(&sha1_ctx, buf, (size_t) length);
-   sha1_final(&sha1_ctx, buf);
-   res = tpm_sign(cert, auth1, FALSE, buf, SHA1_DIGEST_LENGTH, outData,
outDataSize);
-   tpm_free(buf);
-@@ -292,7 +294,8 @@ TPM_RESULT TPM_CertifyKey2(TPM_KEY_HANDL
-   TPM_KEY_DATA *cert, *key;
-   sha1_ctx_t sha1_ctx;
-   BYTE *buf, *p;
--  UINT32 length;
-+  size_t length;
-+  UINT32 length32;
-   info("TPM_CertifyKey2()");
-   /* get keys */
-   cert = tpm_get_key(certHandle);
-@@ -362,8 +365,9 @@ TPM_RESULT TPM_CertifyKey2(TPM_KEY_HANDL
-   /* compute the digest of the CERTIFY_INFO[2] structure and sign it */
-   length = sizeof_TPM_CERTIFY_INFO((*certifyInfo));
-   p = buf = tpm_malloc(length);
-+  length32 = (UINT32) length;
-   if (buf == NULL
--      || tpm_marshal_TPM_CERTIFY_INFO(&p, &length, certifyInfo)) {
-+      || tpm_marshal_TPM_CERTIFY_INFO(&p, &length32, certifyInfo)) {
-     free_TPM_KEY_PARMS(certifyInfo->algorithmParms);
-     return TPM_FAIL;
-   }
-diff -uprN orig/tpm_emulator-0.4/tpm/tpm_daa.c tpm_emulator/tpm/tpm_daa.c
---- orig/tpm_emulator-0.4/tpm/tpm_daa.c    2006-06-23
03:37:07.000000000 -0700
-+++ tpm_emulator/tpm/tpm_daa.c    2006-07-24 14:35:35.000000000 -0700
-@@ -716,14 +716,14 @@ TPM_RESULT TPM_DAA_Join(TPM_HANDLE handl
-           sizeof(session->DAA_tpmSpecific.DAA_rekey));
-       sha1_update(&sha1, (BYTE*) &session->DAA_tpmSpecific.DAA_count,
-           sizeof(session->DAA_tpmSpecific.DAA_count));
--      sha1_update(&sha1, "\x00", 1);
-+      sha1_update(&sha1, (BYTE *) "\x00", 1);
-       sha1_final(&sha1, scratch);
-       sha1_init(&sha1);
-       sha1_update(&sha1, (BYTE*) &session->DAA_tpmSpecific.DAA_rekey,
-           sizeof(session->DAA_tpmSpecific.DAA_rekey));
-       sha1_update(&sha1, (BYTE*) &session->DAA_tpmSpecific.DAA_count,
-           sizeof(session->DAA_tpmSpecific.DAA_count));
--      sha1_update(&sha1, "\x01", 1);
-+      sha1_update(&sha1, (BYTE *) "\x01", 1);
-       sha1_final(&sha1, scratch + SHA1_DIGEST_LENGTH);
-       mpz_init(f), mpz_init(q);
-       mpz_import(f, 2 * SHA1_DIGEST_LENGTH, 1, 1, 0, 0, scratch);
-@@ -805,14 +805,14 @@ TPM_RESULT TPM_DAA_Join(TPM_HANDLE handl
-           sizeof(session->DAA_tpmSpecific.DAA_rekey));
-       sha1_update(&sha1, (BYTE*) &session->DAA_tpmSpecific.DAA_count,
-           sizeof(session->DAA_tpmSpecific.DAA_count));
--      sha1_update(&sha1, "\x00", 1);
-+      sha1_update(&sha1, (BYTE *) "\x00", 1);
-       sha1_final(&sha1, scratch);
-       sha1_init(&sha1);
-       sha1_update(&sha1, (BYTE*) &session->DAA_tpmSpecific.DAA_rekey,
-           sizeof(session->DAA_tpmSpecific.DAA_rekey));
-       sha1_update(&sha1, (BYTE*) &session->DAA_tpmSpecific.DAA_count,
-           sizeof(session->DAA_tpmSpecific.DAA_count));
--      sha1_update(&sha1, "\x01", 1);
-+      sha1_update(&sha1, (BYTE *) "\x01", 1);
-       sha1_final(&sha1, scratch + SHA1_DIGEST_LENGTH);
-       mpz_init(f), mpz_init(q);
-       mpz_import(f, 2 * SHA1_DIGEST_LENGTH, 1, 1, 0, 0, scratch);
-@@ -1489,14 +1489,14 @@ TPM_RESULT TPM_DAA_Join(TPM_HANDLE handl
-           sizeof(session->DAA_tpmSpecific.DAA_rekey));
-       sha1_update(&sha1, (BYTE*) &session->DAA_tpmSpecific.DAA_count,
-           sizeof(session->DAA_tpmSpecific.DAA_count));
--      sha1_update(&sha1, "\x00", 1);
-+      sha1_update(&sha1, (BYTE *) "\x00", 1);
-       sha1_final(&sha1, scratch);
-       sha1_init(&sha1);
-       sha1_update(&sha1, (BYTE*) &session->DAA_tpmSpecific.DAA_rekey,
-           sizeof(session->DAA_tpmSpecific.DAA_rekey));
-       sha1_update(&sha1, (BYTE*) &session->DAA_tpmSpecific.DAA_count,
-           sizeof(session->DAA_tpmSpecific.DAA_count));
--      sha1_update(&sha1, "\x01", 1);
-+      sha1_update(&sha1, (BYTE *) "\x01", 1);
-       sha1_final(&sha1, scratch + SHA1_DIGEST_LENGTH);
-       mpz_init(f), mpz_init(q);
-       mpz_import(f, 2 * SHA1_DIGEST_LENGTH, 1, 1, 0, 0, scratch);
-@@ -1712,14 +1712,14 @@ TPM_RESULT TPM_DAA_Join(TPM_HANDLE handl
-           sizeof(session->DAA_tpmSpecific.DAA_rekey));
-       sha1_update(&sha1, (BYTE*) &session->DAA_tpmSpecific.DAA_count,
-           sizeof(session->DAA_tpmSpecific.DAA_count));
--      sha1_update(&sha1, "\x00", 1);
-+      sha1_update(&sha1, (BYTE *) "\x00", 1);
-       sha1_final(&sha1, scratch);
-       sha1_init(&sha1);
-       sha1_update(&sha1, (BYTE*) &session->DAA_tpmSpecific.DAA_rekey,
-           sizeof(session->DAA_tpmSpecific.DAA_rekey));
-       sha1_update(&sha1, (BYTE*) &session->DAA_tpmSpecific.DAA_count,
-           sizeof(session->DAA_tpmSpecific.DAA_count));
--      sha1_update(&sha1, "\x01", 1);
-+      sha1_update(&sha1, (BYTE *) "\x01", 1);
-       sha1_final(&sha1, scratch + SHA1_DIGEST_LENGTH);
-       mpz_init(f), mpz_init(q);
-       mpz_import(f, 2 * SHA1_DIGEST_LENGTH, 1, 1, 0, 0, scratch);
-@@ -1793,14 +1793,14 @@ TPM_RESULT TPM_DAA_Join(TPM_HANDLE handl
-           sizeof(session->DAA_tpmSpecific.DAA_rekey));
-       sha1_update(&sha1, (BYTE*) &session->DAA_tpmSpecific.DAA_count,
-           sizeof(session->DAA_tpmSpecific.DAA_count));
--      sha1_update(&sha1, "\x00", 1);
-+      sha1_update(&sha1, (BYTE *) "\x00", 1);
-       sha1_final(&sha1, scratch);
-       sha1_init(&sha1);
-       sha1_update(&sha1, (BYTE*) &session->DAA_tpmSpecific.DAA_rekey,
-           sizeof(session->DAA_tpmSpecific.DAA_rekey));
-       sha1_update(&sha1, (BYTE*) &session->DAA_tpmSpecific.DAA_count,
-           sizeof(session->DAA_tpmSpecific.DAA_count));
--      sha1_update(&sha1, "\x01", 1);
-+      sha1_update(&sha1, (BYTE *) "\x01", 1);
-       sha1_final(&sha1, scratch + SHA1_DIGEST_LENGTH);
-       mpz_init(f), mpz_init(q);
-       mpz_import(f, 2 * SHA1_DIGEST_LENGTH, 1, 1, 0, 0, scratch);
-@@ -2918,14 +2918,14 @@ TPM_RESULT TPM_DAA_Sign(TPM_HANDLE handl
-           sizeof(session->DAA_tpmSpecific.DAA_rekey));
-       sha1_update(&sha1, (BYTE*) &session->DAA_tpmSpecific.DAA_count,
-           sizeof(session->DAA_tpmSpecific.DAA_count));
--      sha1_update(&sha1, "\x00", 1);
-+      sha1_update(&sha1, (BYTE *) "\x00", 1);
-       sha1_final(&sha1, scratch);
-       sha1_init(&sha1);
-       sha1_update(&sha1, (BYTE*) &session->DAA_tpmSpecific.DAA_rekey,
-           sizeof(session->DAA_tpmSpecific.DAA_rekey));
-       sha1_update(&sha1, (BYTE*) &session->DAA_tpmSpecific.DAA_count,
-           sizeof(session->DAA_tpmSpecific.DAA_count));
--      sha1_update(&sha1, "\x01", 1);
-+      sha1_update(&sha1, (BYTE *) "\x01", 1);
-       sha1_final(&sha1, scratch + SHA1_DIGEST_LENGTH);
-       mpz_init(f), mpz_init(q);
-       mpz_import(f, 2 * SHA1_DIGEST_LENGTH, 1, 1, 0, 0, scratch);
-@@ -3143,7 +3143,7 @@ TPM_RESULT TPM_DAA_Sign(TPM_HANDLE handl
-         sha1_init(&sha1);
-         sha1_update(&sha1, (BYTE*) &session->DAA_session.DAA_digest,
-           sizeof(session->DAA_session.DAA_digest));
--        sha1_update(&sha1, "\x01", 1);
-+        sha1_update(&sha1, (BYTE *) "\x01", 1);
-         sha1_update(&sha1, inputData1, inputSize1);
-         sha1_final(&sha1, (BYTE*) &session->DAA_session.DAA_digest);
-       }
-@@ -3172,7 +3172,7 @@ TPM_RESULT TPM_DAA_Sign(TPM_HANDLE handl
-         sha1_init(&sha1);
-         sha1_update(&sha1, (BYTE*) &session->DAA_session.DAA_digest,
-           sizeof(session->DAA_session.DAA_digest));
--        sha1_update(&sha1, "\x00", 1);
-+        sha1_update(&sha1, (BYTE*) "\x00", 1);
-         rsa_export_modulus(&aikData->key, scratch, &size);
-         sha1_update(&sha1, scratch, size);
-         sha1_final(&sha1, (BYTE*) &session->DAA_session.DAA_digest);
-@@ -3229,14 +3229,14 @@ TPM_RESULT TPM_DAA_Sign(TPM_HANDLE handl
-           sizeof(session->DAA_tpmSpecific.DAA_rekey));
-       sha1_update(&sha1, (BYTE*) &session->DAA_tpmSpecific.DAA_count,
-           sizeof(session->DAA_tpmSpecific.DAA_count));
--      sha1_update(&sha1, "\x00", 1);
-+      sha1_update(&sha1, (BYTE *) "\x00", 1);
-       sha1_final(&sha1, scratch);
-       sha1_init(&sha1);
-       sha1_update(&sha1, (BYTE*) &session->DAA_tpmSpecific.DAA_rekey,
-           sizeof(session->DAA_tpmSpecific.DAA_rekey));
-       sha1_update(&sha1, (BYTE*) &session->DAA_tpmSpecific.DAA_count,
-           sizeof(session->DAA_tpmSpecific.DAA_count));
--      sha1_update(&sha1, "\x01", 1);
-+      sha1_update(&sha1, (BYTE *) "\x01", 1);
-       sha1_final(&sha1, scratch + SHA1_DIGEST_LENGTH);
-       mpz_init(f), mpz_init(q);
-       mpz_import(f, 2 * SHA1_DIGEST_LENGTH, 1, 1, 0, 0, scratch);
-@@ -3309,14 +3309,14 @@ TPM_RESULT TPM_DAA_Sign(TPM_HANDLE handl
-           sizeof(session->DAA_tpmSpecific.DAA_rekey));
-       sha1_update(&sha1, (BYTE*) &session->DAA_tpmSpecific.DAA_count,
-           sizeof(session->DAA_tpmSpecific.DAA_count));
--      sha1_update(&sha1, "\x00", 1);
-+      sha1_update(&sha1, (BYTE *) "\x00", 1);
-       sha1_final(&sha1, scratch);
-       sha1_init(&sha1);
-       sha1_update(&sha1, (BYTE*) &session->DAA_tpmSpecific.DAA_rekey,
-           sizeof(session->DAA_tpmSpecific.DAA_rekey));
-       sha1_update(&sha1, (BYTE*) &session->DAA_tpmSpecific.DAA_count,
-           sizeof(session->DAA_tpmSpecific.DAA_count));
--      sha1_update(&sha1, "\x01", 1);
-+      sha1_update(&sha1, (BYTE *) "\x01", 1);
-       sha1_final(&sha1, scratch + SHA1_DIGEST_LENGTH);
-       mpz_init(f), mpz_init(q);
-       mpz_import(f, 2 * SHA1_DIGEST_LENGTH, 1, 1, 0, 0, scratch);
-diff -uprN orig/tpm_emulator-0.4/tpm/tpm_data.c tpm_emulator/tpm/tpm_data.c
---- orig/tpm_emulator-0.4/tpm/tpm_data.c    2006-06-23
03:37:07.000000000 -0700
-+++ tpm_emulator/tpm/tpm_data.c    2006-07-24 14:35:35.000000000 -0700
-@@ -40,6 +40,7 @@ static inline void init_pcr_attr(int pcr
- void tpm_init_data(void)
- {
-   /* endorsement key */
-+#ifndef TPM_GENERATE_EK
-   uint8_t ek_n[] = 
"\xa8\xdb\xa9\x42\xa8\xf3\xb8\x06\x85\x90\x76\x93\xad\xf7"
-     "\x74\xec\x3f\xd3\x3d\x9d\xe8\x2e\xff\x15\xed\x0e\xce\x5f\x93"
-     "\x92\xeb\xd1\x96\x2b\x72\x18\x81\x79\x12\x9d\x9c\x40\xd7\x1a"
-@@ -77,6 +78,8 @@ void tpm_init_data(void)
-     "\xd1\xc0\x8b\x5b\xa2\x2e\xa7\x15\xca\x50\x75\x10\x48\x9c\x2b"
-     "\x18\xb9\x67\x8f\x5d\x64\xc3\x28\x9f\x2f\x16\x2f\x08\xda\x47"
-     "\xec\x86\x43\x0c\x80\x99\x07\x34\x0f";
-+#endif
-+
-   int i;
-   /* reset all data to NULL, FALSE or 0 */
-   memset(&tpmData, 0, sizeof(tpmData));
-@@ -152,44 +155,43 @@ void tpm_release_data(void)
-
- #ifdef TPM_STORE_TO_FILE
-
--#include <linux/fs.h>
--#include <linux/unistd.h>
--#include <asm/uaccess.h>
-+#include <sys/types.h>
-+#include <sys/stat.h>
-+#include <fcntl.h>
-+#include <unistd.h>
-
- #define TPM_STORAGE_FILE "/var/tpm/tpm_emulator-1.2."
STR(VERSION_MAJOR) "." STR(VERSION_MINOR)
-
- static int write_to_file(uint8_t *data, size_t data_length)
- {
-   int res;
--  struct file *fp;
--  mm_segment_t old_fs = get_fs();
--  fp = filp_open(TPM_STORAGE_FILE, O_WRONLY | O_TRUNC | O_CREAT,
S_IRUSR | S_IWUSR);
--  if (IS_ERR(fp)) return -1;
--  set_fs(get_ds());
--  res = fp->f_op->write(fp, data, data_length, &fp->f_pos);
--  set_fs(old_fs);
--  filp_close(fp, NULL);
-+  int fp;
-+  fp = open(TPM_STORAGE_FILE, O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR |
S_IWUSR);
-+  res = write(fp, data, data_length);
-+  close(fp);
-   return (res == data_length) ? 0 : -1;
- }
-
- static int read_from_file(uint8_t **data, size_t *data_length)
- {
-   int res;
--  struct file *fp;
--  mm_segment_t old_fs = get_fs();
--  fp = filp_open(TPM_STORAGE_FILE, O_RDONLY, 0);
--  if (IS_ERR(fp)) return -1;
--  *data_length = (size_t)fp->f_dentry->d_inode->i_size;
--  /* *data_length = i_size_read(fp->f_dentry->d_inode); */
-+  int fp, file_status;
-+  struct stat file_info;
-+  fp = open(TPM_STORAGE_FILE, O_RDONLY, 0);
-+  file_status = fstat(fp, &file_info);
-+  if (file_status < 0) {
-+    close(fp);
-+    return -1;
-+  }
-+
-+  *data_length = file_info.st_size;
-   *data = tpm_malloc(*data_length);
-   if (*data == NULL) {
--    filp_close(fp, NULL);
-+    close(fp);
-     return -1;
-   }
--  set_fs(get_ds());
--  res = fp->f_op->read(fp, *data, *data_length, &fp->f_pos);
--  set_fs(old_fs);
--  filp_close(fp, NULL);
-+  res = read(fp, *data, *data_length);
-+  close(fp);
-   if (res != *data_length) {
-     tpm_free(*data);
-     return -1;
-@@ -216,23 +218,30 @@ static int read_from_file(uint8_t **data
- int tpm_store_permanent_data(void)
- {
-   uint8_t *buf, *ptr;
--  size_t buf_length, len;
-+  UINT32 buf_length, len;
-
-   /* marshal data */
--  buf_length = len = sizeof_TPM_STCLEAR_FLAGS(tpmData.stclear.flags)
--    + sizeof_TPM_PERMANENT_FLAGS(tpmData.permanent.flags) + 2
--    + sizeof_TPM_PERMANENT_DATA(tpmData.permanent.data);
-+  buf_length = len = 4 + sizeof_TPM_STCLEAR_FLAGS(tpmData.stclear.flags)
-+    + sizeof_TPM_PERMANENT_FLAGS(tpmData.permanent.flags)
-+    + sizeof_TPM_STANY_FLAGS(tpmData.stany.flags) + 2
-+    + sizeof_TPM_STCLEAR_DATA(tpmData.stclear.data)
-+    + sizeof_TPM_PERMANENT_DATA(tpmData.permanent.data)
-+    + sizeof_TPM_STANY_DATA(tpmData.stany.data);
-   buf = ptr = tpm_malloc(buf_length);
-   if (buf == NULL
-       || tpm_marshal_TPM_VERSION(&ptr, &len,
&tpmData.permanent.data.version)
-       || tpm_marshal_TPM_STCLEAR_FLAGS(&ptr, &len, &tpmData.stclear.flags)
-       || tpm_marshal_TPM_PERMANENT_FLAGS(&ptr, &len,
&tpmData.permanent.flags)
-+      || tpm_marshal_TPM_STANY_FLAGS(&ptr, &len, &tpmData.stany.flags)
-       || tpm_marshal_BOOL(&ptr, &len,
tpmData.permanent.flags.selfTestSucceeded)
-       || tpm_marshal_BOOL(&ptr, &len, tpmData.permanent.flags.owned)
--      || tpm_marshal_TPM_PERMANENT_DATA(&ptr, &len,
&tpmData.permanent.data)) {
-+      || tpm_marshal_TPM_STCLEAR_DATA(&ptr, &len, &tpmData.stclear.data)
-+      || tpm_marshal_TPM_PERMANENT_DATA(&ptr, &len,
&tpmData.permanent.data)
-+      || tpm_marshal_TPM_STANY_DATA(&ptr, &len, &tpmData.stany.data)) {
-     tpm_free(buf);
-     return -1;
-   }
-+
-   if (write_to_file(buf, buf_length - len)) {
-     tpm_free(buf);
-     return -1;
-@@ -244,31 +253,36 @@ int tpm_store_permanent_data(void)
- int tpm_restore_permanent_data(void)
- {
-   uint8_t *buf, *ptr;
--  size_t buf_length, len;
-+  size_t buf_length;
-+  UINT32 len;
-   TPM_VERSION ver;
-
-   /* read data */
-   if (read_from_file(&buf, &buf_length)) return -1;
-   ptr = buf;
--  len = buf_length;
-+  len = (uint32_t) buf_length;
-   /* unmarshal data */
-   if (tpm_unmarshal_TPM_VERSION(&ptr, &len, &ver)
-       || memcmp(&ver, &tpmData.permanent.data.version,
sizeof(TPM_VERSION))
-       || tpm_unmarshal_TPM_STCLEAR_FLAGS(&ptr, &len,
&tpmData.stclear.flags)
-       || tpm_unmarshal_TPM_PERMANENT_FLAGS(&ptr, &len,
&tpmData.permanent.flags)
-+      || tpm_unmarshal_TPM_STANY_FLAGS(&ptr, &len, &tpmData.stany.flags)
-       || tpm_unmarshal_BOOL(&ptr, &len,
&tpmData.permanent.flags.selfTestSucceeded)
-       || tpm_unmarshal_BOOL(&ptr, &len, &tpmData.permanent.flags.owned)
--      || tpm_unmarshal_TPM_PERMANENT_DATA(&ptr, &len,
&tpmData.permanent.data)) {
-+      || tpm_unmarshal_TPM_STCLEAR_DATA(&ptr, &len, &tpmData.stclear.data)
-+      || tpm_unmarshal_TPM_PERMANENT_DATA(&ptr, &len,
&tpmData.permanent.data)
-+      || tpm_unmarshal_TPM_STANY_DATA(&ptr, &len, &tpmData.stany.data)) {
-     tpm_free(buf);
-     return -1;
-   }
-+
-   tpm_free(buf);
-   return 0;
- }
-
- int tpm_erase_permanent_data(void)
- {
--  int res = write_to_file("", 0);
-+  int res = write_to_file((uint8_t *) "", 0);
-   return res;
- }
-
-diff -uprN orig/tpm_emulator-0.4/tpm/tpm_deprecated.c
tpm_emulator/tpm/tpm_deprecated.c
---- orig/tpm_emulator-0.4/tpm/tpm_deprecated.c    2006-06-23
03:37:07.000000000 -0700
-+++ tpm_emulator/tpm/tpm_deprecated.c    2006-07-24 14:35:35.000000000
-0700
-@@ -1,6 +1,7 @@
- /* Software-Based Trusted Platform Module (TPM) Emulator for Linux
-  * Copyright (C) 2004 Mario Strasser <mast@xxxxxxx>,
-  *                    Swiss Federal Institute of Technology (ETH) Zurich
-+ * Copyright (C) 2005 INTEL Corp
-  *
-  * This module is free software; you can redistribute it and/or modify
-  * it under the terms of the GNU General Public License as published
-@@ -50,7 +51,7 @@ TPM_RESULT TPM_SaveKeyContext(TPM_KEY_HA
-   BYTE *ptr;
-   UINT32 len;
-   info("TPM_SaveKeyContext()");
--  res = TPM_SaveContext(keyHandle, TPM_RT_KEY, "SaveKeyContext..",
-+  res = TPM_SaveContext(keyHandle, TPM_RT_KEY, (BYTE*)"SaveKeyContext..",
-                         keyContextSize, &contextBlob);
-   if (res != TPM_SUCCESS) return res;
-   len = *keyContextSize;
-@@ -82,7 +83,7 @@ TPM_RESULT TPM_SaveAuthContext(TPM_AUTHH
-   BYTE *ptr;
-   UINT32 len;
-   info("TPM_SaveAuthContext()");
--  res = TPM_SaveContext(authHandle, TPM_RT_KEY, "SaveAuthContext.",
-+  res = TPM_SaveContext(authHandle, TPM_RT_KEY,
(BYTE*)"SaveAuthContext.",
-                         authContextSize, &contextBlob);
-   if (res != TPM_SUCCESS) return res;
-   len = *authContextSize;
-diff -uprN orig/tpm_emulator-0.4/tpm/tpm_emulator.h
tpm_emulator/tpm/tpm_emulator.h
---- orig/tpm_emulator-0.4/tpm/tpm_emulator.h    2006-06-23
03:37:07.000000000 -0700
-+++ tpm_emulator/tpm/tpm_emulator.h    2006-07-24 14:35:35.000000000 -0700
-@@ -1,5 +1,6 @@
- /* Software-Based Trusted Platform Module (TPM) Emulator for Linux
-  * Copyright (C) 2004 Mario Strasser <mast@xxxxxxx>,
-+ * Copyright (C) 2005 INTEL Corp
-  *
-  * This module is free software; you can redistribute it and/or modify
-  * it under the terms of the GNU General Public License as published
-@@ -22,7 +23,8 @@
- /* TPM configuration */
- #define TPM_STORE_TO_FILE       1
- #undef  TPM_STRONG_PERSISTENCE
--#undef  TPM_GENERATE_EK
-+//#undef  TPM_GENERATE_EK
-+#define  TPM_GENERATE_EK
- #undef  TPM_GENERATE_SEED_DAA
-
- #define TPM_MANUFACTURER 0x4554485A /* 'ETHZ' */       
-diff -uprN orig/tpm_emulator-0.4/tpm/tpm_marshalling.c
tpm_emulator/tpm/tpm_marshalling.c
---- orig/tpm_emulator-0.4/tpm/tpm_marshalling.c    2006-06-23
03:37:07.000000000 -0700
-+++ tpm_emulator/tpm/tpm_marshalling.c    2006-07-24 14:35:35.000000000
-0700
-@@ -1312,7 +1312,7 @@ int tpm_unmarshal_TPM_STANY_FLAGS(BYTE *
-
- int tpm_marshal_RSA(BYTE **ptr, UINT32 *length, rsa_private_key_t *v)
- {
--  UINT32 m_len, e_len, q_len;
-+  size_t m_len, e_len, q_len;
-   if (*length < sizeof_RSA((*v))) return -1;
-   if (v->size > 0) {
-     rsa_export_modulus(v, &(*ptr)[6], &m_len);
-@@ -1460,6 +1460,66 @@ int tpm_unmarshal_TPM_PERMANENT_DATA(BYT
-   return 0;
- }
-
-+int tpm_marshal_TPM_STCLEAR_DATA(BYTE **ptr, UINT32 *length,
TPM_STCLEAR_DATA *v)
-+{
-+  if (tpm_marshal_TPM_STRUCTURE_TAG(ptr, length, v->tag)
-+    || tpm_marshal_TPM_NONCE(ptr, length, &v->contextNonceKey)
-+    || tpm_marshal_TPM_COUNT_ID(ptr, length, v->countID) ) return -1;
-+
-+  return 0;
-+}
-+
-+int tpm_unmarshal_TPM_STCLEAR_DATA(BYTE **ptr, UINT32 *length,
TPM_STCLEAR_DATA *v)
-+{
-+  if (tpm_unmarshal_TPM_STRUCTURE_TAG(ptr, length, &v->tag)
-+    || tpm_unmarshal_TPM_NONCE(ptr, length, &v->contextNonceKey)
-+    || tpm_unmarshal_TPM_COUNT_ID(ptr, length, &v->countID) ) return -1;
-+
-+  return 0;
-+}
-+
-+int tpm_marshal_TPM_STANY_DATA(BYTE **ptr, UINT32 *length,
TPM_STANY_DATA *v)
-+{
-+  UINT32 i;
-+  if (tpm_marshal_TPM_STRUCTURE_TAG(ptr, length, v->tag)
-+    || tpm_marshal_TPM_NONCE(ptr, length, &v->contextNonceSession)
-+    || tpm_marshal_TPM_DIGEST(ptr, length, &v->auditDigest)
-+    || tpm_marshal_BOOL(ptr, length, v->auditSession)
-+    || tpm_marshal_TPM_CURRENT_TICKS(ptr, length, &v->currentTicks)
-+    || tpm_marshal_UINT32(ptr, length, v->contextCount)
-+    || tpm_marshal_UINT32_ARRAY(ptr, length, v->contextList,
TPM_MAX_SESSION_LIST)) return -1;
-+  for (i = 0; i < TPM_MAX_SESSIONS; i++) {
-+    if (tpm_marshal_TPM_SESSION_DATA(ptr, length, &v->sessions[i]))
return -1;
-+  }
-+  for (i = 0; i < TPM_MAX_SESSIONS_DAA; i++) {
-+    if (tpm_marshal_TPM_DAA_SESSION_DATA(ptr, length,
&v->sessionsDAA[i])) return -1;
-+  }
-+  if (tpm_marshal_TPM_TRANSHANDLE(ptr, length, v->transExclusive))
return -1;
-+
-+  return 0;
-+}
-+
-+int tpm_unmarshal_TPM_STANY_DATA(BYTE **ptr, UINT32 *length,
TPM_STANY_DATA *v)
-+{
-+  UINT32 i;
-+  if (tpm_unmarshal_TPM_STRUCTURE_TAG(ptr, length, &v->tag)
-+    || tpm_unmarshal_TPM_NONCE(ptr, length, &v->contextNonceSession)
-+    || tpm_unmarshal_TPM_DIGEST(ptr, length, &v->auditDigest)
-+    || tpm_unmarshal_BOOL(ptr, length, &v->auditSession)
-+    || tpm_unmarshal_TPM_CURRENT_TICKS(ptr, length, &v->currentTicks)
-+    || tpm_unmarshal_UINT32(ptr, length, &v->contextCount)
-+    || tpm_unmarshal_UINT32_ARRAY(ptr, length, v->contextList,
TPM_MAX_SESSION_LIST)) return -1;
-+  for (i = 0; i < TPM_MAX_SESSIONS; i++) {
-+    if (tpm_unmarshal_TPM_SESSION_DATA(ptr, length, &v->sessions[i]))
return -1;
-+  }
-+  for (i = 0; i < TPM_MAX_SESSIONS_DAA; i++) {
-+    if (tpm_unmarshal_TPM_DAA_SESSION_DATA(ptr, length,
&v->sessionsDAA[i])) return -1;
-+  }
-+  if (tpm_unmarshal_TPM_TRANSHANDLE(ptr, length, &v->transExclusive))
return -1;
-+
-+  return 0;
-+}
-+
- int tpm_marshal_TPM_SESSION_DATA(BYTE **ptr, UINT32 *length,
TPM_SESSION_DATA *v)
- {
-   if (tpm_marshal_BYTE(ptr, length, v->type)
-diff -uprN orig/tpm_emulator-0.4/tpm/tpm_marshalling.h
tpm_emulator/tpm/tpm_marshalling.h
---- orig/tpm_emulator-0.4/tpm/tpm_marshalling.h    2006-06-23
03:37:07.000000000 -0700
-+++ tpm_emulator/tpm/tpm_marshalling.h    2006-07-24 14:35:35.000000000
-0700
-@@ -432,6 +432,12 @@ int tpm_unmarshal_TPM_KEY_DATA(BYTE **pt
- int tpm_marshal_TPM_PERMANENT_DATA(BYTE **ptr, UINT32 *length,
TPM_PERMANENT_DATA *);
- int tpm_unmarshal_TPM_PERMANENT_DATA(BYTE **ptr, UINT32 *length,
TPM_PERMANENT_DATA *);
-
-+int tpm_marshal_TPM_STCLEAR_DATA(BYTE **ptr, UINT32 *length,
TPM_STCLEAR_DATA *v);
-+int tpm_unmarshal_TPM_STCLEAR_DATA(BYTE **ptr, UINT32 *length,
TPM_STCLEAR_DATA *v);
-+
-+int tpm_marshal_TPM_STANY_DATA(BYTE **ptr, UINT32 *length,
TPM_STANY_DATA *v);
-+int tpm_unmarshal_TPM_STANY_DATA(BYTE **ptr, UINT32 *length,
TPM_STANY_DATA *v);
-+
- int tpm_marshal_TPM_SESSION_DATA(BYTE **ptr, UINT32 *length,
TPM_SESSION_DATA *v);
- int tpm_unmarshal_TPM_SESSION_DATA(BYTE **ptr, UINT32 *length,
TPM_SESSION_DATA *v);
-
-diff -uprN orig/tpm_emulator-0.4/tpm/tpm_owner.c
tpm_emulator/tpm/tpm_owner.c
---- orig/tpm_emulator-0.4/tpm/tpm_owner.c    2006-06-23
03:37:07.000000000 -0700
-+++ tpm_emulator/tpm/tpm_owner.c    2006-07-24 14:35:35.000000000 -0700
-@@ -108,7 +108,7 @@ TPM_RESULT TPM_TakeOwnership(TPM_PROTOCO
-   TPM_RESULT res;
-   rsa_private_key_t *ek = &tpmData.permanent.data.endorsementKey;
-   TPM_KEY_DATA *srk = &tpmData.permanent.data.srk;
--  UINT32 buf_size = ek->size >> 3;
-+  size_t buf_size = ek->size >> 3, key_length;
-   BYTE buf[buf_size];
-
-   info("TPM_TakeOwnership()");
-@@ -173,7 +173,8 @@ TPM_RESULT TPM_TakeOwnership(TPM_PROTOCO
-     return TPM_FAIL;
-   }
-   rsa_export_modulus(&srk->key, srkPub->pubKey.key,
--    &srkPub->pubKey.keyLength);
-+             &key_length);
-+  srkPub->pubKey.keyLength = (UINT32) key_length;
-   /* setup tpmProof and set state to owned */
-   tpm_get_random_bytes(tpmData.permanent.data.tpmProof.nonce,
-     sizeof(tpmData.permanent.data.tpmProof.nonce));
-diff -uprN orig/tpm_emulator-0.4/tpm/tpm_startup.c
tpm_emulator/tpm/tpm_startup.c
---- orig/tpm_emulator-0.4/tpm/tpm_startup.c    2006-06-23
03:37:07.000000000 -0700
-+++ tpm_emulator/tpm/tpm_startup.c    2006-07-24 14:35:35.000000000 -0700
-@@ -41,26 +41,29 @@ void TPM_Init(TPM_STARTUP_TYPE startupTy
- TPM_RESULT TPM_Startup(TPM_STARTUP_TYPE startupType)
- {
-   int i;
-+  int restore_fail;
-   info("TPM_Startup(%d)", startupType);
-   if (tpmData.stany.flags.postInitialise == FALSE) return
TPM_INVALID_POSTINIT;
--  /* reset STANY_FLAGS */
--  SET_TO_ZERO(&tpmData.stany.flags);
--  tpmData.stany.flags.tag = TPM_TAG_STANY_FLAGS;
--  /* reset STANY_DATA (invalidates ALL sessions) */
--  SET_TO_ZERO(&tpmData.stany.data);
--  tpmData.stany.data.tag = TPM_TAG_STANY_DATA;
--  /* init session-context nonce */
--  SET_TO_RAND(&tpmData.stany.data.contextNonceSession);
-+
-+  /* try and restore state to get EK, SRK, etc */
-+  restore_fail = tpm_restore_permanent_data();
-+
-   /* set data and flags according to the given startup type */
-   if (startupType == TPM_ST_CLEAR) {
--    /* if available, restore permanent data */
--    tpm_restore_permanent_data();
-+    /* reset STANY_FLAGS */
-+    SET_TO_ZERO(&tpmData.stany.flags);
-+    tpmData.stany.flags.tag = TPM_TAG_STANY_FLAGS;
-+    /* reset STANY_DATA (invalidates ALL sessions) */
-+    SET_TO_ZERO(&tpmData.stany.data);
-+    tpmData.stany.data.tag = TPM_TAG_STANY_DATA;
-+    /* init session-context nonce */
-+    SET_TO_RAND(&tpmData.stany.data.contextNonceSession);
-     /* reset PCR values */
-     for (i = 0; i < TPM_NUM_PCR; i++) {
--      if (tpmData.permanent.data.pcrAttrib[i].pcrReset)
--        SET_TO_ZERO(tpmData.permanent.data.pcrValue[i].digest);
-+      if (!tpmData.permanent.data.pcrAttrib[i].pcrReset)
-+        SET_TO_ZERO(&tpmData.permanent.data.pcrValue[i].digest);
-       else
--        SET_TO_0xFF(tpmData.permanent.data.pcrValue[i].digest);
-+        SET_TO_0xFF(&tpmData.permanent.data.pcrValue[i].digest);
-     }
-     /* reset STCLEAR_FLAGS */
-     SET_TO_ZERO(&tpmData.stclear.flags);
-@@ -79,7 +82,8 @@ TPM_RESULT TPM_Startup(TPM_STARTUP_TYPE
-     /* init key-context nonce */
-     SET_TO_RAND(&tpmData.stclear.data.contextNonceKey);
-   } else if (startupType == TPM_ST_STATE) {
--    if (tpm_restore_permanent_data()) {
-+    /* restore must have been successful for TPM_ST_STATE */
-+    if (restore_fail) {
-       error("restoring permanent data failed");
-       tpmData.permanent.data.testResult =
"tpm_restore_permanent_data() failed";
-       tpmData.permanent.flags.selfTestSucceeded = FALSE;
-diff -uprN orig/tpm_emulator-0.4/tpm/tpm_storage.c
tpm_emulator/tpm/tpm_storage.c
---- orig/tpm_emulator-0.4/tpm/tpm_storage.c    2006-06-23
03:37:07.000000000 -0700
-+++ tpm_emulator/tpm/tpm_storage.c    2006-07-24 14:35:35.000000000 -0700
-@@ -58,6 +58,7 @@ int encrypt_sealed_data(TPM_KEY_DATA *ke
-                         BYTE *enc, UINT32 *enc_size)
- {
-   UINT32 len;
-+  size_t enc_size32 = *enc_size;
-   BYTE *buf, *ptr;
-   rsa_public_key_t pub_key;
-   int scheme;
-@@ -72,7 +73,7 @@ int encrypt_sealed_data(TPM_KEY_DATA *ke
-   if (buf == NULL
-       || tpm_marshal_TPM_SEALED_DATA(&ptr, &len, seal)
-       || rsa_encrypt(&pub_key, scheme, buf,
sizeof_TPM_SEALED_DATA((*seal)),
--                     enc, enc_size)) {
-+                     enc, &enc_size32)) {
-     tpm_free(buf);
-     rsa_release_public_key(&pub_key);
-     return -1;
-@@ -85,7 +86,8 @@ int encrypt_sealed_data(TPM_KEY_DATA *ke
- int decrypt_sealed_data(TPM_KEY_DATA *key, BYTE *enc, UINT32 enc_size,
-                         TPM_SEALED_DATA *seal, BYTE **buf)
- {
--  UINT32 len;
-+  size_t len;
-+  UINT32 len32;
-   BYTE *ptr;
-   int scheme;
-   switch (key->encScheme) {
-@@ -96,8 +98,12 @@ int decrypt_sealed_data(TPM_KEY_DATA *ke
-   len = enc_size;
-   *buf = ptr = tpm_malloc(len);
-   if (*buf == NULL
--      || rsa_decrypt(&key->key, scheme, enc, enc_size, *buf, &len)
--      || tpm_unmarshal_TPM_SEALED_DATA(&ptr, &len, seal)) {
-+      || rsa_decrypt(&key->key, scheme, enc, enc_size, *buf, &len) ){
-+    tpm_free(*buf);
-+    return -1;
-+  }
-+  len32 = len;
-+  if (tpm_unmarshal_TPM_SEALED_DATA(&ptr, &len32, seal)) {
-     tpm_free(*buf);
-     return -1;
-   }
-@@ -240,11 +246,12 @@ TPM_RESULT TPM_Unseal(TPM_KEY_HANDLE par
-
- TPM_RESULT TPM_UnBind(TPM_KEY_HANDLE keyHandle, UINT32 inDataSize,
-                       BYTE *inData, TPM_AUTH *auth1,
--                      UINT32 *outDataSize, BYTE **outData)
-+                      UINT32 *outDataSize32, BYTE **outData)
- {
-   TPM_RESULT res;
-   TPM_KEY_DATA *key;
-   int scheme;
-+  size_t outDataSize;
-  
-   info("TPM_UnBind()");
-   /* get key */
-@@ -262,8 +269,8 @@ TPM_RESULT TPM_UnBind(TPM_KEY_HANDLE key
-   /* the size of the input data muss be greater than zero */
-   if (inDataSize == 0) return TPM_BAD_PARAMETER;
-   /* decrypt data */
--  *outDataSize = inDataSize;
--  *outData = tpm_malloc(*outDataSize);
-+  outDataSize = inDataSize;
-+  *outData = tpm_malloc(outDataSize);
-   if (*outData == NULL) return TPM_NOSPACE;
-   switch (key->encScheme) {
-     case TPM_ES_RSAESOAEP_SHA1_MGF1: scheme = RSA_ES_OAEP_SHA1; break;
-@@ -271,20 +278,21 @@ TPM_RESULT TPM_UnBind(TPM_KEY_HANDLE key
-     default: tpm_free(*outData); return TPM_DECRYPT_ERROR;
-   }
-   if (rsa_decrypt(&key->key, scheme, inData, inDataSize,
--      *outData, outDataSize)) {
-+      *outData, &outDataSize)) {
-     tpm_free(*outData);
-     return TPM_DECRYPT_ERROR;
-   }
-   /* verify data if it is of type TPM_BOUND_DATA */
-   if (key->encScheme == TPM_ES_RSAESOAEP_SHA1_MGF1
-       || key->keyUsage != TPM_KEY_LEGACY) {
--    if (*outDataSize < 5 || memcmp(*outData, "\x01\x01\00\x00\x02", 5)
!= 0) {
-+    if (outDataSize < 5 || memcmp(*outData, "\x01\x01\00\x00\x02", 5)
!= 0) {
-       tpm_free(*outData);
-       return TPM_DECRYPT_ERROR;
-     }
--    *outDataSize -= 5;
--    memmove(*outData, &(*outData)[5], *outDataSize);
-+    outDataSize -= 5;
-+    memmove(*outData, &(*outData)[5], outDataSize);
-   }
-+  *outDataSize32 = (UINT32) outDataSize;
-   return TPM_SUCCESS;
- }
-
-@@ -334,12 +342,13 @@ int compute_pubkey_digest(TPM_PUBKEY *ke
- }
-
- int encrypt_private_key(TPM_KEY_DATA *key, TPM_STORE_ASYMKEY *store,
--                        BYTE *enc, UINT32 *enc_size)
-+                        BYTE *enc, UINT32 *enc_size32)
- {
-   UINT32 len;
-   BYTE *buf, *ptr;
-   rsa_public_key_t pub_key;
-   int scheme;
-+  size_t enc_size;
-   switch (key->encScheme) {
-     case TPM_ES_RSAESOAEP_SHA1_MGF1: scheme = RSA_ES_OAEP_SHA1; break;
-     case TPM_ES_RSAESPKCSv15: scheme = RSA_ES_PKCSV15; break;
-@@ -351,11 +360,12 @@ int encrypt_private_key(TPM_KEY_DATA *ke
-   if (buf == NULL
-       || tpm_marshal_TPM_STORE_ASYMKEY(&ptr, &len, store)
-       || rsa_encrypt(&pub_key, scheme, buf,
sizeof_TPM_STORE_ASYMKEY((*store)),
--                     enc, enc_size)) {
-+                     enc, &enc_size)) {
-     tpm_free(buf);
-     rsa_release_public_key(&pub_key);
-     return -1;
-   }
-+  *enc_size32 = (UINT32) enc_size;
-   tpm_free(buf);
-   rsa_release_public_key(&pub_key);
-   return 0;
-@@ -364,7 +374,8 @@ int encrypt_private_key(TPM_KEY_DATA *ke
- int decrypt_private_key(TPM_KEY_DATA *key, BYTE *enc, UINT32 enc_size,
-                         TPM_STORE_ASYMKEY *store, BYTE **buf)
- {
--  UINT32 len;
-+  UINT32 len32;
-+  size_t len;
-   BYTE *ptr;
-   int scheme;
-   switch (key->encScheme) {
-@@ -375,8 +386,12 @@ int decrypt_private_key(TPM_KEY_DATA *ke
-   len = enc_size;
-   *buf = ptr = tpm_malloc(len);
-   if (*buf == NULL
--      || rsa_decrypt(&key->key, scheme, enc, enc_size, *buf, &len)
--      || tpm_unmarshal_TPM_STORE_ASYMKEY(&ptr, &len, store)) {
-+      || rsa_decrypt(&key->key, scheme, enc, enc_size, *buf, &len) ) {
-+    tpm_free(*buf);
-+    return -1;
-+  }
-+  len32 = (UINT32) len;
-+  if (tpm_unmarshal_TPM_STORE_ASYMKEY(&ptr, &len32, store)) { 
-     tpm_free(*buf);
-     return -1;
-   }
-@@ -394,7 +409,7 @@ TPM_RESULT TPM_CreateWrapKey(TPM_KEY_HAN
-   TPM_SESSION_DATA *session;
-   TPM_STORE_ASYMKEY store;
-   rsa_private_key_t rsa;
--  UINT32 key_length;
-+  size_t key_length;
-
-   info("TPM_CreateWrapKey()");
-   /* get parent key */
-@@ -450,11 +465,11 @@ TPM_RESULT TPM_CreateWrapKey(TPM_KEY_HAN
-     }
-   }
-   /* generate key and store it */
--  key_length = keyInfo->algorithmParms.parms.rsa.keyLength;
--  if (rsa_generate_key(&rsa, key_length)) return TPM_FAIL;
--  wrappedKey->pubKey.keyLength = key_length >> 3;
-+  if (rsa_generate_key(&rsa,
keyInfo->algorithmParms.parms.rsa.keyLength))
-+    return TPM_FAIL;
-+  wrappedKey->pubKey.keyLength =
keyInfo->algorithmParms.parms.rsa.keyLength >> 3;
-   wrappedKey->pubKey.key = tpm_malloc(wrappedKey->pubKey.keyLength);
--  store.privKey.keyLength = key_length >> 4;
-+  store.privKey.keyLength =
keyInfo->algorithmParms.parms.rsa.keyLength >> 4;
-   store.privKey.key = tpm_malloc(store.privKey.keyLength);
-   wrappedKey->encDataSize = parent->key.size >> 3;
-   wrappedKey->encData = tpm_malloc(wrappedKey->encDataSize);
-@@ -466,9 +481,11 @@ TPM_RESULT TPM_CreateWrapKey(TPM_KEY_HAN
-     tpm_free(wrappedKey->encData);
-     return TPM_NOSPACE;
-   }
--  rsa_export_modulus(&rsa, wrappedKey->pubKey.key,
--    &wrappedKey->pubKey.keyLength);
--  rsa_export_prime1(&rsa, store.privKey.key, &store.privKey.keyLength);
-+  rsa_export_modulus(&rsa, wrappedKey->pubKey.key,
-+             &key_length);
-+  wrappedKey->pubKey.keyLength = (UINT32) key_length;
-+  rsa_export_prime1(&rsa, store.privKey.key, &key_length);
-+  store.privKey.keyLength = (UINT32) key_length;
-   rsa_release_private_key(&rsa);
-   /* compute the digest of the wrapped key (without encData) */
-   if (compute_key_digest(wrappedKey, &store.pubDataDigest)) {
-@@ -602,6 +619,7 @@ TPM_RESULT TPM_LoadKey2(TPM_KEY_HANDLE p
-
- int tpm_setup_key_parms(TPM_KEY_DATA *key, TPM_KEY_PARMS *parms)
- {
-+  size_t key_length;
-   parms->algorithmID = TPM_ALG_RSA;
-   parms->encScheme = key->encScheme;
-   parms->sigScheme = key->sigScheme;
-@@ -611,7 +629,8 @@ int tpm_setup_key_parms(TPM_KEY_DATA *ke
-   parms->parms.rsa.exponent = tpm_malloc(parms->parms.rsa.exponentSize);
-   if (parms->parms.rsa.exponent == NULL) return -1;
-   rsa_export_exponent(&key->key, parms->parms.rsa.exponent,
--    &parms->parms.rsa.exponentSize);
-+    &key_length);
-+  parms->parms.rsa.exponentSize = (UINT32) key_length;
-   parms->parmSize = 12 + parms->parms.rsa.exponentSize;
-   return 0;
- }
-@@ -622,6 +641,7 @@ TPM_RESULT TPM_GetPubKey(TPM_KEY_HANDLE
-   TPM_RESULT res;
-   TPM_KEY_DATA *key;
-   TPM_DIGEST digest;
-+  size_t key_length;
-   info("TPM_GetPubKey()");
-   /* get key */
-   if (keyHandle == TPM_KH_SRK
-@@ -650,8 +670,8 @@ TPM_RESULT TPM_GetPubKey(TPM_KEY_HANDLE
-   pubKey->pubKey.keyLength = key->key.size >> 3;
-   pubKey->pubKey.key = tpm_malloc(pubKey->pubKey.keyLength);
-   if (pubKey->pubKey.key == NULL) return TPM_NOSPACE;
--  rsa_export_modulus(&key->key, pubKey->pubKey.key,
--    &pubKey->pubKey.keyLength);
-+  rsa_export_modulus(&key->key, pubKey->pubKey.key, &key_length);
-+  pubKey->pubKey.keyLength = (UINT32) key_length;
-   if (tpm_setup_key_parms(key, &pubKey->algorithmParms) != 0) {
-     error("TPM_GetPubKey(): tpm_setup_key_parms() failed.");
-     tpm_free(pubKey->pubKey.key);
-diff -uprN orig/tpm_emulator-0.4/tpm/tpm_structures.h
tpm_emulator/tpm/tpm_structures.h
---- orig/tpm_emulator-0.4/tpm/tpm_structures.h    2006-06-23
03:37:07.000000000 -0700
-+++ tpm_emulator/tpm/tpm_structures.h    2006-07-24 14:35:35.000000000
-0700
-@@ -1958,6 +1958,7 @@ typedef struct tdTPM_DAA_ISSUER {
-   TPM_DIGEST DAA_digest_gamma;
-   BYTE DAA_generic_q[26];
- } TPM_DAA_ISSUER;
-+#define sizeof_TPM_DAA_ISSUER(s) (2 + (20 * 6) + 26 )
-
- /*
-  * TPM_DAA_TPM ([TPM_Part2], Section 22.4)
-@@ -1973,6 +1974,7 @@ typedef struct tdTPM_DAA_TPM {
-   TPM_DIGEST DAA_rekey;
-   UINT32 DAA_count;
- } TPM_DAA_TPM;
-+#define sizeof_TPM_DAA_TPM(s) (2 + (4 * 20) + 4)
-
- /*
-  * TPM_DAA_CONTEXT ([TPM_Part2], Section 22.5)
-@@ -1987,6 +1989,7 @@ typedef struct tdTPM_DAA_CONTEXT {
-   BYTE DAA_scratch[256];
-   BYTE DAA_stage;
- } TPM_DAA_CONTEXT;
-+#define sizeof_TPM_DAA_CONTEXT(s) (2 + (3 * 20) + 256 + 1)
-
- /*
-  * TPM_DAA_JOINDATA ([TPM_Part2], Section 22.6)
-@@ -1998,6 +2001,7 @@ typedef struct tdTPM_DAA_JOINDATA {
-   BYTE DAA_join_u1[138];
-   TPM_DIGEST DAA_digest_n0;
- } TPM_DAA_JOINDATA;
-+#define sizeof_TPM_DAA_JOINDATA(s) (1 + 1 + 20)
-
- /*
-  * TPM_DAA_BLOB ([TPM_Part2], Section 22.8)
-@@ -2202,6 +2206,7 @@ typedef struct tdTPM_STCLEAR_DATA {
-   //UINT32 ownerReference;
-   //BOOL disableResetLock;
- } TPM_STCLEAR_DATA;
-+#define sizeof_TPM_STCLEAR_DATA(s) (2 + 20 + 4)
-
- /*
-  * TPM_SESSION_DATA
-@@ -2238,6 +2243,11 @@ typedef struct tdTPM_DAA_SESSION_DATA {
-   TPM_DAA_JOINDATA DAA_joinSession;
-   TPM_HANDLE handle;
- } TPM_DAA_SESSION_DATA;
-+#define sizeof_TPM_DAA_SESSION_DATA(s) ( 1 \
-+  + sizeof_TPM_DAA_ISSUER(s.DAA_issuerSettings) \
-+  + sizeof_TPM_DAA_TPM(s.DAA_tpmSpecific) \
-+  + sizeof_TPM_DAA_CONTEXT(s.DAA_session) \
-+  + sizeof_TPM_DAA_JOINDATA(s.DAA_joinSession) + 4)
-
- /*
-  * TPM_STANY_DATA ([TPM_Part2], Section 7.6)
-@@ -2262,6 +2272,11 @@ typedef struct tdTPM_STANY_DATA {
-   TPM_DAAHANDLE currentDAA;
-   TPM_TRANSHANDLE transExclusive;
- } TPM_STANY_DATA;
-+#define sizeof_TPM_STANY_DATA(s) (2 + 20 + 20 + 1 \
-+  + sizeof_TPM_CURRENT_TICKS(s.currentTicks) \
-+  + 4 + (4 * TPM_MAX_SESSION_LIST) \
-+  + (sizeof_TPM_SESSION_DATA(s.sessions[0]) * TPM_MAX_SESSION_LIST) \
-+  + (sizeof_TPM_DAA_SESSION_DATA(s.sessionsDAA[0]) *
TPM_MAX_SESSIONS_DAA) + 4)
-
- /*
-  * TPM_DATA
-diff -uprN orig/tpm_emulator-0.4/tpm/tpm_testing.c
tpm_emulator/tpm/tpm_testing.c
---- orig/tpm_emulator-0.4/tpm/tpm_testing.c    2006-06-23
03:37:07.000000000 -0700
-+++ tpm_emulator/tpm/tpm_testing.c    2006-07-24 14:35:35.000000000 -0700
-@@ -1,6 +1,7 @@
- /* Software-Based Trusted Platform Module (TPM) Emulator for Linux
-  * Copyright (C) 2004 Mario Strasser <mast@xxxxxxx>,
-  *                    Swiss Federal Institute of Technology (ETH) Zurich
-+ * Copyright (C) 2005 INTEL Corp
-  *
-  * This module is free software; you can redistribute it and/or modify
-  * it under the terms of the GNU General Public License as published
-@@ -95,24 +96,24 @@ static int tpm_test_sha1(void)
-   struct {
-     uint8_t *data; uint32_t repetitions; uint8_t *digest;
-   } test_cases[] =  {{
--    "abc", 1,
--   
"\xA9\x99\x3E\x36\x47\x06\x81\x6A\xBA\x3E\x25\x71\x78\x50\xC2\x6C\x9C\xD0\xD8\x9D"
-+    (uint8_t*)"abc", 1,
-+   
(uint8_t*)"\xA9\x99\x3E\x36\x47\x06\x81\x6A\xBA\x3E\x25\x71\x78\x50\xC2\x6C\x9C\xD0\xD8\x9D"
-   }, {
--    "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", 1,
--   
"\x84\x98\x3E\x44\x1C\x3B\xD2\x6E\xBA\xAE\x4A\xA1\xF9\x51\x29\xE5\xE5\x46\x70\xF1"
-+   
(uint8_t*)"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", 1,
-+   
(uint8_t*)"\x84\x98\x3E\x44\x1C\x3B\xD2\x6E\xBA\xAE\x4A\xA1\xF9\x51\x29\xE5\xE5\x46\x70\xF1"
-   }, {
--    "a", 1000000,
--   
"\x34\xAA\x97\x3C\xD4\xC4\xDA\xA4\xF6\x1E\xEB\x2B\xDB\xAD\x27\x31\x65\x34\x01\x6F"
-+    (uint8_t*)"a", 1000000,
-+   
(uint8_t*)"\x34\xAA\x97\x3C\xD4\xC4\xDA\xA4\xF6\x1E\xEB\x2B\xDB\xAD\x27\x31\x65\x34\x01\x6F"
-   }, {
--   
"0123456701234567012345670123456701234567012345670123456701234567", 10,
--   
"\xDE\xA3\x56\xA2\xCD\xDD\x90\xC7\xA7\xEC\xED\xC5\xEB\xB5\x63\x93\x4F\x46\x04\x52"
-+   
(uint8_t*)"0123456701234567012345670123456701234567012345670123456701234567",
10,
-+   
(uint8_t*)"\xDE\xA3\x56\xA2\xCD\xDD\x90\xC7\xA7\xEC\xED\xC5\xEB\xB5\x63\x93\x4F\x46\x04\x52"
-   }};
-
-   debug("tpm_test_sha1()");
-   for (i = 0; i < sizeof(test_cases) / sizeof(test_cases[0]); i++) {
-     sha1_init(&ctx);
-     for (j = 0; j < test_cases[i].repetitions; j++)
--      sha1_update(&ctx, test_cases[i].data, strlen(test_cases[i].data));
-+      sha1_update(&ctx, test_cases[i].data,
strlen((char*)test_cases[i].data));
-     sha1_final(&ctx, digest);
-     if (memcmp(digest, test_cases[i].digest, SHA1_DIGEST_LENGTH) != 0)
return -1;
-   }
-@@ -128,41 +129,41 @@ static int tpm_test_hmac(void)
-   struct {
-     uint8_t *key, key_len, *data, data_len, *digest;
-   } test_cases[] = {{
--    "\x0b", 20, "Hi There", 8,
--   
"\xb6\x17\x31\x86\x55\x05\x72\x64\xe2\x8b\xc0\xb6\xfb\x37\x8c\x8e\xf1\x46\xbe\x00"
-+    (uint8_t*)"\x0b", 20, (uint8_t*)"Hi There", 8,
-+   
(uint8_t*)"\xb6\x17\x31\x86\x55\x05\x72\x64\xe2\x8b\xc0\xb6\xfb\x37\x8c\x8e\xf1\x46\xbe\x00"
-   }, {
--    "Jefe", 4, "what do ya want for nothing?", 28,
--   
"\xef\xfc\xdf\x6a\xe5\xeb\x2f\xa2\xd2\x74\x16\xd5\xf1\x84\xdf\x9c\x25\x9a\x7c\x79"
-+    (uint8_t*)"Jefe", 4, (uint8_t*)"what do ya want for nothing?", 28,
-+   
(uint8_t*)"\xef\xfc\xdf\x6a\xe5\xeb\x2f\xa2\xd2\x74\x16\xd5\xf1\x84\xdf\x9c\x25\x9a\x7c\x79"
-   }, {
--    "\xaa", 20, "\xdd", 50,
--   
"\x12\x5d\x73\x42\xb9\xac\x11\xcd\x91\xa3\x9a\xf4\x8a\xa1\x7b\x4f\x63\xf1\x75\xd3"
-+    (uint8_t*)"\xaa", 20, (uint8_t*)"\xdd", 50,
-+   
(uint8_t*)"\x12\x5d\x73\x42\xb9\xac\x11\xcd\x91\xa3\x9a\xf4\x8a\xa1\x7b\x4f\x63\xf1\x75\xd3"
-   }, {
--   
"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14"
--    "\x15\x16\x17\x18\x19", 25, "\xcd", 50,
--   
"\x4c\x90\x07\xf4\x02\x62\x50\xc6\xbc\x84\x14\xf9\xbf\x50\xc8\x6c\x2d\x72\x35\xda"
-+   
(uint8_t*)"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14"
-+    "\x15\x16\x17\x18\x19", 25, (uint8_t*)"\xcd", 50,
-+   
(uint8_t*)"\x4c\x90\x07\xf4\x02\x62\x50\xc6\xbc\x84\x14\xf9\xbf\x50\xc8\x6c\x2d\x72\x35\xda"
-   }, {
--    "\x0c", 20, "Test With Truncation", 20,
--   
"\x4c\x1a\x03\x42\x4b\x55\xe0\x7f\xe7\xf2\x7b\xe1\xd5\x8b\xb9\x32\x4a\x9a\x5a\x04"
-+    (uint8_t*)"\x0c", 20, (uint8_t*)"Test With Truncation", 20,
-+   
(uint8_t*)"\x4c\x1a\x03\x42\x4b\x55\xe0\x7f\xe7\xf2\x7b\xe1\xd5\x8b\xb9\x32\x4a\x9a\x5a\x04"
-   }, {
--    "\xaa", 80, "Test Using Larger Than Block-Size Key - Hash Key
First", 54,
--   
"\xaa\x4a\xe5\xe1\x52\x72\xd0\x0e\x95\x70\x56\x37\xce\x8a\x3b\x55\xed\x40\x21\x12"
-+    (uint8_t*)"\xaa", 80, (uint8_t*)"Test Using Larger Than Block-Size
Key - Hash Key First", 54,
-+   
(uint8_t*)"\xaa\x4a\xe5\xe1\x52\x72\xd0\x0e\x95\x70\x56\x37\xce\x8a\x3b\x55\xed\x40\x21\x12"
-   }, {
--    "\xaa", 80,
--    "Test Using Larger Than Block-Size Key and Larger Than One
Block-Size Data", 73,
--   
"\xe8\xe9\x9d\x0f\x45\x23\x7d\x78\x6d\x6b\xba\xa7\x96\x5c\x78\x08\xbb\xff\x1a\x91"
-+    (uint8_t*)"\xaa", 80,
-+    (uint8_t*)"Test Using Larger Than Block-Size Key and Larger Than
One Block-Size Data", 73,
-+   
(uint8_t*)"\xe8\xe9\x9d\x0f\x45\x23\x7d\x78\x6d\x6b\xba\xa7\x96\x5c\x78\x08\xbb\xff\x1a\x91"
-   }};
-
-   debug("tpm_test_hmac()");
-   for (i = 0; i < sizeof(test_cases) / sizeof(test_cases[0]); i++) {
--    if (strlen(test_cases[i].key) < test_cases[i].key_len) {
-+    if (strlen((char*)test_cases[i].key) < test_cases[i].key_len) {
-       uint8_t key[test_cases[i].key_len];
-       memset(key, test_cases[i].key[0], test_cases[i].key_len);
-       hmac_init(&ctx, key, test_cases[i].key_len);
-     } else {
-       hmac_init(&ctx, test_cases[i].key, test_cases[i].key_len);
-     }
--    for (j = 0; j < test_cases[i].data_len; j +=
strlen(test_cases[i].data)) {
--      hmac_update(&ctx, test_cases[i].data, strlen(test_cases[i].data));
-+    for (j = 0; j < test_cases[i].data_len; j +=
strlen((char*)test_cases[i].data)) {
-+      hmac_update(&ctx, test_cases[i].data,
strlen((char*)test_cases[i].data));
-     }
-     hmac_final(&ctx, digest);
-     if (memcmp(digest, test_cases[i].digest, SHA1_DIGEST_LENGTH) != 0)
return -1;
-@@ -173,9 +174,9 @@ static int tpm_test_hmac(void)
- static int tpm_test_rsa_EK(void)
- {
-   int res = 0;
--  char *data = "RSA PKCS #1 v1.5 Test-String";
-+  uint8_t *data = (uint8_t*)"RSA PKCS #1 v1.5 Test-String";
-   uint8_t buf[256];
--  size_t buf_len, data_len = strlen(data);
-+  size_t buf_len, data_len = strlen((char*)data);
-   rsa_private_key_t priv_key;
-   rsa_public_key_t pub_key;
-
-diff -uprN orig/tpm_emulator-0.4/tpm/tpm_ticks.c
tpm_emulator/tpm/tpm_ticks.c
---- orig/tpm_emulator-0.4/tpm/tpm_ticks.c    2006-06-23
03:37:07.000000000 -0700
-+++ tpm_emulator/tpm/tpm_ticks.c    2006-07-24 14:35:35.000000000 -0700
-@@ -1,6 +1,7 @@
- /* Software-Based Trusted Platform Module (TPM) Emulator for Linux
-  * Copyright (C) 2004 Mario Strasser <mast@xxxxxxx>,
-  *                    Swiss Federal Institute of Technology (ETH) Zurich
-+ * Copyright (C) 2005 INTEL Corp
-  *
-  * This module is free software; you can redistribute it and/or modify
-  * it under the terms of the GNU General Public License as published
-@@ -39,9 +40,7 @@ TPM_RESULT TPM_SetTickType(TPM_TICKTYPE
- TPM_RESULT TPM_GetTicks(TPM_CURRENT_TICKS *currentTime)
- {
-   info("TPM_GetTicks()");
--  memcpy(currentTime, &tpmData.stany.data.currentTicks,
--    sizeof(TPM_CURRENT_TICKS));
--  return TPM_SUCCESS;
-+  return TPM_DISABLED_CMD;
- }
-
- TPM_RESULT TPM_TickStampBlob(TPM_KEY_HANDLE keyHandle, TPM_NONCE
*antiReplay,
-@@ -49,64 +48,11 @@ TPM_RESULT TPM_TickStampBlob(TPM_KEY_HAN
-                              TPM_CURRENT_TICKS *currentTicks,
-                              UINT32 *sigSize, BYTE **sig)
- {
--  TPM_RESULT res;
--  TPM_KEY_DATA *key;
--  BYTE *info, *p;
--  UINT32 info_length, length;
-   info("TPM_TickStampBlob()");
--  /* get key */
--  key = tpm_get_key(keyHandle);
--  if (key == NULL) return TPM_INVALID_KEYHANDLE;
--  /* verify authorization */
--  res = tpm_verify_auth(auth1, key->usageAuth, keyHandle);
--  if (res != TPM_SUCCESS) return res;
--  if (key->keyUsage != TPM_KEY_SIGNING && key->keyUsage != TPM_KEY_LEGACY
--      && key->keyUsage != TPM_KEY_IDENTITY) return TPM_INVALID_KEYUSAGE;
--  /* get current ticks */
--  TPM_GetTicks(currentTicks);
--  /* sign data using signature scheme PKCS1_SHA1 and TPM_SIGN_INFO
container */
--  *sigSize = key->key.size >> 3;
--  *sig = tpm_malloc(*sigSize);
--  if (*sig == NULL) return TPM_FAIL;
--  /* setup TPM_SIGN_INFO structure */
--  info_length = 30 + sizeof(TPM_DIGEST) +
sizeof_TPM_CURRENT_TICKS(currentTicks);
--  info = tpm_malloc(info_length);
--  if (info == NULL) {
--    tpm_free(*sig);
--    return TPM_FAIL;
--  }
--  memcpy(&info[0], "\x05\x00TSTP", 6);
--  memcpy(&info[6], antiReplay->nonce, 20);
--  *(UINT32*)&info[26] = CPU_TO_BE32(20
--                        + sizeof_TPM_CURRENT_TICKS(currentTicks));
--  memcpy(&info[30], digestToStamp->digest, sizeof(TPM_DIGEST));
--  p = &info[30 + sizeof(TPM_DIGEST)];
--  length = sizeof_TPM_CURRENT_TICKS(currentTicks);
--  if (tpm_marshal_TPM_CURRENT_TICKS(&p, &length, currentTicks)
--      || rsa_sign(&key->key, RSA_SSA_PKCS1_SHA1, info, info_length,
*sig)) {  
--    tpm_free(*sig);
--    tpm_free(info);
--    return TPM_FAIL;
--  }
--  return TPM_SUCCESS;
-+  return TPM_DISABLED_CMD;
- }
-
- void tpm_update_ticks(void)
- {
--  if (tpmData.stany.data.currentTicks.tag == 0) {
--    tpmData.stany.data.currentTicks.tag = TPM_TAG_CURRENT_TICKS;
--    tpmData.stany.data.currentTicks.currentTicks += tpm_get_ticks();
--/* removed since v1.2 rev 94
--    tpmData.stany.data.currentTicks.tickType =
tpmData.permanent.data.tickType;
--*/
--    tpm_get_random_bytes(tpmData.stany.data.currentTicks.tickNonce.nonce,
--      sizeof(TPM_NONCE));
--    tpmData.stany.data.currentTicks.tickRate = 1;
--/* removed since v1.2 rev 94
--    tpmData.stany.data.currentTicks.tickSecurity = TICK_SEC_NO_CHECK;
--*/
--  } else {
--    tpmData.stany.data.currentTicks.currentTicks += tpm_get_ticks();  
--  }
- }
-
-diff -uprN orig/tpm_emulator-0.4/tpm/tpm_transport.c
tpm_emulator/tpm/tpm_transport.c
---- orig/tpm_emulator-0.4/tpm/tpm_transport.c    2006-06-23
03:37:07.000000000 -0700
-+++ tpm_emulator/tpm/tpm_transport.c    2006-07-24 14:35:35.000000000 -0700
-@@ -189,7 +189,7 @@ static void decrypt_wrapped_command(BYTE
-     sha1_init(&sha1);
-     sha1_update(&sha1, auth->nonceEven.nonce,
sizeof(auth->nonceEven.nonce));
-     sha1_update(&sha1, auth->nonceOdd.nonce,
sizeof(auth->nonceOdd.nonce));
--    sha1_update(&sha1, "in", 2);
-+    sha1_update(&sha1, (BYTE*)"in", 2);
-     sha1_update(&sha1, secret, sizeof(TPM_SECRET));
-     j = CPU_TO_BE32(i);
-     sha1_update(&sha1, (BYTE*)&j, 4);
-@@ -211,7 +211,7 @@ static void encrypt_wrapped_command(BYTE
-     sha1_init(&sha1);
-     sha1_update(&sha1, auth->nonceEven.nonce,
sizeof(auth->nonceEven.nonce));
-     sha1_update(&sha1, auth->nonceOdd.nonce,
sizeof(auth->nonceOdd.nonce));
--    sha1_update(&sha1, "out", 3);
-+    sha1_update(&sha1, (BYTE*)"out", 3);
-     sha1_update(&sha1, secret, sizeof(TPM_SECRET));
-     j = CPU_TO_BE32(i);
-     sha1_update(&sha1, (BYTE*)&j, 4);
-diff -uprN orig/tpm_emulator-0.4/tpmd.c tpm_emulator/tpmd.c
---- orig/tpm_emulator-0.4/tpmd.c    1969-12-31 16:00:00.000000000 -0800
-+++ tpm_emulator/tpmd.c    2006-07-24 14:35:35.000000000 -0700
-@@ -0,0 +1,156 @@
-+/* Software-Based Trusted Platform Module (TPM) Emulator for Linux
-+ * Copyright (C) 2005 INTEL Corp
-+ *
-+ * This module is free software; you can redistribute it and/or modify
-+ * it under the terms of the GNU General Public License as published
-+ * by the Free Software Foundation; either version 2 of the License,
-+ * or (at your option) any later version.
-+ *
-+ * This module is distributed in the hope that it will be useful,
-+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
-+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-+ * GNU General Public License for more details.
-+ *
-+ */
-+
-+#include <stdio.h>
-+#include <stdlib.h>
-+#include <unistd.h>
-+#include <string.h>
-+#include <sys/types.h>
-+#include <sys/stat.h>
-+#include <fcntl.h>
-+#include <sys/time.h>
-+
-+#include "tpm_emulator.h"
-+
-+#define TPM_RX_FNAME "/var/tpm/tpm_in.fifo"
-+#define TPM_TX_FNAME "/var/tpm/tpm_out.fifo"
-+
-+#define BUFFER_SIZE 2048
-+
-+static int devurandom=0;
-+     
-+void get_random_bytes(void *buf, int nbytes) {
-+ 
-+  if (devurandom == 0) {
-+    devurandom = open("/dev/urandom", O_RDONLY);
-+  }
-+
-+  if (read(devurandom, buf, nbytes) != nbytes) {
-+      printf("Can't get random number.\n");
-+      exit(-1);
-+  }
-+}
-+
-+uint64_t tpm_get_ticks(void)
-+{
-+  //struct timeval tv;
-+  //int gettimeofday(&tv, struct timezone *tz);
-+  return 0;
-+}
-+
-+int main(int argc, char **argv)
-+{
-+  uint8_t in[BUFFER_SIZE], *out;
-+  uint32_t out_size;
-+  int in_size, written;
-+  int i;
-+  struct stat file_info;
-+
-+  int tpm_tx_fh=-1, tpm_rx_fh=-1;
-+  if (argc < 2) {
-+    printf("Usage: tpmd clear|save|deactivated\n" );
-+      return -1;
-+  }
-+
-+  /* initialize TPM emulator */
-+  if (!strcmp(argv[1], "clear")) {
-+    printf("Initializing tpm: %s\n", argv[1]);
-+    tpm_emulator_init(1);
-+  } else if (!strcmp(argv[1], "save")) {
-+    printf("Initializing tpm: %s\n", argv[1]);
-+    tpm_emulator_init(2);
-+  } else if (!strcmp(argv[1], "deactivated")) {
-+    printf("Initializing tpm: %s\n", argv[1]);
-+    tpm_emulator_init(3);
-+  } else {
-+    printf("invalid startup mode '%s'; must be 'clear', "
-+      "'save' (default) or 'deactivated", argv[1]);
-+    return -1;
-+  }
-+
-+  if ( stat(TPM_RX_FNAME, &file_info) == -1) {
-+    if ( mkfifo(TPM_RX_FNAME, S_IWUSR | S_IRUSR ) ) {
-+      printf("Failed to create fifo %s.\n", TPM_RX_FNAME);
-+      return -1;
-+    }
-+  }
-+
-+  if ( stat(TPM_TX_FNAME, &file_info) == -1) {
-+    if ( mkfifo(TPM_TX_FNAME, S_IWUSR | S_IRUSR ) ) {
-+      printf("Failed to create fifo %s.\n", TPM_TX_FNAME);
-+      return -1;
-+    }
-+  }
-+
-+  while (1) {
-+abort_command:
-+    if (tpm_rx_fh < 0) {
-+      tpm_rx_fh = open(TPM_RX_FNAME, O_RDONLY);
-+    }
-+   
-+    if (tpm_rx_fh < 0) {
-+      printf("ERROR: failed to open devices to listen to guest.\n");
-+      return -1;
-+    }
-+   
-+    if (tpm_tx_fh < 0) {
-+      tpm_tx_fh = open(TPM_TX_FNAME, O_WRONLY);
-+    }
-+
-+    if (tpm_tx_fh < 0) {
-+      printf("ERROR: failed to open devices to respond to guest.\n");
-+      return -1;
-+    }
-+
-+    in_size = read(tpm_rx_fh, in, BUFFER_SIZE);
-+    if (in_size < 6) { // Magic size of minium TPM command
-+      printf("Recv[%d] to small: 0x", in_size);
-+      if (in_size <= 0) {
-+          close(tpm_rx_fh);
-+          tpm_rx_fh = -1;
-+          goto abort_command;
-+      }
-+    } else {
-+      printf("Recv[%d]: 0x", in_size);
-+      for (i=0; i< in_size; i++)
-+        printf("%x ", in[i]);
-+      printf("\n");
-+    }
-+
-+   
-+    if (tpm_handle_command(in, in_size, &out, &out_size) != 0) {
-+        printf("ERROR: Handler Failed.\n");
-+    }
-+
-+    written = write(tpm_tx_fh, out, out_size);
-+
-+    if (written != out_size ) {
-+      printf("ERROR: Part of response not written %d/%d.\nAttempt: ",
written, out_size);
-+    } else {
-+      printf("Sent[%Zu]: ", out_size);
-+    }
-+    for (i=0; i< out_size; i++)
-+      printf("%x ", out[i]);
-+    printf("\n");
-+    tpm_free(out);
-+
-+  } // loop
-+
-+  tpm_emulator_shutdown();
-+
-+  close(tpm_tx_fh);
-+  close(tpm_rx_fh);
-+
-+}
-Binary files orig/tpm_emulator-0.4/tpm_emulator and
tpm_emulator/tpm_emulator differ
-diff -uprN orig/tpm_emulator-0.4/tpm_version.h tpm_emulator/tpm_version.h
---- orig/tpm_emulator-0.4/tpm_version.h    2006-06-23
03:37:07.000000000 -0700
-+++ tpm_emulator/tpm_version.h    2006-07-24 14:35:41.000000000 -0700
-@@ -2,5 +2,5 @@
- #define _TPM_VERSION_H_
- #define VERSION_MAJOR 0
- #define VERSION_MINOR 4
--#define VERSION_BUILD 1151058734
-+#define VERSION_BUILD 1153776940
- #endif /* _TPM_VERSION_H_ */
diff --git a/tools/vtpm/vtpm-0.5.1-LDLIBS.patch
b/tools/vtpm/vtpm-0.5.1-LDLIBS.patch
--- a/tools/vtpm/vtpm-0.5.1-LDLIBS.patch
+++ /dev/null
@@ -1,12 +0,0 @@
-diff -Naurp tpm_emulator-0.5.1/tpmd/Makefile
tpm_emulator-0.5.1/tpmd/Makefile
---- tpm_emulator-0.5.1/tpmd/Makefile
-+++ tpm_emulator-0.5.1/tpmd/Makefile
-@@ -8,7 +8,7 @@ WFLAGS  := -Wall -Wno-unused -Wpointer-a
-            #WFLAGS  += -Wextra -Wcast-qual -Wmissing-prototypes
-Wmissing-declarations -Wstrict-aliasing
- CFLAGS  += $(WFLAGS) -g -I.. -I. -O2 -fno-strict-aliasing
- CFLAGS  += -I../../../../tools/vtpm_manager/manager
--LDFLAGS += -lgmp
-+LDLIBS  += -lgmp
-
- BINDIR  := /usr/bin/
-
diff --git a/tools/vtpm/vtpm-0.5.1.patch b/tools/vtpm/vtpm-0.5.1.patch
--- a/tools/vtpm/vtpm-0.5.1.patch
+++ /dev/null
@@ -1,766 +0,0 @@
-diff -Naurp tpm_emulator-0.5.1/Makefile tpm5-test/Makefile
---- tpm_emulator-0.5.1/Makefile    2008-02-14 03:22:48.000000000 -0500
-+++ tpm5-test/Makefile    2009-07-15 09:45:28.000000000 -0400
-@@ -10,7 +10,7 @@ VERSION_MINOR  := 5
- VERSION_BUILD  := $(shell date +"%s")
- VERSION_SUFFIX := .1
-
--SUBDIRS := tpmd tpmd_dev tddl
-+SUBDIRS := tpmd
-
- all: version all-recursive
-
-@@ -48,12 +48,12 @@ user_install: user
- modules_install: modules
-     @$(MAKE) -C tpmd_dev install || exit -1
-
--DIRS    := . tpm crypto tpmd tpmd_dev tddl tpmd_dev_openbsd
-+DIRS    := . tpm crypto tpmd
- DISTSRC := $(foreach dir, $(DIRS), $(wildcard $(dir)/*.c))
- DISTSRC += $(foreach dir, $(DIRS), $(wildcard $(dir)/*.h))
--DIRS    := . tpmd tpmd_dev tddl tpmd_dev_openbsd
-+DIRS    := . tpmd
- DISTSRC += $(foreach dir, $(DIRS), $(dir)/Makefile)
--DISTSRC += ./README ./AUTHORS ./ChangeLog tpmd_dev/tpmd_dev.rules.in
-+DISTSRC += ./README ./AUTHORS ./ChangeLog
- DISTDIR := tpm_emulator-$(VERSION_MAJOR).$(VERSION_MINOR)$(VERSION_SUFFIX)
-
- dist: $(DISTSRC)
-diff -Naurp tpm_emulator-0.5.1/tpm/tpm_capability.c
tpm5-test/tpm/tpm_capability.c
---- tpm_emulator-0.5.1/tpm/tpm_capability.c    2008-02-14
03:22:48.000000000 -0500
-+++ tpm5-test/tpm/tpm_capability.c    2009-07-16 12:04:20.000000000 -0400
-@@ -136,8 +136,19 @@ static TPM_RESULT cap_property(UINT32 su
-
-     case TPM_CAP_PROP_TIS_TIMEOUT:
-       debug("[TPM_CAP_PROP_TIS_TIMEOUT]");
--      /* TODO: TPM_CAP_PROP_TIS_TIMEOUT */
--      return TPM_FAIL;
-+      /* TODO: TPM_CAP_PROP_TIS_TIMEOUT: Measure these values and
determine correct ones */
-+      UINT32 len = *respSize = 16;
-+      BYTE *ptr = *resp = tpm_malloc(*respSize);
-+      if (ptr == NULL ||
-+          tpm_marshal_UINT32(&ptr, &len, 200000) ||
-+          tpm_marshal_UINT32(&ptr, &len, 200000) ||
-+          tpm_marshal_UINT32(&ptr, &len, 200000) ||
-+          tpm_marshal_UINT32(&ptr, &len, 200000)) {
-+        tpm_free(*resp);
-+        return TPM_FAIL;
-+      }
-+      return TPM_SUCCESS;
-+
-
-     case TPM_CAP_PROP_STARTUP_EFFECT:
-       debug("[TPM_CAP_PROP_STARTUP_EFFECT]");
-@@ -189,8 +200,12 @@ static TPM_RESULT cap_property(UINT32 su
-
-     case TPM_CAP_PROP_DURATION:
-       debug("[TPM_CAP_PROP_DURATION]");
--      /* TODO: TPM_CAP_PROP_DURATION */
--      return TPM_FAIL;
-+      /* TODO: TPM_CAP_PROP_DURATION: Measure these values and return
accurate ones */
-+      BYTE dur[]=
{0x0,0x0,0x0,0xc,0x0,0x7,0xa1,0x20,0x0,0x1e,0x84,0x80,0x11,0xe1,0xa3,0x0};
-+      *respSize = 16;
-+      *resp = tpm_malloc(*respSize);
-+      memcpy(*resp,dur,16);
-+
-
-     case TPM_CAP_PROP_ACTIVE_COUNTER:
-       debug("[TPM_CAP_PROP_ACTIVE_COUNTER]");
-diff -Naurp tpm_emulator-0.5.1/tpmd/Makefile tpm5-test/tpmd/Makefile
---- tpm_emulator-0.5.1/tpmd/Makefile    2008-02-14 03:22:48.000000000 -0500
-+++ tpm5-test/tpmd/Makefile    2009-07-16 12:08:26.000000000 -0400
-@@ -8,9 +8,10 @@ WFLAGS  := -Wall -Wno-unused -Wpointer-a
-            -Wwrite-strings -Wsign-compare -Wno-multichar
-            #WFLAGS  += -Wextra -Wcast-qual -Wmissing-prototypes
-Wmissing-declarations -Wstrict-aliasing
- CFLAGS  += $(WFLAGS) -g -I.. -I. -O2 -fno-strict-aliasing
-+CFLAGS  += -I../../../../tools/vtpm_manager/manager
- LDFLAGS += -lgmp
-
--BINDIR  := /usr/sbin/
-+BINDIR  := /usr/bin/
-
- TPMD    := tpmd
- DIRS    := ../tpm ../crypto
-@@ -18,6 +19,8 @@ SRCS    := $(foreach dir, $(DIRS), $(wil
- OBJS    := $(patsubst %.c, %.o, $(SRCS))
- OBJS    := $(foreach dir, $(DIRS), $(patsubst $(dir)/%.o, %.o,
$(filter $(dir)/%.o, $(OBJS))))
-
-+VTPM_BIN := vtpmd
-+
- vpath %.c $(strip $(DIRS))
-
- all: $(TPMD)
-@@ -32,10 +35,8 @@ TPMD_GROUP ?= tss
- INSTALL    ?= install
-
- install: $(TPMD)
--    $(INSTALL) -m 755 -o $(TPMD_USER) -g $(TPMD_GROUP) -d
$(DESTDIR)/var/lib/tpm
--    $(INSTALL) -m 755 -o $(TPMD_USER) -g $(TPMD_GROUP) -d
$(DESTDIR)/var/run/tpm
-     $(INSTALL) -D -d $(DESTDIR)/$(BINDIR)
--    $(INSTALL) -m 755 $(TPMD) $(DESTDIR)/$(BINDIR)
-+    $(INSTALL) -m 755 $(TPMD) $(DESTDIR)/$(BINDIR)/$(VTPM_BIN)
-
- .PHONY: all clean install
-
-diff -Naurp tpm_emulator-0.5.1/tpmd/tpmd.c tpm5-test/tpmd/tpmd.c
---- tpm_emulator-0.5.1/tpmd/tpmd.c    2008-02-14 03:22:48.000000000 -0500
-+++ tpm5-test/tpmd/tpmd.c    2009-07-16 11:19:05.000000000 -0400
-@@ -32,6 +32,9 @@
- #include <grp.h>
- #include "tpm_emulator_config.h"
- #include "tpm/tpm_emulator.h"
-+#include "tpm/tpm_structures.h"
-+#include "tpm/tpm_marshalling.h"
-+#include "vtpm_manager.h"
-
- #define TPM_DAEMON_NAME     "tpmd"
- #define TPM_CMD_BUF_SIZE    4096
-@@ -39,6 +42,24 @@
- #define TPM_RANDOM_DEVICE   "/dev/urandom"
- #undef  TPM_MKDIRS
-
-+#ifdef VTPM_MULTI_VM
-+ #define DEV_BE "/dev/vtpm"
-+ #define DEV_FE "/dev/tpm"
-+#else
-+ #define PVM_RX_FIFO_D "/var/vtpm/fifos/tpm_cmd_to_%d.fifo"
-+ #define PVM_TX_FIFO "/var/vtpm/fifos/tpm_rsp_from_all.fifo"
-+ #define HVM_RX_FIFO_D "/var/vtpm/socks/%d.socket"
-+
-+ #define VTPM_RX_FIFO_D "/var/vtpm/fifos/vtpm_rsp_to_%d.fifo"
-+ #define VTPM_TX_FIFO "/var/vtpm/fifos/vtpm_cmd_from_all.fifo"
-+
-+ static char *vtpm_rx_name=NULL;
-+#endif
-+
-+ static int vtpm_tx_fh=-1, vtpm_rx_fh=-1;
-+
-+#define BUFFER_SIZE 2048
-+
- static volatile int stopflag = 0;
- static int is_daemon = 0;
- static int opt_debug = 0;
-@@ -49,6 +70,8 @@ static const char *opt_storage_file = "/
- static uid_t opt_uid = 0;
- static gid_t opt_gid = 0;
- static int tpm_startup = 2;
-+static int vtpm_type = VTPM_TYPE_PVM;
-+int dmi_id = 0;
- static int rand_fh;
-
- void tpm_log(int priority, const char *fmt, ...)
-@@ -90,56 +113,241 @@ uint64_t tpm_get_ticks(void)
-
- int tpm_write_to_file(uint8_t *data, size_t data_length)
- {
--    int fh;
--    ssize_t res;
--    fh = open(opt_storage_file, O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR
| S_IWUSR);
--    if (fh < 0) return -1;
--    while (data_length > 0) {
--        res = write(fh, data, data_length);
--    if (res < 0) {
--        close(fh);
--        return -1;
--    }
--    data_length -= res;
--    data += res;
-+  int res, out_data_size, in_header_size;
-+  BYTE *ptr, *out_data, *in_header;
-+  UINT32 result, len, in_rsp_size;
-+  UINT16 tag = VTPM_TAG_REQ;
-+   
-+  printf("Saving NVM\n");
-+  if (vtpm_tx_fh < 0) {
-+#ifdef VTPM_MUTLI_VM
-+    vtpm_tx_fh = open(DEV_FE, O_RDWR);
-+#else
-+    vtpm_tx_fh = open(VTPM_TX_FIFO, O_WRONLY);
-+#endif
-+  }
-+
-+  if (vtpm_tx_fh < 0) {
-+        return -1;
-+  }
-+
-+  // Send request to VTPM Manager to encrypt data
-+#ifdef VTPM_MUTLI_VM
-+  out_data_size = len = VTPM_COMMAND_HEADER_SIZE_CLT + data_length;
-+#else
-+  out_data_size = len = VTPM_COMMAND_HEADER_SIZE_SRV + data_length;
-+#endif
-+ 
-+  out_data = ptr = (BYTE *) malloc(len);
-+
-+  if (ptr == NULL
-+#ifndef VTPM_MUTLI_VM
-+      || tpm_marshal_UINT32(&ptr, &len, dmi_id)
-+#endif
-+      || tpm_marshal_UINT16(&ptr, &len, tag)
-+#ifdef VTPM_MUTLI_VM
-+      || tpm_marshal_UINT32(&ptr, &len, out_data_size)
-+#else
-+      || tpm_marshal_UINT32(&ptr, &len, out_data_size - sizeof(uint32_t))
-+#endif 
-+      || tpm_marshal_UINT32(&ptr, &len, VTPM_ORD_SAVENVM)
-+      || tpm_marshal_BYTE_ARRAY(&ptr, &len, data, data_length)) {
-+    free(out_data);
-+    return -1;
-+  }
-+ 
-+  printf("\tSending SaveNVM Command.\n");
-+  res = write(vtpm_tx_fh, out_data, out_data_size);
-+  free(out_data);
-+  if (res != out_data_size) return -1;
-+
-+  if (vtpm_rx_fh < 0) {
-+#ifdef VTPM_MUTLI_VM
-+    vtpm_rx_fh = vtpm_tx_fh
-+#else
-+    if (vtpm_rx_name == NULL) {
-+      vtpm_rx_name = malloc(10 + strlen(VTPM_RX_FIFO_D));
-+      sprintf(vtpm_rx_name, VTPM_RX_FIFO_D, (uint32_t) dmi_id);
-     }
--    close(fh);
--    return 0;
-+    vtpm_rx_fh = open(vtpm_rx_name, O_RDONLY);
-+#endif
-+  }
-+
-+  if (vtpm_rx_fh < 0) {
-+        return -1;
-+  }
-+ 
-+  // Read Header of response so we can get the size & status
-+#ifdef VTPM_MUTLI_VM
-+  in_header_size = len = VTPM_COMMAND_HEADER_SIZE_CLT;
-+#else
-+  in_header_size = len = VTPM_COMMAND_HEADER_SIZE_SRV;
-+#endif
-+  in_header = ptr = malloc(in_header_size);
-+ 
-+  printf("\tReading SaveNVM header.\n");
-+  res = read(vtpm_rx_fh, in_header, in_header_size);
-+
-+  if ( (res != in_header_size)
-+#ifndef VTPM_MUTLI_VM
-+       || tpm_unmarshal_UINT32(&ptr, &len, (UINT32*)&dmi_id)
-+#endif
-+       || tpm_unmarshal_UINT16(&ptr, &len, &tag)
-+       || tpm_unmarshal_UINT32(&ptr, &len, &in_rsp_size)
-+       || tpm_unmarshal_UINT32(&ptr, &len, &result) ) {
-+      free(in_header);
-+      return -1;
-+  }
-+  free(in_header);
-+ 
-+  if (result != VTPM_SUCCESS) {
-+      return -1; 
-+  }
-+
-+#ifdef VTPM_MUTLI_VM
-+  close(vtpm_tx_fh); close(vtpm_rx_fh);
-+#endif
-+     
-+  printf("\tFinishing up SaveNVM\n");
-+  return (0);
- }
-
- int tpm_read_from_file(uint8_t **data, size_t *data_length)
- {
--    int fh;
--    ssize_t res;
--    size_t total_length;
--    fh = open(opt_storage_file, O_RDONLY);
--    if (fh < 0) return -1;
--    total_length = lseek(fh, 0, SEEK_END);
--    lseek(fh, 0, SEEK_SET);
--    *data = tpm_malloc(total_length);
--    if (*data == NULL) {
--        close(fh);
--        return -1;
--    }
--    *data_length = 0;
--    while (total_length > 0) {
--        res = read(fh, &(*data)[*data_length], total_length);
--    if (res < 0) {
--        close(fh);
--        tpm_free(*data);
--        return -1;
--    }
--        *data_length += res;
--    total_length -= res;
-+  int res, out_data_size, in_header_size;
-+  uint8_t *ptr, *out_data, *in_header;
-+  UINT16 tag = VTPM_TAG_REQ;
-+  UINT32 len, in_rsp_size, result;
-+#ifdef VTPM_MUTLI_VM
-+    int vtpm_rx_fh, vtpm_tx_fh;
-+#endif
-+   
-+  printf("Loading NVM.\n");
-+  if (vtpm_tx_fh < 0) {
-+#ifdef VTPM_MUTLI_VM
-+    vtpm_tx_fh = open(DEV_FE, O_RDWR);
-+#else
-+    vtpm_tx_fh = open(VTPM_TX_FIFO, O_WRONLY);
-+#endif
-+  }
-+
-+  if (vtpm_tx_fh < 0) {
-+    printf("Error in read_from_file:301\n");
-+        return -1;
-+  }
-+
-+  // Send request to VTPM Manager to encrypt data
-+#ifdef VTPM_MUTLI_VM
-+  out_data_size = len = VTPM_COMMAND_HEADER_SIZE_CLT;
-+#else
-+  out_data_size = len = VTPM_COMMAND_HEADER_SIZE_SRV;
-+#endif
-+  out_data = ptr = (BYTE *) malloc(len);
-+
-+  if (ptr == NULL
-+#ifndef VTPM_MUTLI_VM
-+      || tpm_marshal_UINT32(&ptr, &len, dmi_id)
-+#endif 
-+      || tpm_marshal_UINT16(&ptr, &len, tag)
-+#ifdef VTPM_MUTLI_VM
-+      || tpm_marshal_UINT32(&ptr, &len, out_data_size)
-+#else
-+      || tpm_marshal_UINT32(&ptr, &len, out_data_size - sizeof(uint32_t))
-+#endif
-+      || tpm_marshal_UINT32(&ptr, &len, VTPM_ORD_LOADNVM)) {
-+    free(out_data);
-+    printf("Error in read_from_file:325\n");
-+
-+    return -1;
-+  }
-+
-+  printf("\tSending LoadNVM command\n");
-+  res = write(vtpm_tx_fh, out_data, out_data_size);
-+  free(out_data);
-+  if (res != out_data_size)
-+    {
-+    printf("Error in read_from_file:335\n");
-+    return -1;
-+    }
-+
-+    if (vtpm_rx_fh < 0) {
-+#ifdef VTPM_MUTLI_VM
-+    vtpm_rx_fh = vtpm_tx_fh;
-+#else
-+    if (vtpm_rx_name == NULL) {
-+      vtpm_rx_name = malloc(10 + strlen(VTPM_RX_FIFO_D));
-+      sprintf(vtpm_rx_name, VTPM_RX_FIFO_D, (uint32_t) dmi_id);
-     }
--    close(fh);
--    return 0;
-+    vtpm_rx_fh = open(vtpm_rx_name, O_RDONLY);
-+#endif
-+  }
-+
-+  if (vtpm_rx_fh < 0) {
-+    printf("Error in read_from_file:352\n");   
-+    return -1;
-+  }
-+ 
-+  // Read Header of response so we can get the size & status
-+#ifdef VTPM_MUTLI_VM
-+  in_header_size = len = VTPM_COMMAND_HEADER_SIZE_CLT;
-+#else
-+  in_header_size = len = VTPM_COMMAND_HEADER_SIZE_SRV;
-+#endif
-+  in_header = ptr = malloc(in_header_size);
-+ 
-+  printf("\tReading LoadNVM header\n");
-+  res = read(vtpm_rx_fh, in_header, in_header_size);
-+
-+  if ( (res != in_header_size)
-+#ifndef VTPM_MUTLI_VM
-+       || tpm_unmarshal_UINT32(&ptr, &len, (UINT32*)&dmi_id)
-+#endif
-+       || tpm_unmarshal_UINT16(&ptr, &len, &tag)
-+       || tpm_unmarshal_UINT32(&ptr, &len, &in_rsp_size)
-+       || tpm_unmarshal_UINT32(&ptr, &len, &result) ) {
-+      free(in_header);
-+      printf("Error in read_from_file:375\n");    
-+      return -1;
-+  }
-+  free(in_header);
-+ 
-+  if (result != VTPM_SUCCESS) {
-+    printf("Error in read_from_file:381\n");
-+    return -1; 
-+  }
-+
-+  // Read Encrypted data from VTPM Manager
-+  *data_length = in_rsp_size - VTPM_COMMAND_HEADER_SIZE_CLT;
-+  *data = (uint8_t *) malloc(*data_length);
-+
-+  printf("\tReading clear data from LoadNVM.\n");
-+  res = read(vtpm_rx_fh, *data, *data_length);
-+#ifdef VTPM_MUTLI_VM
-+  close(vtpm_rx_fh);close(vtpm_tx_fh);
-+#endif
-+   
-+  printf("\tReturing from loading NVM\n");
-+  if (res != (int)*data_length) {
-+      free(*data);
-+      printf("Error in read_from_file:398\n");
-+      return -1;
-+  } else {
-+      return 0;
-+  }
-+
-+
-+   
- }
-
- static void print_usage(char *name)
- {
-     printf("usage: %s [-d] [-f] [-s storage file] [-u unix socket name] "
--           "[-o user name] [-g group name] [-h] [startup mode]\n", name);
-+           "[-o user name] [-g group name] [-h]"
-+#ifdef VTPM_MULTI_VM
-+       "clear|save|deactivated\n", name);
-+#else
-+       "clear|save|deactivated pvm|hvm vtpmid\n", name);
-+#endif
-     printf("  d : enable debug mode\n");
-     printf("  f : forces the application to run in the foreground\n");
-     printf("  s : storage file to use (default: %s)\n", opt_storage_file);
-@@ -205,7 +413,13 @@ static void parse_options(int argc, char
-                 exit(EXIT_SUCCESS);
-         }
-     }
--    if (optind < argc) {
-+    /*Make sure we have all required options*/
-+#ifdef VTPM_MULTI_VM
-+#define EXTRA_OPTS 0
-+#else
-+#define EXTRA_OPTS 2
-+#endif
-+    if (optind < argc - EXTRA_OPTS ) {
-         debug("startup mode = '%s'", argv[optind]);
-         if (!strcmp(argv[optind], "clear")) {
-             tpm_startup = 1;
-@@ -219,6 +433,25 @@ static void parse_options(int argc, char
-             print_usage(argv[0]);
-             exit(EXIT_SUCCESS);
-         }
-+#ifndef VTPM_MULTI_VM
-+        ++optind;
-+    if(!strcmp(argv[optind], "pvm")) {
-+        vtpm_type = VTPM_TYPE_PVM;    // Get commands from vTPM
Manager through fifo
-+    } else if (!strcmp(argv[optind], "hvm")) {
-+        vtpm_type = VTPM_TYPE_HVM;    // Get commands from qemu via socket
-+        } else {
-+        error("Invalid vm mode '%s'; must be 'pvm', "
-+            "or 'hvm' ", argv[optind]);
-+        print_usage(argv[0]);
-+        exit(EXIT_SUCCESS);
-+    }
-+        ++optind;
-+    dmi_id = atoi(argv[optind]);
-+#endif
-+    } else {
-+    error("Invalid number of arguments");
-+    print_usage(argv[0]);
-+    exit(EXIT_SUCCESS);
-     }
- }
-
-@@ -348,93 +581,180 @@ static int init_socket(const char *name)
-
- static void main_loop(void)
- {
--    int sock, fh, res;
--    int32_t in_len;
-+    int32_t in_len, written;
-     uint32_t out_len;
--    uint8_t in[TPM_CMD_BUF_SIZE], *out;
-+    uint8_t in[TPM_CMD_BUF_SIZE], *out, *addressed_out;
-+    int guest_id=-1;
-+    int i;
-+    char *vtpm_rx_file=NULL;
-+    int res;
-+
-+#ifndef VTPM_MULTI_VM
-+    int sockfd = -1;
-     struct sockaddr_un addr;
--    socklen_t addr_len;
--    fd_set rfds;
--    struct timeval tv;
-+    struct sockaddr_un client_addr;
-+    unsigned int client_length;
-+#endif
-+
-+    int vtpm_tx_fh=-1, vtpm_rx_fh=-1;
-+
-+#ifndef VTPM_MULTI_VM
-+  if (vtpm_type == VTPM_TYPE_PVM) {
-+    vtpm_rx_file = malloc(10 + strlen(PVM_RX_FIFO_D));
-+    sprintf(vtpm_rx_file, PVM_RX_FIFO_D, (uint32_t) dmi_id);
-+  } else {
-+    vtpm_rx_file = malloc(10 + strlen(HVM_RX_FIFO_D));
-+    sprintf(vtpm_rx_file, HVM_RX_FIFO_D, (uint32_t) dmi_id);
-+
-+    if ( (sockfd = socket(PF_UNIX,SOCK_STREAM,0)) < 0) {
-+          error("Unable to create socket. errno = %d\n", errno);
-+      exit (-1);
-+    }
-+
-+    memset(&addr, 0, sizeof(addr));
-+    addr.sun_family = AF_UNIX;
-+    strcpy(addr.sun_path,vtpm_rx_file );
-+    unlink(addr.sun_path);
-+  }
-+#endif
-
-     info("staring main loop");
--    /* open UNIX socket */
--    sock = init_socket(opt_socket_name);
--    if (sock < 0) exit(EXIT_FAILURE);
-     /* init tpm emulator */
--    debug("initializing TPM emulator: %d", tpm_startup);
-+#ifdef VTPM_MULTI_VM
-+    debug("initializing TPM emulator: state=%d", tpm_startup);
-+#else
-+    debug("initializing TPM emulator: state=%d, type=%d, id=%d",
tpm_startup, vtpm_type, dmi_id);
-+#endif
-     tpm_emulator_init(tpm_startup);
-     /* start command processing */
-     while (!stopflag) {
-         /* wait for incomming connections */
-         debug("waiting for connections...");
--        FD_ZERO(&rfds);
--        FD_SET(sock, &rfds);
--        tv.tv_sec = 10;
--        tv.tv_usec = 0;
--        res = select(sock + 1, &rfds, NULL, NULL, &tv);
--        if (res < 0) {
--            error("select(sock) failed: %s", strerror(errno));
--            break;
--        } else if (res == 0) {
--            continue;
--        }
--        addr_len = sizeof(addr);
--        fh = accept(sock, (struct sockaddr*)&addr, &addr_len);
--        if (fh < 0) {
--            error("accept() failed: %s", strerror(errno));
--            continue;
--        }
-+    if (vtpm_rx_fh < 0) {
-+#ifdef VTPM_MUTLI_VM
-+        vtpm_rx_fh = open(DEV_BE, O_RDWR);
-+#else
-+        if (vtpm_type == VTPM_TYPE_PVM)
-+        {
-+        vtpm_rx_fh = open(vtpm_rx_file, O_RDONLY);
-+        } else {
-+        if (bind(sockfd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
-+            error("Unable to bind(). errno = %d\n", errno);
-+            exit (-1);
-+        }
-+
-+        if (listen(sockfd, 10) <0) {
-+            error("Unable to listen(). errno = %d\n", errno);
-+            exit (-1);
-+        }
-+
-+         memset(&client_addr, 0, sizeof(client_addr));
-+         client_length = sizeof(client_addr);
-+
-+         vtpm_rx_fh = vtpm_tx_fh = accept(sockfd, (struct sockaddr
*)&client_addr, &client_length);
-+        }
-+#endif
-+    }
-+   
-+    /*Error Checking*/
-+    if (vtpm_rx_fh < 0) {
-+      error("Failed to open devices to listen to guest.\n");
-+      exit(-1);
-+    }
-+
-         /* receive and handle commands */
-         in_len = 0;
-         do {
-             debug("waiting for commands...");
--            FD_ZERO(&rfds);
--            FD_SET(fh, &rfds);
--            tv.tv_sec = TPM_COMMAND_TIMEOUT;
--            tv.tv_usec = 0;
--            res = select(fh + 1, &rfds, NULL, NULL, &tv);
--            if (res < 0) {
--                error("select(fh) failed: %s", strerror(errno));
--                close(fh);
--                break;
--            } else if (res == 0) {
--#ifdef TPMD_DISCONNECT_IDLE_CLIENTS       
--                info("connection closed due to inactivity");
--                close(fh);
--                break;
--#else       
--                continue;
--#endif       
--            }
--            in_len = read(fh, in, sizeof(in));
--            if (in_len > 0) {
-+
-+            in_len = read(vtpm_rx_fh, in, sizeof(in));
-+        /*Magic size of minimum TPM command is 6*/
-+        //FIXME Magic size check may not be required anymore
-+            if (in_len < 6) {
-+        info("Recv incomplete command of %d bytes.", in_len);
-+        if (in_len <= 0) {
-+            close(vtpm_rx_fh);
-+            vtpm_rx_fh = -1;
-+            continue;
-+                 }
-+        } else {
-+        /*Debug Printouts*/
-                 debug("received %d bytes", in_len);
-+        debug_nostop("Recv[%d]: 0x", in_len);
-+        for (i=0; i< in_len; i++)
-+            debug_more("%x ", in[i]);
-+        debug_more("\n");
-+        /*Multiple Guest check*/
-+        if (guest_id == -1) {
-+            guest_id = *((int32_t *) in);
-+        } else {
-+            if (guest_id != *((int32_t *) in) ) {
-+            error("WARNING: More than one guest attached\n");
-+            }
-+        }
-+
-+        /*Open tx handle now*/
-+        if (vtpm_tx_fh < 0) {
-+#ifdef VTPM_MUTLI_VM
-+            vtpm_tx_fh = open(DEV_BE, O_RDWR);
-+            vtpm_rx_fh = vtpm_tx_fh;
-+#else
-+            if (vtpm_type == VTPM_TYPE_PVM) {
-+            vtpm_tx_fh = open(PVM_TX_FIFO, O_WRONLY);
-+                 } // No need to open the other direction for HVM
-+#endif
-+        }
-+        if (vtpm_tx_fh < 0) {
-+          error("Failed to open devices to respond to guest.\n");
-+          exit(-1);
-+        }
-+
-+        /*Handle the TPM command now*/
-                 out = NULL;
--                res = tpm_handle_command(in, in_len, &out, &out_len);
-+                res = tpm_handle_command(in + sizeof(uint32_t), in_len
- sizeof(uint32_t), &out, &out_len);
-                 if (res < 0) {
-                     error("tpm_handle_command() failed");
-                 } else {
-                     debug("sending %d bytes", out_len);
-+            //FIXME this prepending may or may not be needed
-+            /*Prepend the first 4 bytes of the in buffer.. why?*/
-+            addressed_out = (uint8_t *) tpm_malloc(sizeof(uint32_t) +
out_len);
-+            *(uint32_t *) addressed_out = *(uint32_t *) in;
-+            memcpy(addressed_out + sizeof(uint32_t), out, out_len);
-+            out_len += sizeof(uint32_t);
-+            /*End Prepend*/
-+
-+            /*Perform write operation now*/
-                     while (out_len > 0) {
--                        res = write(fh, out, out_len);
-+                        res = write(vtpm_tx_fh, addressed_out, out_len);
-+
-                         if (res < 0) {
-                             error("write(%d) failed: %s", out_len,
strerror(errno));
-                             break;
--                        }
-+                        } else {
-+              debug_nostop("Sent[%Zu]: ", out_len);
-+              for (i=0; (unsigned int)i< out_len; i++)
-+                debug_more("%x ", addressed_out[i]);
-+              debug_more("\n");
-+            }
-                         out_len    -= res;
-                     }
-                     tpm_free(out);
-+            tpm_free(addressed_out);
-                 }
-             }
-         } while (in_len > 0);
--        close(fh);
-+        //close(fh);
-     }
-+   
-     /* shutdown tpm emulator */
-     tpm_emulator_shutdown();
--    /* close socket */
--    close(sock);
--    unlink(opt_socket_name);
-+    /* Close handles */
-+    close(vtpm_tx_fh);
-+#ifndef VTPM_MULTI_VM
-+    close(vtpm_rx_fh);
-+    free(vtpm_rx_file);
-+#endif
-     info("main loop stopped");
- }
-
-@@ -450,12 +770,13 @@ int main(int argc, char **argv)
-     /* open random device */
-     init_random();
-     /* init signal handlers */
--    init_signal_handler();
-+    //init_signal_handler();
-     /* unless requested otherwiese, fork and daemonize process */
--    if (!opt_foreground) daemonize();
-+    //if (!opt_foreground) daemonize();
-     /* start main processing loop */
-     main_loop();
-     info("stopping TPM Emulator daemon");
-     closelog();
-     return 0;
- }
-+
-diff -Naurp tpm_emulator-0.5.1/tpmd/tpm_emulator_config.h
tpm5-test/tpmd/tpm_emulator_config.h
---- tpm_emulator-0.5.1/tpmd/tpm_emulator_config.h    2008-02-14
03:22:48.000000000 -0500
-+++ tpm5-test/tpmd/tpm_emulator_config.h    2009-07-16
11:25:26.000000000 -0400
-@@ -29,23 +29,28 @@
-
- /* TPM emulator configuration */
-
--#undef  TPM_STRONG_PERSISTENCE
--#undef  TPM_GENERATE_EK
-+#define  TPM_STRONG_PERSISTENCE
-+#define  TPM_GENERATE_EK
- #undef  TPM_GENERATE_SEED_DAA
- #undef  TPM_MEMORY_ALIGNMENT_MANDATORY
-
-+extern int dmi_id;
-+
- /* log macros */
-
- void tpm_log(int priority, const char *fmt, ...);
-
--#define debug(fmt, ...) tpm_log(LOG_DEBUG, "%s:%d: Debug: " fmt "\n", \
--                                __FILE__, __LINE__, ## __VA_ARGS__)
--#define info(fmt, ...)  tpm_log(LOG_INFO, "%s:%d: Info: " fmt "\n", \
--                                __FILE__, __LINE__, ## __VA_ARGS__)
--#define error(fmt, ...) tpm_log(LOG_ERR, "%s:%d: Error: " fmt "\n", \
--                                __FILE__, __LINE__, ## __VA_ARGS__)
--#define alert(fmt, ...) tpm_log(LOG_ALERT, "%s:%d: Alert: " fmt "\n", \
--                                __FILE__, __LINE__, ## __VA_ARGS__)
-+#define debug(fmt, ...) tpm_log(LOG_DEBUG, "VTPMD[%d]: %s:%d: Debug: "
fmt "\n", \
-+                                dmi_id, __FILE__, __LINE__, ##
__VA_ARGS__)
-+#define info(fmt, ...)  tpm_log(LOG_INFO, "VTPMD[%d]: %s:%d: Info: "
fmt "\n", \
-+                                dmi_id, __FILE__, __LINE__, ##
__VA_ARGS__)
-+#define error(fmt, ...) tpm_log(LOG_ERR, "VTPMD[%d]: %s:%d: Error: "
fmt "\n", \
-+                                dmi_id, __FILE__, __LINE__, ##
__VA_ARGS__)
-+#define alert(fmt, ...) tpm_log(LOG_ALERT, "VTPMD[%d]: %s:%d: Alert: "
fmt "\n", \
-+                                dmi_id, __FILE__, __LINE__, ##
__VA_ARGS__)
-+#define debug_nostop(fmt, ...) tpm_log(LOG_DEBUG, "VTPMD[%d]: %s:%d:
Debug: " fmt, \
-+                                dmi_id, __FILE__, __LINE__, ##
__VA_ARGS__)
-+#define debug_more(fmt, ...) tpm_log(LOG_DEBUG, fmt, ## __VA_ARGS__)
-
- /*  min/max macros that also do strict type-checking */
-
diff --git a/tools/vtpm/vtpm-0.7.4.patch b/tools/vtpm/vtpm-0.7.4.patch
--- /dev/null
+++ b/tools/vtpm/vtpm-0.7.4.patch
@@ -0,0 +1,1138 @@
+diff -Naur tpm_emulator-0.7.4-orig/CMakeLists.txt
tpm_emulator-0.7.4/CMakeLists.txt
+--- tpm_emulator-0.7.4-orig/CMakeLists.txt    2012-09-17
13:16:27.832582475 -0400
++++ tpm_emulator-0.7.4/CMakeLists.txt    2012-09-17 13:16:41.621654594
-0400
+@@ -63,6 +63,7 @@
+ # include root directories
+ include_directories(${CMAKE_SOURCE_DIR})
+ include_directories(${CMAKE_BINARY_DIR})
++include_directories(../../vtpm_manager/manager)
+
+ # add internal libraries
+ add_subdirectory(tpm)
+diff -Naur tpm_emulator-0.7.4-orig/CMakeLists.txt.orig
tpm_emulator-0.7.4/CMakeLists.txt.orig
+--- tpm_emulator-0.7.4-orig/CMakeLists.txt.orig    1969-12-31
19:00:00.000000000 -0500
++++ tpm_emulator-0.7.4/CMakeLists.txt.orig    2011-12-20
13:30:06.000000000 -0500
+@@ -0,0 +1,80 @@
++# Software-based Trusted Platform Module (TPM) Emulator
++# Copyright (C) 2004-2010 Mario Strasser <mast@xxxxxxx>
++#
++# $Id: CMakeLists.txt 475 2011-12-20 18:21:19Z mast $
++
++project(TPM_Emulator C)
++
++cmake_minimum_required(VERSION 2.4)
++set(CMAKE_ALLOW_LOOSE_LOOP_CONSTRUCTS true)
++if(COMMAND cmake_policy)
++cmake_policy(SET CMP0003 NEW)
++endif()
++
++# enforce out of source build
++string(COMPARE EQUAL "${CMAKE_SOURCE_DIR}" "${CMAKE_BINARY_DIR}"
IS_INSOURCE)
++if(IS_INSOURCE)
++    message(FATAL_ERROR "${PROJECT_NAME} requires an out of source
build.")
++endif()
++
++# set project and build version
++set(${PROJECT_NAME}_VERSION_MAJOR 0)
++set(${PROJECT_NAME}_VERSION_MINOR 7)
++string(REGEX REPLACE ".*Revision: ([0-9]+).*" "\\1"
${PROJECT_NAME}_VERSION_BUILD "$Revision: 475 $")
++
++# create project configuration
++if(WIN32)
++STRING(REGEX REPLACE "\\\\" "/" PROGRAMFILES
"$ENV{PROGRAMFILES}/${PROJECT_NAME}")
++set(TPM_LOG_FILE "${PROGRAMFILES}/tpmd.log")
++set(TPM_STORAGE_NAME
"${PROGRAMFILES}/tpm_emulator-1_2_${${PROJECT_NAME}_VERSION_MAJOR}_${${PROJECT_NAME}_VERSION_MINOR}")
++set(TPM_DEVICE_NAME "//./pipe/tpmd:0")
++elseif(APPLE)
++set(TPM_LOG_FILE "/private/var/log/tpmd.log")
++set(TPM_SOCKET_NAME "/private/var/run/tpm/tpmd_socket:0")
++set(TPM_STORAGE_NAME
"/private/var/lib/tpm/tpm_emulator-1_2_${${PROJECT_NAME}_VERSION_MAJOR}_${${PROJECT_NAME}_VERSION_MINOR}")
++set(TPM_DEVICE_NAME "/dev/tpm")
++else()
++set(TPM_LOG_FILE "/var/log/tpmd.log")
++set(TPM_SOCKET_NAME "/var/run/tpm/tpmd_socket:0")
++set(TPM_STORAGE_NAME
"/var/lib/tpm/tpm_emulator-1_2_${${PROJECT_NAME}_VERSION_MAJOR}_${${PROJECT_NAME}_VERSION_MINOR}")
++set(TPM_DEVICE_NAME "/dev/tpm")
++endif()
++configure_file(${CMAKE_CURRENT_SOURCE_DIR}/config.h.in
${CMAKE_CURRENT_BINARY_DIR}/config.h)
++add_definitions(-Wall -Werror -Wno-unused-parameter -Wpointer-arith
-Wcast-align -Wwrite-strings)
++if("${CMAKE_SYSTEM}" MATCHES "Linux")
++    add_definitions(-Wextra)
++endif()
++if(USE_OPENSSL)
++    add_definitions(-DUSE_OPENSSL)
++endif()
++include_directories("/opt/local/include")
++link_directories("/opt/local/lib")
++
++# configure CPack
++set(CPACK_PACKAGE_VERSION_MAJOR ${${PROJECT_NAME}_VERSION_MAJOR})
++set(CPACK_PACKAGE_VERSION_MINOR ${${PROJECT_NAME}_VERSION_MINOR})
++set(CPACK_SOURCE_PACKAGE_FILE_NAME
"tpm_emulator-${CPACK_PACKAGE_VERSION_MAJOR}.${CPACK_PACKAGE_VERSION_MINOR}.4")
++set(CPACK_SOURCE_GENERATOR "TGZ")
++set(CPACK_SOURCE_IGNORE_FILES ".svn/" "/build/" "/.project" "/.cproject")
++set(CPACK_GENERATOR "ZIP")
++set(CPACK_SET_DESTDIR ON)
++include(CPack)
++
++# include root directories
++include_directories(${CMAKE_SOURCE_DIR})
++include_directories(${CMAKE_BINARY_DIR})
++
++# add internal libraries
++add_subdirectory(tpm)
++add_subdirectory(mtm)
++add_subdirectory(crypto)
++
++# add TDDL
++add_subdirectory(tddl)
++
++# add kernel modules
++add_subdirectory(tpmd_dev)
++
++# add executables
++add_subdirectory(tpmd)
++
+diff -Naur tpm_emulator-0.7.4-orig/tpm/tpm_emulator_extern.h
tpm_emulator-0.7.4/tpm/tpm_emulator_extern.h
+--- tpm_emulator-0.7.4-orig/tpm/tpm_emulator_extern.h    2012-09-17
13:16:27.834582486 -0400
++++ tpm_emulator-0.7.4/tpm/tpm_emulator_extern.h    2012-09-17
13:16:41.621654594 -0400
+@@ -29,6 +29,8 @@
+   TPM_LOG_ERROR
+ };
+
++extern int dmi_id;
++
+ void (*tpm_log)(int priority, const char *fmt, ...);
+
+ #if defined(_WIN32) || defined(_WIN64)
+@@ -37,12 +39,16 @@
+ #define __BFILE__ ((strrchr(__FILE__, '/') ? : __FILE__ - 1) + 1)
+ #endif
+
+-#define debug(fmt, ...) tpm_log(TPM_LOG_DEBUG, "%s:%d: Debug: " fmt
"\n", \
+-                                __BFILE__, __LINE__, ## __VA_ARGS__)
+-#define info(fmt, ...)  tpm_log(TPM_LOG_INFO, "%s:%d: Info: " fmt "\n", \
+-                                __BFILE__, __LINE__, ## __VA_ARGS__)
+-#define error(fmt, ...) tpm_log(TPM_LOG_ERROR, "%s:%d: Error: " fmt
"\n", \
+-                                __BFILE__, __LINE__, ## __VA_ARGS__)
++#define debug(fmt, ...) tpm_log(TPM_LOG_DEBUG, "VTPMD[%d]: %s:%d:
Debug: " fmt "\n", \
++                                dmi_id, __BFILE__, __LINE__, ##
__VA_ARGS__)
++#define info(fmt, ...)  tpm_log(TPM_LOG_INFO, "VTPMD[%d]: %s:%d: Info:
" fmt "\n", \
++                                dmi_id, __BFILE__, __LINE__, ##
__VA_ARGS__)
++#define error(fmt, ...) tpm_log(TPM_LOG_ERROR, "VTPMD[%d]: %s:%d:
Error: " fmt "\n", \
++                                dmi_id, __BFILE__, __LINE__, ##
__VA_ARGS__)
++#define debug_nostop(fmt, ...) tpm_log(TPM_LOG_DEBUG, "VTPMD[%d]:
%s:%d: Debug: " fmt, \
++                                dmi_id, __BFILE__, __LINE__, ##
__VA_ARGS__)
++#define debug_more(fmt, ...) tpm_log(TPM_LOG_DEBUG, fmt, ## __VA_ARGS__)
++
+ /* initialization */
+ int (*tpm_extern_init)(void);
+ void (*tpm_extern_release)(void);
+diff -Naur tpm_emulator-0.7.4-orig/tpmd/unix/tpmd.c
tpm_emulator-0.7.4/tpmd/unix/tpmd.c
+--- tpm_emulator-0.7.4-orig/tpmd/unix/tpmd.c    2012-09-17
13:16:27.839582511 -0400
++++ tpm_emulator-0.7.4/tpmd/unix/tpmd.c    2012-09-17
13:16:41.623654604 -0400
+@@ -30,9 +30,31 @@
+ #include <grp.h>
+ #include "config.h"
+ #include "tpm/tpm_emulator.h"
++#include "tpm/tpm_structures.h"
++#include "tpm/tpm_marshalling.h"
++#include "vtpm_manager.h"
+
+ #define TPM_COMMAND_TIMEOUT 30
+
++#define TPM_DAEMON_NAME     "tpmd"
++#define TPM_CMD_BUF_SIZE    4096
++#define TPM_RANDOM_DEVICE   "/dev/urandom"
++#undef  TPM_MKDIRS
++
++#define PVM_RX_FIFO_D "/var/vtpm/fifos/tpm_cmd_to_%d.fifo"
++#define PVM_TX_FIFO "/var/vtpm/fifos/tpm_rsp_from_all.fifo"
++#define HVM_RX_FIFO_D "/var/vtpm/socks/%d.socket"
++
++#define VTPM_RX_FIFO_D "/var/vtpm/fifos/vtpm_rsp_to_%d.fifo"
++#define VTPM_TX_FIFO "/var/vtpm/fifos/vtpm_cmd_from_all.fifo"
++
++static char *vtpm_rx_name=NULL;
++
++static int vtpm_tx_fh=-1, vtpm_rx_fh=-1;
++
++#define BUFFER_SIZE 2048
++
++
+ static volatile int stopflag = 0;
+ static int is_daemon = 0;
+ static int opt_debug = 0;
+@@ -44,6 +66,9 @@
+ static uint32_t tpm_config = 0;
+ extern const char *tpm_storage_file;
+
++static int vtpm_type = VTPM_TYPE_PVM;
++int dmi_id;
++
+ void my_log(int priority, const char *fmt, ...)
+ {
+     va_list ap, bp;
+@@ -156,35 +181,218 @@
+             exit(EXIT_SUCCESS);
+         }
+     } else {
+-        /* if no startup mode is given assume save if a configuration
+-           file is available, clear otherwise */
+-        int fh = open(tpm_storage_file, O_RDONLY);
+-        if (fh < 0) {
+-            tpm_startup = 1;
+-            info("no startup mode was specified; asuming 'clear'");
+-        } else {
+-            tpm_startup = 2;
+-            close(fh);
+-        }
++       tpm_startup = 1;
++       info("no startup mode was specified; asuming 'clear'");
+     }
++    /* GET VM TYPE */
++    ++optind;
++    if (optind < argc) {
++       if(!strcmp(argv[optind], "pvm")) {
++      vtpm_type = VTPM_TYPE_PVM;      // Get commands from vTPM
Manager through fifo
++       } else if (!strcmp(argv[optind], "hvm")) {
++      vtpm_type = VTPM_TYPE_HVM;      // Get commands from qemu via socket
++       } else {
++      error("Invalid vm mode '%s'; must be 'pvm', "
++        "or 'hvm' ", argv[optind]);
++      print_usage(argv[0]);
++      exit(EXIT_SUCCESS);
++       }
++    } else {
++       vtpm_type = VTPM_TYPE_PVM;
++       info("no vm mode specified; assuming 'pvm'");
++    }
++    /* GET DMI ID */
++    ++optind;
++    if(optind >= argc || sscanf(argv[optind], "%d", &dmi_id) != 1) {
++       error("Missing or non-integer dmi_id specified!");
++       print_usage(argv[0]);
++       exit(EXIT_SUCCESS);
++    }
++}
++
++int vtpm_write_to_file(uint8_t *data, size_t data_length)
++{
++  int res, out_data_size, in_header_size;
++  BYTE *ptr, *out_data, *in_header;
++  UINT32 result, len, in_rsp_size;
++  UINT16 tag = VTPM_TAG_REQ;
++
++  printf("Saving NVM\n");
++  if (vtpm_tx_fh < 0) {
++     vtpm_tx_fh = open(VTPM_TX_FIFO, O_WRONLY);
++  }
++
++  if (vtpm_tx_fh < 0) {
++                return -1;
++  }
++
++  // Send request to VTPM Manager to encrypt data
++  out_data_size = len = VTPM_COMMAND_HEADER_SIZE_SRV + data_length;
++
++  out_data = ptr = (BYTE *) malloc(len);
++
++  if (ptr == NULL
++    || tpm_marshal_UINT32(&ptr, &len, dmi_id)
++    || tpm_marshal_UINT16(&ptr, &len, tag)
++    || tpm_marshal_UINT32(&ptr, &len, out_data_size - sizeof(uint32_t))
++    || tpm_marshal_UINT32(&ptr, &len, VTPM_ORD_SAVENVM)
++    || tpm_marshal_BYTE_ARRAY(&ptr, &len, data, data_length)) {
++     free(out_data);
++     return -1;
++  }
++
++  printf("\tSending SaveNVM Command.\n");
++  res = write(vtpm_tx_fh, out_data, out_data_size);
++  free(out_data);
++  if (res != out_data_size) return -1;
++
++  if (vtpm_rx_fh < 0) {
++    if (vtpm_rx_name == NULL) {
++      vtpm_rx_name = malloc(10 + strlen(VTPM_RX_FIFO_D));
++      sprintf(vtpm_rx_name, VTPM_RX_FIFO_D, (uint32_t) dmi_id);
++    }
++        vtpm_rx_fh = open(vtpm_rx_name, O_RDONLY);
++  }
++
++  if (vtpm_rx_fh < 0) {
++                return -1;
++  }
++
++  // Read Header of response so we can get the size & status
++  in_header_size = len = VTPM_COMMAND_HEADER_SIZE_SRV;
++  in_header = ptr = malloc(in_header_size);
++
++  printf("\tReading SaveNVM header.\n");
++  res = read(vtpm_rx_fh, in_header, in_header_size);
++
++  if ( (res != in_header_size)
++    || tpm_unmarshal_UINT32(&ptr, &len, (UINT32*)&dmi_id)
++    || tpm_unmarshal_UINT16(&ptr, &len, &tag)
++    || tpm_unmarshal_UINT32(&ptr, &len, &in_rsp_size)
++    || tpm_unmarshal_UINT32(&ptr, &len, &result) ) {
++     free(in_header);
++     return -1;
++  }
++  free(in_header);
++
++  if (result != VTPM_SUCCESS) {
++      return -1;
++  }
++
++  printf("\tFinishing up SaveNVM\n");
++  return (0);
++}
++
++int vtpm_read_from_file(uint8_t **data, size_t *data_length)
++{
++   int res, out_data_size, in_header_size;
++   uint8_t *ptr, *out_data, *in_header;
++   UINT16 tag = VTPM_TAG_REQ;
++   UINT32 len, in_rsp_size, result;
++
++   printf("Loading NVM.\n");
++   if (vtpm_tx_fh < 0) {
++      vtpm_tx_fh = open(VTPM_TX_FIFO, O_WRONLY);
++   }
++
++   if (vtpm_tx_fh < 0) {
++      printf("Error in read_from_file:301\n");
++      return -1;
++   }
++
++   // Send request to VTPM Manager to encrypt data
++   out_data_size = len = VTPM_COMMAND_HEADER_SIZE_SRV;
++   out_data = ptr = (BYTE *) malloc(len);
++
++   if (ptr == NULL
++     || tpm_marshal_UINT32(&ptr, &len, dmi_id)
++     || tpm_marshal_UINT16(&ptr, &len, tag)
++     || tpm_marshal_UINT32(&ptr, &len, out_data_size - sizeof(uint32_t))
++     || tpm_marshal_UINT32(&ptr, &len, VTPM_ORD_LOADNVM)) {
++      free(out_data);
++      printf("Error in read_from_file:325\n");
++
++      return -1;
++   }
++
++   printf("\tSending LoadNVM command\n");
++   res = write(vtpm_tx_fh, out_data, out_data_size);
++   free(out_data);
++   if (res != out_data_size)
++   {
++      printf("Error in read_from_file:335\n");
++      return -1;
++   }
++
++   if (vtpm_rx_fh < 0) {
++      if (vtpm_rx_name == NULL) {
++     vtpm_rx_name = malloc(10 + strlen(VTPM_RX_FIFO_D));
++     sprintf(vtpm_rx_name, VTPM_RX_FIFO_D, (uint32_t) dmi_id);
++      }
++      vtpm_rx_fh = open(vtpm_rx_name, O_RDONLY);
++   }
++
++   if (vtpm_rx_fh < 0) {
++      printf("Error in read_from_file:352\n");
++      return -1;
++   }
++
++   // Read Header of response so we can get the size & status
++   in_header_size = len = VTPM_COMMAND_HEADER_SIZE_SRV;
++   in_header = ptr = malloc(in_header_size);
++
++   printf("\tReading LoadNVM header\n");
++   res = read(vtpm_rx_fh, in_header, in_header_size);
++
++   if ( (res != in_header_size)
++     || tpm_unmarshal_UINT32(&ptr, &len, (UINT32*)&dmi_id)
++     || tpm_unmarshal_UINT16(&ptr, &len, &tag)
++     || tpm_unmarshal_UINT32(&ptr, &len, &in_rsp_size)
++     || tpm_unmarshal_UINT32(&ptr, &len, &result) ) {
++      free(in_header);
++      printf("Error in read_from_file:375\n");
++      return -1;
++   }
++   free(in_header);
++
++   if (result != VTPM_SUCCESS) {
++      printf("Error in read_from_file:381\n");
++      return -1;
++   }
++
++   // Read Encrypted data from VTPM Manager
++   *data_length = in_rsp_size - VTPM_COMMAND_HEADER_SIZE_CLT;
++   *data = (uint8_t *) malloc(*data_length);
++
++   printf("\tReading clear data from LoadNVM.\n");
++   res = read(vtpm_rx_fh, *data, *data_length);
++
++   printf("\tReturing from loading NVM\n");
++   if (res != (int)*data_length) {
++      free(*data);
++      printf("Error in read_from_file:398\n");
++      return -1;
++   } else {
++      return 0;
++   }
+ }
+
+ static void switch_uid_gid(void)
+ {
+-    if (opt_gid != getgid()) {
+-        info("switching effective group ID to %d", opt_gid);
+-        if (setgid(opt_gid) == -1) {
+-            error("switching effective group ID to %d failed: %s",
opt_gid, strerror(errno));
+-            exit(EXIT_FAILURE);
+-        }
+-    }
+-    if (opt_uid != getuid()) {
+-        info("switching effective user ID to %d", opt_uid);
+-        if (setuid(opt_uid) == -1) {
+-            error("switching effective user ID to %d failed: %s",
opt_uid, strerror(errno));
+-            exit(EXIT_FAILURE);
+-        }
+-    }
++   if (opt_gid != getgid()) {
++      info("switching effective group ID to %d", opt_gid);
++      if (setgid(opt_gid) == -1) {
++     error("switching effective group ID to %d failed: %s", opt_gid,
strerror(errno));
++     exit(EXIT_FAILURE);
++      }
++   }
++   if (opt_uid != getuid()) {
++      info("switching effective user ID to %d", opt_uid);
++      if (setuid(opt_uid) == -1) {
++     error("switching effective user ID to %d failed: %s", opt_uid,
strerror(errno));
++     exit(EXIT_FAILURE);
++      }
++   }
+ }
+
+ static void signal_handler(int sig)
+@@ -214,174 +422,175 @@
+     }
+ }
+
+-static void daemonize(void)
+-{
+-    pid_t sid, pid;
+-    info("daemonizing process");
+-    pid = fork();
+-    if (pid < 0) {
+-        error("fork() failed: %s", strerror(errno));
+-        exit(EXIT_FAILURE);
+-    }
+-    if (pid > 0) exit(EXIT_SUCCESS);
+-    pid = getpid();
+-    sid = setsid();
+-    if (sid < 0) {
+-        error("setsid() failed: %s", strerror(errno));
+-        exit(EXIT_FAILURE);
+-    }
+-    if (chdir("/") < 0) {
+-        error("chdir() failed: %s", strerror(errno));
+-        exit(EXIT_FAILURE);
+-    }
+-    close(STDIN_FILENO);
+-    close(STDOUT_FILENO);
+-    close(STDERR_FILENO);
+-    is_daemon = 1;
+-    info("process was successfully daemonized: pid=%d sid=%d", pid, sid);
+-}
+-
+-static int mkdirs(const char *path)
+-{
+-    char *copy = strdup(path);
+-    char *p = strchr(copy + 1, '/');
+-    while (p != NULL) {
+-        *p = '\0';
+-        if ((mkdir(copy, 0755) == -1) && (errno != EEXIST)) {
+-            free(copy);
+-            return errno;
+-        }
+-        *p = '/';
+-        p = strchr(p + 1, '/');
+-    }
+-    free(copy);
+-    return 0;
+-}
+-
+-static int init_socket(const char *name)
+-{
+-    int sock;
+-    struct sockaddr_un addr;
+-    info("initializing socket %s", name);
+-    sock = socket(AF_UNIX, SOCK_STREAM, 0);
+-    if (sock < 0) {
+-        error("socket(AF_UNIX) failed: %s", strerror(errno));
+-        return -1;
+-    }
+-    mkdirs(name);
+-    addr.sun_family = AF_UNIX;
+-    strncpy(addr.sun_path, name, sizeof(addr.sun_path));
+-    umask(0177);
+-    if (bind(sock, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
+-        error("bind(%s) failed: %s", addr.sun_path, strerror(errno));
+-        close(sock);
+-        return -1;
+-    }
+-    listen(sock, 1);
+-    return sock;
+-}
+-
+ static void main_loop(void)
+ {
+-    int sock, fh, res;
+     int32_t in_len;
+     uint32_t out_len;
+-    uint8_t in[TPM_CMD_BUF_SIZE], *out;
++    uint8_t in[TPM_CMD_BUF_SIZE], *out, *addressed_out;
++    int guest_id=-1;
++    int i;
++    char *vtpm_rx_file=NULL;
++    int res;
++
++    int sockfd = -1;
+     struct sockaddr_un addr;
+-    socklen_t addr_len;
+-    fd_set rfds;
+-    struct timeval tv;
++    struct sockaddr_un client_addr;
++    unsigned int client_length;
++
++    int vtpm_tx_fh=-1, vtpm_rx_fh=-1;
++
++  if (vtpm_type == VTPM_TYPE_PVM) {
++    vtpm_rx_file = malloc(10 + strlen(PVM_RX_FIFO_D));
++    sprintf(vtpm_rx_file, PVM_RX_FIFO_D, (uint32_t) dmi_id);
++  } else {
++    vtpm_rx_file = malloc(10 + strlen(HVM_RX_FIFO_D));
++    sprintf(vtpm_rx_file, HVM_RX_FIFO_D, (uint32_t) dmi_id);
++
++    if ( (sockfd = socket(PF_UNIX,SOCK_STREAM,0)) < 0) {
++          error("Unable to create socket. errno = %d\n", errno);
++      exit (-1);
++    }
++
++    memset(&addr, 0, sizeof(addr));
++    addr.sun_family = AF_UNIX;
++    strcpy(addr.sun_path,vtpm_rx_file );
++    unlink(addr.sun_path);
++  }
+
+     info("staring main loop");
+-    /* open UNIX socket */
+-    sock = init_socket(opt_socket_name);
+-    if (sock < 0) exit(EXIT_FAILURE);
+     /* init tpm emulator */
+-    debug("initializing TPM emulator");
+-    if (tpm_emulator_init(tpm_startup, tpm_config) != 0) {
+-        error("tpm_emulator_init() failed");
+-        close(sock);
+-        unlink(opt_socket_name);
+-        exit(EXIT_FAILURE);
+-    }
++    debug("initializing TPM emulator: state=%d, type=%d, id=%d",
tpm_startup, vtpm_type, dmi_id);
++    /* Set config flags that must be on for vtpm operation */
++    tpm_config |= TPM_CONF_STRONG_PERSISTENCE;
++    tpm_config &= ~TPM_CONF_USE_INTERNAL_PRNG;
++    tpm_config |= TPM_CONF_GENERATE_EK;
++    tpm_config |= TPM_CONF_GENERATE_SEED_DAA;
++    /*Start the emulator */
++    tpm_emulator_init(tpm_startup, tpm_config);
+     /* start command processing */
+     while (!stopflag) {
+         /* wait for incomming connections */
+         debug("waiting for connections...");
+-        FD_ZERO(&rfds);
+-        FD_SET(sock, &rfds);
+-        tv.tv_sec = 10;
+-        tv.tv_usec = 0;
+-        res = select(sock + 1, &rfds, NULL, NULL, &tv);
+-        if (res < 0) {
+-            error("select(sock) failed: %s", strerror(errno));
+-            break;
+-        } else if (res == 0) {
+-            continue;
++        if (vtpm_rx_fh < 0) {
++            if (vtpm_type == VTPM_TYPE_PVM)
++            {
++                vtpm_rx_fh = open(vtpm_rx_file, O_RDONLY);
++            } else {
++                if (bind(sockfd, (struct sockaddr *)&addr,
sizeof(addr)) < 0) {
++                    error("Unable to bind(). errno = %d\n", errno);
++                    exit (-1);
++                }
++
++                if (listen(sockfd, 10) <0) {
++                    error("Unable to listen(). errno = %d\n", errno);
++                    exit (-1);
++                }
++
++                 memset(&client_addr, 0, sizeof(client_addr));
++                 client_length = sizeof(client_addr);
++
++                 vtpm_rx_fh = vtpm_tx_fh = accept(sockfd, (struct
sockaddr *)&client_addr, &client_length);
++            }
+         }
+-        addr_len = sizeof(addr);
+-        fh = accept(sock, (struct sockaddr*)&addr, &addr_len);
+-        if (fh < 0) {
+-            error("accept() failed: %s", strerror(errno));
+-            continue;
++
++        /*Error Checking*/
++        if (vtpm_rx_fh < 0) {
++          error("Failed to open devices to listen to guest.\n");
++          exit(-1);
+         }
++
+         /* receive and handle commands */
+         in_len = 0;
+         do {
+             debug("waiting for commands...");
+-            FD_ZERO(&rfds);
+-            FD_SET(fh, &rfds);
+-            tv.tv_sec = TPM_COMMAND_TIMEOUT;
+-            tv.tv_usec = 0;
+-            res = select(fh + 1, &rfds, NULL, NULL, &tv);
+-            if (res < 0) {
+-                error("select(fh) failed: %s", strerror(errno));
+-                close(fh);
+-                break;
+-            } else if (res == 0) {
+-#ifdef TPMD_DISCONNECT_IDLE_CLIENTS
+-                info("connection closed due to inactivity");
+-                close(fh);
+-                break;
+-#else
+-                continue;
+-#endif
+-            }
+-            in_len = read(fh, in, sizeof(in));
+-            if (in_len > 0) {
++
++            in_len = read(vtpm_rx_fh, in, sizeof(in));
++            /*Magic size of minimum TPM command is 6*/
++            if (in_len < 6) {
++                info("Recv incomplete command of %d bytes.", in_len);
++                if (in_len <= 0) {
++                    close(vtpm_rx_fh);
++                    vtpm_rx_fh = -1;
++                    continue;
++                 }
++            } else {
++                /*Debug Printouts*/
+                 debug("received %d bytes", in_len);
++                debug_nostop("Recv[%d]: 0x", in_len);
++                for (i=0; i< in_len; i++)
++                    debug_more("%02x ", in[i]);
++                debug_more("\n");
++                /*Multiple Guest check*/
++                if (guest_id == -1) {
++                    guest_id = *((int32_t *) in);
++                } else {
++                    if (guest_id != *((int32_t *) in) ) {
++                        error("WARNING: More than one guest attached\n");
++                    }
++                }
++
++                /*Open tx handle now*/
++                if (vtpm_tx_fh < 0) {
++                    if (vtpm_type == VTPM_TYPE_PVM) {
++                        vtpm_tx_fh = open(PVM_TX_FIFO, O_WRONLY);
++                    } // No need to open the other direction for HVM
++                }
++                if (vtpm_tx_fh < 0) {
++                  error("Failed to open devices to respond to guest.\n");
++                  exit(-1);
++                }
++
++                /*Handle the TPM command now*/
+                 out = NULL;
+-                res = tpm_handle_command(in, in_len, &out, &out_len);
++                res = tpm_handle_command(in + sizeof(uint32_t), in_len
- sizeof(uint32_t), &out, &out_len);
+                 if (res < 0) {
+                     error("tpm_handle_command() failed");
+                 } else {
+                     debug("sending %d bytes", out_len);
+-                    uint32_t len = 0;
+-                    while (len < out_len) {
+-                        res = write(fh, &out[len], out_len - len);
++            //Prepend the dmi_id
++                    addressed_out = (uint8_t *)
tpm_malloc(sizeof(uint32_t) + out_len);
++                    *(uint32_t *) addressed_out = *(uint32_t *) in;
++                    memcpy(addressed_out + sizeof(uint32_t), out,
out_len);
++                    out_len += sizeof(uint32_t);
++                    /*End Prepend*/
++
++                    /*Perform write operation now*/
++                    while (out_len > 0) {
++                        res = write(vtpm_tx_fh, addressed_out, out_len);
++
+                         if (res < 0) {
+-                            error("write(%d) failed: %s",
+-                                  out_len - len, strerror(errno));
++                            error("write(%d) failed: %s", out_len,
strerror(errno));
+                             break;
++                        } else {
++                          debug_nostop("Sent[%Zu]: ", out_len);
++                          for (i=0; (unsigned int)i< out_len; i++)
++                            debug_more("%02x ", addressed_out[i]);
++                          debug_more("\n");
+                         }
+-                        len += res;
++                        out_len -= res;
+                     }
+                     tpm_free(out);
++                    tpm_free(addressed_out);
+                 }
+             }
+         } while (in_len > 0);
+-        close(fh);
+     }
++
+     /* shutdown tpm emulator */
+     tpm_emulator_shutdown();
+-    /* close socket */
+-    close(sock);
+-    unlink(opt_socket_name);
++    /* Close handles */
++    close(vtpm_tx_fh);
++    close(vtpm_rx_fh);
++    free(vtpm_rx_file);
+     info("main loop stopped");
+ }
+
+ int main(int argc, char **argv)
+ {
++    //Set load/store functions
++    tpm_write_to_storage = vtpm_write_to_file;
++    tpm_read_from_storage = vtpm_read_from_file;
++
+     openlog(argv[0], 0, LOG_DAEMON);
+     setlogmask(~LOG_MASK(LOG_DEBUG));
+     syslog(LOG_INFO, "--- separator ---\n");
+@@ -393,8 +602,6 @@
+     switch_uid_gid();
+     /* init signal handlers */
+     init_signal_handler();
+-    /* unless requested otherwiese, fork and daemonize process */
+-    if (!opt_foreground) daemonize();
+     /* start main processing loop */
+     main_loop();
+     info("stopping TPM Emulator daemon");
+diff -Naur tpm_emulator-0.7.4-orig/tpmd/unix/tpmd.c.orig
tpm_emulator-0.7.4/tpmd/unix/tpmd.c.orig
+--- tpm_emulator-0.7.4-orig/tpmd/unix/tpmd.c.orig    1969-12-31
19:00:00.000000000 -0500
++++ tpm_emulator-0.7.4/tpmd/unix/tpmd.c.orig    2011-12-20
13:30:06.000000000 -0500
+@@ -0,0 +1,403 @@
++/* Software-based Trusted Platform Module (TPM) Emulator
++ * Copyright (C) 2004-2010 Mario Strasser <mast@xxxxxxx>
++ *
++ * This program is free software; you can redistribute it and/or modify
++ * it under the terms of the GNU General Public License as published
++ * by the Free Software Foundation; either version 2 of the License,
++ * or (at your option) any later version.
++ *
++ * This program is distributed in the hope that it will be useful,
++ * but WITHOUT ANY WARRANTY; without even the implied warranty of
++ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
++ * GNU General Public License for more details.
++ *
++ * $Id: tpmd.c 463 2011-06-08 14:25:04Z mast $
++ */
++
++#include <stdio.h>
++#include <stdlib.h>
++#include <unistd.h>
++#include <signal.h>
++#include <string.h>
++#include <errno.h>
++#include <syslog.h>
++#include <stdarg.h>
++#include <fcntl.h>
++#include <sys/stat.h>
++#include <sys/socket.h>
++#include <sys/un.h>
++#include <pwd.h>
++#include <grp.h>
++#include "config.h"
++#include "tpm/tpm_emulator.h"
++
++#define TPM_COMMAND_TIMEOUT 30
++
++static volatile int stopflag = 0;
++static int is_daemon = 0;
++static int opt_debug = 0;
++static int opt_foreground = 0;
++static const char *opt_socket_name = TPM_SOCKET_NAME;
++static uid_t opt_uid = 0;
++static gid_t opt_gid = 0;
++static int tpm_startup = 2;
++static uint32_t tpm_config = 0;
++extern const char *tpm_storage_file;
++
++void my_log(int priority, const char *fmt, ...)
++{
++    va_list ap, bp;
++    va_start(ap, fmt);
++    va_copy(bp, ap);
++    switch (priority) {
++      case TPM_LOG_DEBUG:
++        vsyslog(LOG_DEBUG, fmt, ap);
++        break;
++      case TPM_LOG_ERROR:
++        vsyslog(LOG_ERR, fmt, ap);
++        break;
++      case TPM_LOG_INFO:
++      default:
++        vsyslog(LOG_INFO, fmt, ap);
++        break;
++    }
++    va_end(ap);
++    if (!is_daemon && (priority != TPM_LOG_DEBUG || opt_debug)) {
++        vprintf(fmt, bp);
++    }
++    va_end(bp);
++}
++
++static void print_usage(char *name)
++{
++    printf("usage: %s [-d] [-f] [-s storage file] [-u unix socket name] "
++           "[-o user name] [-g group name] [-h] [startup mode]\n", name);
++    printf("  d : enable debug mode\n");
++    printf("  f : forces the application to run in the foreground\n");
++    printf("  s : storage file to use (default: %s)\n", tpm_storage_file);
++    printf("  u : unix socket name to use (default: %s)\n",
opt_socket_name);
++    printf("  o : effective user the application should run as\n");
++    printf("  g : effective group the application should run as\n");
++    printf("  h : print this help message\n");
++    printf("  startup mode : must be 'clear', "
++           "'save' (default) or 'deactivated\n");
++}
++
++static void parse_options(int argc, char **argv)
++{
++    char c;
++    struct passwd *pwd;
++    struct group *grp;
++    opt_uid = getuid();
++    opt_gid = getgid();
++    info("parsing options");
++    while ((c = getopt (argc, argv, "dfs:u:o:g:c:h")) != -1) {
++        debug("handling option '-%c'", c);
++        switch (c) {
++            case 'd':
++                opt_debug = 1;
++                setlogmask(setlogmask(0) | LOG_MASK(LOG_DEBUG));
++                debug("debug mode enabled");
++                break;
++            case 'f':
++                debug("application is forced to run in foreground");
++                opt_foreground = 1;
++                break;
++            case 's':
++                tpm_storage_file = optarg;
++                debug("using storage file '%s'", tpm_storage_file);
++                break;
++            case 'u':
++                opt_socket_name = optarg;
++                debug("using unix socket '%s'", opt_socket_name);
++                break;
++            case 'o':
++                pwd  = getpwnam(optarg);
++                if (pwd == NULL) {
++                    error("invalid user name '%s'\n", optarg);
++                    exit(EXIT_FAILURE);
++                }
++                opt_uid = pwd->pw_uid;
++                break;
++            case 'g':
++                grp  = getgrnam(optarg);
++                if (grp == NULL) {
++                    error("invalid group name '%s'\n", optarg);
++                    exit(EXIT_FAILURE);
++                }
++                opt_gid = grp->gr_gid;
++                break;
++            case 'c':
++                tpm_config = strtol(optarg, NULL, 0);
++                debug("tpm_config = %04x", tpm_config);
++                break;
++            case '?':
++                error("unknown option '-%c'", optopt);
++                print_usage(argv[0]);
++                exit(EXIT_FAILURE);
++            case 'h':
++            default:
++                print_usage(argv[0]);
++                exit(EXIT_SUCCESS);
++        }
++    }
++    if (optind < argc) {
++        debug("startup mode = '%s'", argv[optind]);
++        if (!strcmp(argv[optind], "clear")) {
++            tpm_startup = 1;
++        } else if (!strcmp(argv[optind], "save")) {
++            tpm_startup = 2;
++        } else if (!strcmp(argv[optind], "deactivated")) {
++            tpm_startup = 3;
++        } else {
++            error("invalid startup mode '%s'; must be 'clear', "
++                  "'save' (default) or 'deactivated", argv[optind]);
++            print_usage(argv[0]);
++            exit(EXIT_SUCCESS);
++        }
++    } else {
++        /* if no startup mode is given assume save if a configuration
++           file is available, clear otherwise */
++        int fh = open(tpm_storage_file, O_RDONLY);
++        if (fh < 0) {
++            tpm_startup = 1;
++            info("no startup mode was specified; asuming 'clear'");
++        } else {
++            tpm_startup = 2;
++            close(fh);
++        }
++    }
++}
++
++static void switch_uid_gid(void)
++{
++    if (opt_gid != getgid()) {
++        info("switching effective group ID to %d", opt_gid);
++        if (setgid(opt_gid) == -1) {
++            error("switching effective group ID to %d failed: %s",
opt_gid, strerror(errno));
++            exit(EXIT_FAILURE);
++        }
++    }
++    if (opt_uid != getuid()) {
++        info("switching effective user ID to %d", opt_uid);
++        if (setuid(opt_uid) == -1) {
++            error("switching effective user ID to %d failed: %s",
opt_uid, strerror(errno));
++            exit(EXIT_FAILURE);
++        }
++    }
++}
++
++static void signal_handler(int sig)
++{
++    info("signal received: %d", sig);
++    if (sig == SIGTERM || sig == SIGQUIT || sig == SIGINT) stopflag = 1;
++}
++
++static void init_signal_handler(void)
++{
++    info("installing signal handlers");
++    if (signal(SIGTERM, signal_handler) == SIG_ERR) {
++        error("signal(SIGTERM) failed: %s", strerror(errno));
++        exit(EXIT_FAILURE);
++    }
++    if (signal(SIGQUIT, signal_handler) == SIG_ERR) {
++        error("signal(SIGQUIT) failed: %s", strerror(errno));
++        exit(EXIT_FAILURE);
++    }
++    if (signal(SIGINT, signal_handler) == SIG_ERR) {
++        error("signal(SIGINT) failed: %s", strerror(errno));
++        exit(EXIT_FAILURE);
++    }
++    if (signal(SIGPIPE, signal_handler) == SIG_ERR) {
++        error("signal(SIGPIPE) failed: %s", strerror(errno));
++        exit(EXIT_FAILURE);
++    }
++}
++
++static void daemonize(void)
++{
++    pid_t sid, pid;
++    info("daemonizing process");
++    pid = fork();
++    if (pid < 0) {
++        error("fork() failed: %s", strerror(errno));
++        exit(EXIT_FAILURE);
++    }
++    if (pid > 0) exit(EXIT_SUCCESS);
++    pid = getpid();
++    sid = setsid();
++    if (sid < 0) {
++        error("setsid() failed: %s", strerror(errno));
++        exit(EXIT_FAILURE);
++    }
++    if (chdir("/") < 0) {
++        error("chdir() failed: %s", strerror(errno));
++        exit(EXIT_FAILURE);
++    }
++    close(STDIN_FILENO);
++    close(STDOUT_FILENO);
++    close(STDERR_FILENO);
++    is_daemon = 1;
++    info("process was successfully daemonized: pid=%d sid=%d", pid, sid);
++}
++
++static int mkdirs(const char *path)
++{
++    char *copy = strdup(path);
++    char *p = strchr(copy + 1, '/');
++    while (p != NULL) {
++        *p = '\0';
++        if ((mkdir(copy, 0755) == -1) && (errno != EEXIST)) {
++            free(copy);
++            return errno;
++        }
++        *p = '/';
++        p = strchr(p + 1, '/');
++    }
++    free(copy);
++    return 0;
++}
++
++static int init_socket(const char *name)
++{
++    int sock;
++    struct sockaddr_un addr;
++    info("initializing socket %s", name);
++    sock = socket(AF_UNIX, SOCK_STREAM, 0);
++    if (sock < 0) {
++        error("socket(AF_UNIX) failed: %s", strerror(errno));
++        return -1;
++    }
++    mkdirs(name);
++    addr.sun_family = AF_UNIX;
++    strncpy(addr.sun_path, name, sizeof(addr.sun_path));
++    umask(0177);
++    if (bind(sock, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
++        error("bind(%s) failed: %s", addr.sun_path, strerror(errno));
++        close(sock);
++        return -1;
++    }
++    listen(sock, 1);
++    return sock;
++}
++
++static void main_loop(void)
++{
++    int sock, fh, res;
++    int32_t in_len;
++    uint32_t out_len;
++    uint8_t in[TPM_CMD_BUF_SIZE], *out;
++    struct sockaddr_un addr;
++    socklen_t addr_len;
++    fd_set rfds;
++    struct timeval tv;
++
++    info("staring main loop");
++    /* open UNIX socket */
++    sock = init_socket(opt_socket_name);
++    if (sock < 0) exit(EXIT_FAILURE);
++    /* init tpm emulator */
++    debug("initializing TPM emulator");
++    if (tpm_emulator_init(tpm_startup, tpm_config) != 0) {
++        error("tpm_emulator_init() failed");
++        close(sock);
++        unlink(opt_socket_name);
++        exit(EXIT_FAILURE);
++    }
++    /* start command processing */
++    while (!stopflag) {
++        /* wait for incomming connections */
++        debug("waiting for connections...");
++        FD_ZERO(&rfds);
++        FD_SET(sock, &rfds);
++        tv.tv_sec = 10;
++        tv.tv_usec = 0;
++        res = select(sock + 1, &rfds, NULL, NULL, &tv);
++        if (res < 0) {
++            error("select(sock) failed: %s", strerror(errno));
++            break;
++        } else if (res == 0) {
++            continue;
++        }
++        addr_len = sizeof(addr);
++        fh = accept(sock, (struct sockaddr*)&addr, &addr_len);
++        if (fh < 0) {
++            error("accept() failed: %s", strerror(errno));
++            continue;
++        }
++        /* receive and handle commands */
++        in_len = 0;
++        do {
++            debug("waiting for commands...");
++            FD_ZERO(&rfds);
++            FD_SET(fh, &rfds);
++            tv.tv_sec = TPM_COMMAND_TIMEOUT;
++            tv.tv_usec = 0;
++            res = select(fh + 1, &rfds, NULL, NULL, &tv);
++            if (res < 0) {
++                error("select(fh) failed: %s", strerror(errno));
++                close(fh);
++                break;
++            } else if (res == 0) {
++#ifdef TPMD_DISCONNECT_IDLE_CLIENTS
++                info("connection closed due to inactivity");
++                close(fh);
++                break;
++#else
++                continue;
++#endif
++            }
++            in_len = read(fh, in, sizeof(in));
++            if (in_len > 0) {
++                debug("received %d bytes", in_len);
++                out = NULL;
++                res = tpm_handle_command(in, in_len, &out, &out_len);
++                if (res < 0) {
++                    error("tpm_handle_command() failed");
++                } else {
++                    debug("sending %d bytes", out_len);
++                    uint32_t len = 0;
++                    while (len < out_len) {
++                        res = write(fh, &out[len], out_len - len);
++                        if (res < 0) {
++                            error("write(%d) failed: %s",
++                                  out_len - len, strerror(errno));
++                            break;
++                        }
++                        len += res;
++                    }
++                    tpm_free(out);
++                }
++            }
++        } while (in_len > 0);
++        close(fh);
++    }
++    /* shutdown tpm emulator */
++    tpm_emulator_shutdown();
++    /* close socket */
++    close(sock);
++    unlink(opt_socket_name);
++    info("main loop stopped");
++}
++
++int main(int argc, char **argv)
++{
++    openlog(argv[0], 0, LOG_DAEMON);
++    setlogmask(~LOG_MASK(LOG_DEBUG));
++    syslog(LOG_INFO, "--- separator ---\n");
++    tpm_log = my_log;
++    info("starting TPM Emulator daemon (1.2.%d.%d-%d)",
++         VERSION_MAJOR, VERSION_MINOR, VERSION_BUILD);
++    parse_options(argc, argv);
++    /* switch uid/gid if required */
++    switch_uid_gid();
++    /* init signal handlers */
++    init_signal_handler();
++    /* unless requested otherwiese, fork and daemonize process */
++    if (!opt_foreground) daemonize();
++    /* start main processing loop */
++    main_loop();
++    info("stopping TPM Emulator daemon");
++    closelog();
++    return EXIT_SUCCESS;
++}
diff --git a/tools/vtpm/vtpm.patch b/tools/vtpm/vtpm.patch
--- a/tools/vtpm/vtpm.patch
+++ /dev/null
@@ -1,716 +0,0 @@
-diff -uprN tpm_emulator/AUTHORS vtpm/AUTHORS
---- tpm_emulator/AUTHORS    2006-12-08 12:51:29.000000000 -0800
-+++ vtpm/AUTHORS    2006-12-13 16:38:52.000000000 -0800
-@@ -1,3 +1,3 @@
- Mario Strasser <mast@xxxxxxx>
- Heiko Stamer <stamer@xxxxxxxx> [DAA]
--INTEL Corp <> [Dropped to Ring3]
-+INTEL Corp <> [VTPM Extensions]
-diff -uprN tpm_emulator/ChangeLog vtpm/ChangeLog
---- tpm_emulator/ChangeLog    2006-12-08 12:51:29.000000000 -0800
-+++ vtpm/ChangeLog    2006-12-13 16:38:52.000000000 -0800
-@@ -1,5 +1,6 @@
- ????-??-?? Intel Corp
-     * Moved module out of kernel to run as a ring 3 app
-+    * Modified save_to_file and load_from_file to call xen VTPM manager
-
- 2006-06-23  Mario Strasser <mast@xxxxxxx>
-     * tpm_startup.c: behaviour of ST_CLEAR and storage of
-diff -uprN tpm_emulator/linux_module.h vtpm/linux_module.h
---- tpm_emulator/linux_module.h    2006-12-08 12:51:29.000000000 -0800
-+++ vtpm/linux_module.h    2007-01-09 14:49:06.000000000 -0800
-@@ -44,18 +44,26 @@
- #define TPM_DEVICE_NAME   "tpm"
- #define TPM_MODULE_NAME   "tpm_emulator"
-
-+/* debug and log output functions */
-+extern int dmi_id;
-+
- #ifdef DEBUG
--#define debug(fmt, ...) printf("TPMD: %s:%d: Debug: " fmt "\n", \
--                        __FILE__, __LINE__, ## __VA_ARGS__)
-+#define debug(fmt, ...) printf("TPMD[%d]: %s:%d: Debug: " fmt "\n", \
-+                        dmi_id, __FILE__, __LINE__, ## __VA_ARGS__)
-+#define debug_nostop(fmt, ...) printf("TPMD[%d]: %s:%d: Debug: " fmt, \
-+                        dmi_id, __FILE__, __LINE__, ## __VA_ARGS__)
-+#define debug_more(fmt, ...) printf( fmt, ## __VA_ARGS__ )
- #else
- #define debug(fmt, ...)
-+#define debug_nostop(fmt, ...)
-+#define debug_more(fmt, ...)
- #endif
--#define info(fmt, ...)  printf("TPMD: %s:%d: Info: " fmt "\n", \
--                        __FILE__, __LINE__, ## __VA_ARGS__)
--#define error(fmt, ...) printf("TPMD: %s:%d: Error: " fmt "\n", \
--                        __FILE__, __LINE__, ## __VA_ARGS__)
--#define alert(fmt, ...) printf("TPMD: %s:%d: Alert: " fmt "\n", \
--                        __FILE__, __LINE__, ## __VA_ARGS__)
-+#define info(fmt, ...)  printf("TPMD[%d]: %s:%d: Info: " fmt "\n", \
-+                        dmi_id, __FILE__, __LINE__, ## __VA_ARGS__)
-+#define error(fmt, ...) printf("TPMD[%d]: %s:%d: Error: " fmt "\n", \
-+                        dmi_id, __FILE__, __LINE__, ## __VA_ARGS__)
-+#define alert(fmt, ...) printf("TPMD[%d]: %s:%d: Alert: " fmt "\n", \
-+                        dmi_id, __FILE__, __LINE__, ## __VA_ARGS__)
-
- /* memory allocation */
-
-diff -uprN tpm_emulator/Makefile vtpm/Makefile
---- tpm_emulator/Makefile    2006-12-08 12:51:29.000000000 -0800
-+++ vtpm/Makefile    2006-12-13 16:38:52.000000000 -0800
-@@ -7,7 +7,7 @@
- COMPILE_ARCH    ?= $(shell uname -m | sed -e s/i.86/x86_32/)
-
- # module settings
--BIN            := tpm_emulator
-+BIN            := vtpmd
- VERSION_MAJOR  := 0
- VERSION_MINOR  := 4
- VERSION_BUILD  := $(shell date +"%s")
-@@ -22,7 +22,7 @@ TOOLS_INSTALL_DIR = $(DESTDIR)/usr/bin
-
- CC      := gcc
- CFLAGS  += -g -Wall $(INCLUDE) -DDEBUG
--CFLAGS  += -I. -Itpm
-+CFLAGS  += -I. -Itpm -I../../vtpm_manager/manager
-
- # Is the simulator running in it's own vm?
- #CFLAGS += -DVTPM_MULTI_VM
-@@ -62,7 +62,6 @@ $(BIN):    $(src)/crypto/gmp.h $(src)/crypt
-
- install: $(BIN)
-     $(INSTALL_PROG) $(BIN) $(TOOLS_INSTALL_DIR)
--    @if [ ! -d "/var/tpm" ]; then mkdir /var/tpm; fi
-
- clean:
-     rm -f $(src)/crypto/gmp.h $(src)/crypto/libgmp.a $(OBJS)
-@@ -98,3 +97,4 @@ version:
-     @echo "#endif /* _TPM_VERSION_H_ */" >> $(src)/tpm_version.h
-
- .PHONY: all install clean dist gmp version
-+
-diff -uprN tpm_emulator/tpm/tpm_capability.c vtpm/tpm/tpm_capability.c
---- tpm_emulator/tpm/tpm_capability.c    2006-06-23 03:37:07.000000000
-0700
-+++ vtpm/tpm/tpm_capability.c    2007-01-10 10:00:49.000000000 -0800
-@@ -136,8 +136,18 @@ static TPM_RESULT cap_property(UINT32 su
-
-     case TPM_CAP_PROP_TIS_TIMEOUT:
-       debug("[TPM_CAP_PROP_TIS_TIMEOUT]");
--      /* TODO: TPM_CAP_PROP_TIS_TIMEOUT */
--      return TPM_FAIL;
-+      /* TODO: TPM_CAP_PROP_TIS_TIMEOUT: Measure these values and
determine correct ones */
-+      UINT32 len = *respSize = 16;
-+      BYTE *ptr = *resp = tpm_malloc(*respSize);
-+      if (ptr == NULL ||
-+          tpm_marshal_UINT32(&ptr, &len, 200000) ||
-+          tpm_marshal_UINT32(&ptr, &len, 200000) ||
-+          tpm_marshal_UINT32(&ptr, &len, 200000) ||
-+          tpm_marshal_UINT32(&ptr, &len, 200000)) {
-+        tpm_free(*resp);
-+        return TPM_FAIL;
-+      }
-+      return TPM_SUCCESS;
-
-     case TPM_CAP_PROP_STARTUP_EFFECT:
-       debug("[TPM_CAP_PROP_STARTUP_EFFECT]");
-@@ -190,7 +200,11 @@ static TPM_RESULT cap_property(UINT32 su
-
-     case TPM_CAP_PROP_DURATION:
-       debug("[TPM_CAP_PROP_DURATION]");
--      /* TODO: TPM_CAP_PROP_DURATION */
-+      /* TODO: TPM_CAP_PROP_DURATION: Measure these values and return
accurate ones */
-+      BYTE dur[]=
{0x0,0x0,0x0,0xc,0x0,0x7,0xa1,0x20,0x0,0x1e,0x84,0x80,0x11,0xe1,0xa3,0x0};
-+      *respSize = 16;
-+      *resp = tpm_malloc(*respSize);
-+      memcpy(*resp,dur,16);
-       return TPM_FAIL;
-
-     case TPM_CAP_PROP_ACTIVE_COUNTER:
-diff -uprN tpm_emulator/tpm/tpm_cmd_handler.c vtpm/tpm/tpm_cmd_handler.c
---- tpm_emulator/tpm/tpm_cmd_handler.c    2008-02-27 16:35:41.000000000
-0500
-+++ vtpm/tpm/tpm_cmd_handler.c    2008-02-28 14:43:28.000000000 -0500
-@@ -94,12 +94,18 @@ void tpm_compute_out_param_digest(TPM_CO
-   sha1_ctx_t sha1;
-   UINT32 res = CPU_TO_BE32(rsp->result);
-   UINT32 ord = CPU_TO_BE32(ordinal);
-+  UINT32 offset = 0;
-
-   /* compute SHA1 hash */
-   sha1_init(&sha1);
-   sha1_update(&sha1, (BYTE*)&res, 4);
-   sha1_update(&sha1, (BYTE*)&ord, 4);
--  sha1_update(&sha1, rsp->param, rsp->paramSize);
-+  if (ordinal == TPM_ORD_LoadKey2) {
-+      offset = 4;
-+  }
-+  if (rsp->paramSize - offset > 0) {
-+      sha1_update(&sha1, rsp->param + offset, rsp->paramSize - offset);
-+  }
-   sha1_final(&sha1, rsp->auth1->digest);
-   if (rsp->auth2 != NULL) memcpy(rsp->auth2->digest,
-     rsp->auth1->digest, sizeof(rsp->auth1->digest));
-diff -uprN tpm_emulator/tpm/tpm_data.c vtpm/tpm/tpm_data.c
---- tpm_emulator/tpm/tpm_data.c    2008-02-27 16:35:41.000000000 -0500
-+++ vtpm/tpm/tpm_data.c    2008-02-27 16:35:40.000000000 -0500
-@@ -1,6 +1,7 @@
- /* Software-Based Trusted Platform Module (TPM) Emulator for Linux
-  * Copyright (C) 2004 Mario Strasser <mast@xxxxxxx>,
-  *                    Swiss Federal Institute of Technology (ETH) Zurich
-+ * Copyright (C) 2005 INTEL Corp
-  *
-  * This module is free software; you can redistribute it and/or modify
-  * it under the terms of the GNU General Public License as published
-@@ -15,10 +16,15 @@
-  * $Id: tpm_data.c 98 2006-05-07 14:16:29Z hstamer $
-  */
-
-+#include <sys/types.h>
-+#include <sys/stat.h>
-+#include <fcntl.h>
-+#include <unistd.h>
-+
- #include "tpm_emulator.h"
- #include "tpm_structures.h"
- #include "tpm_marshalling.h"
--#include "linux_module.h"
-+#include "vtpm_manager.h"
-
- TPM_DATA tpmData;
-
-@@ -158,45 +164,232 @@ void tpm_release_data(void)
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
--#include <unistd.h>
-
--#define TPM_STORAGE_FILE "/var/tpm/tpm_emulator-1.2."
STR(VERSION_MAJOR) "." STR(VERSION_MINOR)
-+ static int vtpm_tx_fh=-1, vtpm_rx_fh=-1;
-+
-+#ifdef VTPM_MUTLI_VM
-+ #define DEV_FE "/dev/tpm"
-+#else
-+ #define VTPM_RX_FIFO_D  "/var/vtpm/fifos/vtpm_rsp_to_%d.fifo"
-+ #define VTPM_TX_FIFO  "/var/vtpm/fifos/vtpm_cmd_from_all.fifo"
-+
-+ extern int dmi_id;
-+ static char *vtpm_rx_name=NULL;
-+#endif
-
- static int write_to_file(uint8_t *data, size_t data_length)
- {
--  int res;
--  int fp;
--  fp = open(TPM_STORAGE_FILE, O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR |
S_IWUSR);
--  res = write(fp, data, data_length);
--  close(fp);
--  return (res == data_length) ? 0 : -1;
-+  int res, out_data_size, in_header_size;
-+  BYTE *ptr, *out_data, *in_header;
-+  UINT32 result, len, in_rsp_size;
-+  UINT16 tag = VTPM_TAG_REQ;
-+   
-+  printf("Saving NVM\n");
-+  if (vtpm_tx_fh < 0) {
-+#ifdef VTPM_MUTLI_VM
-+    vtpm_tx_fh = open(DEV_FE, O_RDWR);
-+#else
-+    vtpm_tx_fh = open(VTPM_TX_FIFO, O_WRONLY);
-+#endif
-+  }
-+
-+  if (vtpm_tx_fh < 0) {
-+        return -1;
-+  }
-+
-+  // Send request to VTPM Manager to encrypt data
-+#ifdef VTPM_MUTLI_VM
-+  out_data_size = len = VTPM_COMMAND_HEADER_SIZE_CLT + data_length;
-+#else
-+  out_data_size = len = VTPM_COMMAND_HEADER_SIZE_SRV + data_length;
-+#endif
-+ 
-+  out_data = ptr = (BYTE *) malloc(len);
-+
-+  if (ptr == NULL
-+#ifndef VTPM_MUTLI_VM
-+      || tpm_marshal_UINT32(&ptr, &len, dmi_id)
-+#endif
-+      || tpm_marshal_UINT16(&ptr, &len, tag)
-+#ifdef VTPM_MUTLI_VM
-+      || tpm_marshal_UINT32(&ptr, &len, out_data_size)
-+#else
-+      || tpm_marshal_UINT32(&ptr, &len, out_data_size - sizeof(uint32_t))
-+#endif 
-+      || tpm_marshal_UINT32(&ptr, &len, VTPM_ORD_SAVENVM)
-+      || tpm_marshal_BYTE_ARRAY(&ptr, &len, data, data_length)) {
-+    free(out_data);
-+    return -1;
-+  }
-+ 
-+  printf("\tSending SaveNVM Command.\n");
-+  res = write(vtpm_tx_fh, out_data, out_data_size);
-+  free(out_data);
-+  if (res != out_data_size) return -1;
-+
-+  if (vtpm_rx_fh < 0) {
-+#ifdef VTPM_MUTLI_VM
-+    vtpm_rx_fh = vtpm_tx_fh
-+#else
-+    if (vtpm_rx_name == NULL) {
-+      vtpm_rx_name = malloc(10 + strlen(VTPM_RX_FIFO_D));
-+      sprintf(vtpm_rx_name, VTPM_RX_FIFO_D, (uint32_t) dmi_id);
-+    }
-+    vtpm_rx_fh = open(vtpm_rx_name, O_RDONLY);
-+#endif
-+  }
-+
-+  if (vtpm_rx_fh < 0) {
-+        return -1;
-+  }
-+ 
-+  // Read Header of response so we can get the size & status
-+#ifdef VTPM_MUTLI_VM
-+  in_header_size = len = VTPM_COMMAND_HEADER_SIZE_CLT;
-+#else
-+  in_header_size = len = VTPM_COMMAND_HEADER_SIZE_SRV;
-+#endif
-+  in_header = ptr = malloc(in_header_size);
-+ 
-+  printf("\tReading SaveNVM header.\n");
-+  res = read(vtpm_rx_fh, in_header, in_header_size);
-+
-+  if ( (res != in_header_size)
-+#ifndef VTPM_MUTLI_VM
-+       || tpm_unmarshal_UINT32(&ptr, &len, (UINT32*)&dmi_id)
-+#endif
-+       || tpm_unmarshal_UINT16(&ptr, &len, &tag)
-+       || tpm_unmarshal_UINT32(&ptr, &len, &in_rsp_size)
-+       || tpm_unmarshal_UINT32(&ptr, &len, &result) ) {
-+      free(in_header);
-+      return -1;
-+  }
-+  free(in_header);
-+ 
-+  if (result != VTPM_SUCCESS) {
-+      return -1; 
-+  }
-+
-+#ifdef VTPM_MUTLI_VM
-+  close(vtpm_tx_fh); close(vtpm_rx_fh);
-+#endif
-+     
-+  printf("\tFinishing up SaveNVM\n");
-+  return (0);
- }
-
- static int read_from_file(uint8_t **data, size_t *data_length)
- {
--  int res;
--  int fp, file_status;
--  struct stat file_info;
--  fp = open(TPM_STORAGE_FILE, O_RDONLY, 0);
--  file_status = fstat(fp, &file_info);
--  if (file_status < 0) {
--    close(fp);
--    return -1;
--  }
-+  int res, out_data_size, in_header_size;
-+  uint8_t *ptr, *out_data, *in_header;
-+  UINT16 tag = VTPM_TAG_REQ;
-+  UINT32 len, in_rsp_size, result;
-+#ifdef VTPM_MUTLI_VM
-+    int vtpm_rx_fh, vtpm_tx_fh;
-+#endif
-+   
-+  printf("Loading NVM.\n");
-+  if (vtpm_tx_fh < 0) {
-+#ifdef VTPM_MUTLI_VM
-+    vtpm_tx_fh = open(DEV_FE, O_RDWR);
-+#else
-+    vtpm_tx_fh = open(VTPM_TX_FIFO, O_WRONLY);
-+#endif
-+  }
-
--  *data_length = file_info.st_size;
--  *data = tpm_malloc(*data_length);
--  if (*data == NULL) {
--    close(fp);
-+  if (vtpm_tx_fh < 0) {
-+        return -1;
-+  }
-+
-+  // Send request to VTPM Manager to encrypt data
-+#ifdef VTPM_MUTLI_VM
-+  out_data_size = len = VTPM_COMMAND_HEADER_SIZE_CLT;
-+#else
-+  out_data_size = len = VTPM_COMMAND_HEADER_SIZE_SRV;
-+#endif
-+  out_data = ptr = (BYTE *) malloc(len);
-+
-+  if (ptr == NULL
-+#ifndef VTPM_MUTLI_VM
-+      || tpm_marshal_UINT32(&ptr, &len, dmi_id)
-+#endif 
-+      || tpm_marshal_UINT16(&ptr, &len, tag)
-+#ifdef VTPM_MUTLI_VM
-+      || tpm_marshal_UINT32(&ptr, &len, out_data_size)
-+#else
-+      || tpm_marshal_UINT32(&ptr, &len, out_data_size - sizeof(uint32_t))
-+#endif
-+      || tpm_marshal_UINT32(&ptr, &len, VTPM_ORD_LOADNVM)) {
-+    free(out_data);
-     return -1;
-   }
--  res = read(fp, *data, *data_length);
--  close(fp);
-+
-+  printf("\tSending LoadNVM command\n");
-+  res = write(vtpm_tx_fh, out_data, out_data_size);
-+  free(out_data);
-+  if (res != out_data_size) return -1;
-+
-+    if (vtpm_rx_fh < 0) {
-+#ifdef VTPM_MUTLI_VM
-+    vtpm_rx_fh = vtpm_tx_fh;
-+#else
-+    if (vtpm_rx_name == NULL) {
-+      vtpm_rx_name = malloc(10 + strlen(VTPM_RX_FIFO_D));
-+      sprintf(vtpm_rx_name, VTPM_RX_FIFO_D, (uint32_t) dmi_id);
-+    }
-+    vtpm_rx_fh = open(vtpm_rx_name, O_RDONLY);
-+#endif
-+  }
-+
-+  if (vtpm_rx_fh < 0) {
-+        return -1;
-+  }
-+ 
-+  // Read Header of response so we can get the size & status
-+#ifdef VTPM_MUTLI_VM
-+  in_header_size = len = VTPM_COMMAND_HEADER_SIZE_CLT;
-+#else
-+  in_header_size = len = VTPM_COMMAND_HEADER_SIZE_SRV;
-+#endif
-+  in_header = ptr = malloc(in_header_size);
-+ 
-+  printf("\tReading LoadNVM header\n");
-+  res = read(vtpm_rx_fh, in_header, in_header_size);
-+
-+  if ( (res != in_header_size)
-+#ifndef VTPM_MUTLI_VM
-+       || tpm_unmarshal_UINT32(&ptr, &len, (UINT32*)&dmi_id)
-+#endif
-+       || tpm_unmarshal_UINT16(&ptr, &len, &tag)
-+       || tpm_unmarshal_UINT32(&ptr, &len, &in_rsp_size)
-+       || tpm_unmarshal_UINT32(&ptr, &len, &result) ) {
-+      free(in_header);
-+      return -1;
-+  }
-+  free(in_header);
-+ 
-+  if (result != VTPM_SUCCESS) {
-+      return -1; 
-+  }
-+
-+  // Read Encrypted data from VTPM Manager
-+  *data_length = in_rsp_size - VTPM_COMMAND_HEADER_SIZE_CLT;
-+  *data = (uint8_t *) malloc(*data_length);
-+
-+  printf("\tReading clear data from LoadNVM.\n");
-+  res = read(vtpm_rx_fh, *data, *data_length);
-+#ifdef VTPM_MUTLI_VM
-+  close(vtpm_rx_fh);close(vtpm_tx_fh);
-+#endif
-+   
-+  printf("\tReturing from loading NVM\n");
-   if (res != *data_length) {
--    tpm_free(*data);
--    return -1;
-+      free(*data);
-+      return -1;
-+  } else {
-+      return 0;
-   }
--  return 0;
-+
- }
-
- #else
-diff -uprN tpm_emulator/tpmd.c vtpm/tpmd.c
---- tpm_emulator/tpmd.c    2006-12-08 12:51:29.000000000 -0800
-+++ vtpm/tpmd.c    2007-01-09 14:48:56.000000000 -0800
-@@ -21,12 +21,24 @@
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <sys/time.h>
-+#include <sys/socket.h>
-+#include <sys/un.h>
-+#include <errno.h>
-
- #include "tpm_emulator.h"
-+#include "vtpm_manager.h"
-
--#define TPM_RX_FNAME "/var/tpm/tpm_in.fifo"
--#define TPM_TX_FNAME "/var/tpm/tpm_out.fifo"
-+#ifdef VTPM_MULTI_VM
-+ #define DEV_BE "/dev/vtpm"
-+#else
-+ #define PVM_RX_FIFO_D "/var/vtpm/fifos/tpm_cmd_to_%d.fifo"
-+ #define PVM_TX_FIFO "/var/vtpm/fifos/tpm_rsp_from_all.fifo"
-
-+ #define HVM_RX_FIFO_D "/var/vtpm/socks/%d.socket"
-+#endif
-+
-+ int dmi_id;
-+                       
- #define BUFFER_SIZE 2048
-
- static int devurandom=0;
-@@ -38,7 +50,7 @@ void get_random_bytes(void *buf, int nby
-   }
-
-   if (read(devurandom, buf, nbytes) != nbytes) {
--      printf("Can't get random number.\n");
-+      error("Can't get random number.\n");
-       exit(-1);
-   }
- }
-@@ -52,105 +64,182 @@ uint64_t tpm_get_ticks(void)
-
- int main(int argc, char **argv)
- {
--  uint8_t in[BUFFER_SIZE], *out;
-+  uint8_t type, in[BUFFER_SIZE], *out, *addressed_out;
-+  char *vtpm_rx_file=NULL;
-   uint32_t out_size;
-   int in_size, written;
--  int i;
--  struct stat file_info;
-+  int i, guest_id=-1;
-
--  int tpm_tx_fh=-1, tpm_rx_fh=-1;
-+#ifndef VTPM_MULTI_VM
-+  int sockfd = -1;
-+  struct sockaddr_un addr;
-+  struct sockaddr_un client_addr;
-+  unsigned int client_length;
-+
-+#endif
-+
-+  int vtpm_tx_fh=-1, vtpm_rx_fh=-1;
-+#ifdef VTPM_MULTI_VM
-   if (argc < 2) {
--    printf("Usage: tpmd clear|save|deactivated\n" );
-+    error("Usage: tpmd clear|save|deactivated\n" );
-+#else
-+  if (argc < 4) {
-+    error("Usage: tpmd clear|save|deactivated pvm|hvm vtpmid\n" );
-+#endif
-       return -1;
-   }
-
-+#ifndef VTPM_MULTI_VM
-+  /* setup type of vm */
-+  if (!strcmp(argv[2], "pvm")) {
-+    type = VTPM_TYPE_PVM; // Get commands from vTPM Manager through fifo
-+  } else if (!strcmp(argv[2], "hvm")) {
-+    type = VTPM_TYPE_HVM; // Get commands from qemu via socket
-+  } else {
-+    error("invalid vTPM type '%s'.\n", argv[2]);
-+  }
-+
-+  dmi_id = atoi(argv[3]);
-+
-+  if (type == VTPM_TYPE_PVM) {
-+    vtpm_rx_file = malloc(10 + strlen(PVM_RX_FIFO_D));
-+    sprintf(vtpm_rx_file, PVM_RX_FIFO_D, (uint32_t) dmi_id);
-+  } else {
-+    vtpm_rx_file = malloc(10 + strlen(HVM_RX_FIFO_D));
-+    sprintf(vtpm_rx_file, HVM_RX_FIFO_D, (uint32_t) dmi_id);
-+
-+    if ( (sockfd = socket(PF_UNIX,SOCK_STREAM,0)) < 0) {
-+          error("Unable to create socket. errno = %d\n", errno);
-+      exit (-1);
-+    }
-+
-+    memset(&addr, 0, sizeof(addr));
-+    addr.sun_family = AF_UNIX;
-+    strcpy(addr.sun_path,vtpm_rx_file );
-+    unlink(addr.sun_path);
-+  }
-+#endif
-+
-+#ifdef VTPM_MULTI_VM
-+  info("Initializing tpm state: %s\n", argv[1]);
-+#else
-+  info("Initializing tpm state: %s, type: %s, id: %d\n", argv[1],
argv[2], dmi_id);
-+#endif
-+
-   /* initialize TPM emulator */
-   if (!strcmp(argv[1], "clear")) {
--    printf("Initializing tpm: %s\n", argv[1]);
-     tpm_emulator_init(1);
--  } else if (!strcmp(argv[1], "save")) {
--    printf("Initializing tpm: %s\n", argv[1]);
-+  } else if (!strcmp(argv[1], "save")) {
-     tpm_emulator_init(2);
-   } else if (!strcmp(argv[1], "deactivated")) {
--    printf("Initializing tpm: %s\n", argv[1]);
-     tpm_emulator_init(3);
-   } else {
--    printf("invalid startup mode '%s'; must be 'clear', "
-+    error("invalid startup mode '%s'; must be 'clear', "
-       "'save' (default) or 'deactivated", argv[1]);
-     return -1;
-   }
--
--  if ( stat(TPM_RX_FNAME, &file_info) == -1) {
--    if ( mkfifo(TPM_RX_FNAME, S_IWUSR | S_IRUSR ) ) {
--      printf("Failed to create fifo %s.\n", TPM_RX_FNAME);
--      return -1;
--    }
--  }
--
--  if ( stat(TPM_TX_FNAME, &file_info) == -1) {
--    if ( mkfifo(TPM_TX_FNAME, S_IWUSR | S_IRUSR ) ) {
--      printf("Failed to create fifo %s.\n", TPM_TX_FNAME);
--      return -1;
--    }
--  }
--
-+ 
-   while (1) {
- abort_command:
--    if (tpm_rx_fh < 0) {
--      tpm_rx_fh = open(TPM_RX_FNAME, O_RDONLY);
-+    if (vtpm_rx_fh < 0) {
-+#ifdef VTPM_MUTLI_VM
-+      vtpm_rx_fh = open(DEV_BE, O_RDWR);
-+#else
-+      if (type == VTPM_TYPE_PVM) {
-+        vtpm_rx_fh = open(vtpm_rx_file, O_RDONLY);
-+      } else {
-+        if (bind(sockfd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
-+          error("Unable to bind(). errno = %d\n", errno);
-+          exit (-1);
-+        }
-+
-+        if (listen(sockfd, 10) <0) {
-+          error("Unable to listen(). errno = %d\n", errno);
-+          exit (-1);
-+        }
-+
-+        memset(&client_addr, 0, sizeof(client_addr));
-+        client_length = sizeof(client_addr);
-+
-+        vtpm_rx_fh = vtpm_tx_fh = accept(sockfd, (struct sockaddr
*)&client_addr, &client_length);
-+      }
-+#endif
-     }
-    
--    if (tpm_rx_fh < 0) {
--      printf("ERROR: failed to open devices to listen to guest.\n");
-+    if (vtpm_rx_fh < 0) {
-+      error("Failed to open devices to listen to guest.\n");
-       return -1;
-     }
-    
--    if (tpm_tx_fh < 0) {
--      tpm_tx_fh = open(TPM_TX_FNAME, O_WRONLY);
--    }
--
--    if (tpm_tx_fh < 0) {
--      printf("ERROR: failed to open devices to respond to guest.\n");
--      return -1;
--    }
--
--    in_size = read(tpm_rx_fh, in, BUFFER_SIZE);
-+    in_size = read(vtpm_rx_fh, in, BUFFER_SIZE);
-     if (in_size < 6) { // Magic size of minium TPM command
--      printf("Recv[%d] to small: 0x", in_size);
-+      info("Recv incomplete command of %d bytes.", in_size);
-       if (in_size <= 0) {
--          close(tpm_rx_fh);
--          tpm_rx_fh = -1;
-+          close(vtpm_rx_fh);
-+          vtpm_rx_fh = -1;
-           goto abort_command;
-       }
-     } else {
--      printf("Recv[%d]: 0x", in_size);
-+      debug_nostop("Recv[%d]: 0x", in_size);
-       for (i=0; i< in_size; i++)
--        printf("%x ", in[i]);
--      printf("\n");
-+        debug_more("%x ", in[i]);
-+      debug_more("\n");
-     }
-
--   
--    if (tpm_handle_command(in, in_size, &out, &out_size) != 0) {
--        printf("ERROR: Handler Failed.\n");
-+    if (guest_id == -1) {
-+        guest_id = *((uint32_t *) in);
-+    } else {
-+        if (guest_id != *((uint32_t *) in) ) {
-+            error("WARNING: More than one guest attached\n");
-+        }
-+    }
-+
-+    if (vtpm_tx_fh < 0) {
-+#ifdef VTPM_MUTLI_VM
-+      vtpm_tx_fh = open(DEV_BE, O_RDWR);
-+      vtpm_rx_fh = vtpm_tx_fh;
-+#else
-+      if (type == VTPM_TYPE_PVM) {
-+        vtpm_tx_fh = open(PVM_TX_FIFO, O_WRONLY);
-+      } // No need to open the other direction for HVM
-+#endif
-+    }
-+
-+    if (vtpm_tx_fh < 0) {
-+      error("Failed to open devices to respond to guest.\n");
-+      return -1;
-+    }
-+
-+    // Handle the command, but skip the domain id header   
-+    if (tpm_handle_command(in + sizeof(uint32_t), in_size -
sizeof(uint32_t), &out, &out_size) != 0) {
-+      error("Handler Failed.\n");
-     }
-
--    written = write(tpm_tx_fh, out, out_size);
-+    addressed_out = (uint8_t *) tpm_malloc(sizeof(uint32_t) + out_size);
-+    *(uint32_t *) addressed_out = *(uint32_t *) in;
-+    memcpy(addressed_out + sizeof(uint32_t), out, out_size);
-+
-+    written = write(vtpm_tx_fh, addressed_out, out_size +
sizeof(uint32_t));
-
--    if (written != out_size ) {
--      printf("ERROR: Part of response not written %d/%d.\nAttempt: ",
written, out_size);
-+    if (written != out_size + sizeof(uint32_t)) {
-+      error("Part of response not written %d/%d.\n", written, out_size);
-     } else {
--      printf("Sent[%Zu]: ", out_size);
-+      debug_nostop("Sent[%Zu]: ", out_size + sizeof(uint32_t));
-+      for (i=0; i< out_size+ sizeof(uint32_t); i++)
-+        debug_more("%x ", addressed_out[i]);
-+      debug_more("\n");
-     }
--    for (i=0; i< out_size; i++)
--      printf("%x ", out[i]);
--    printf("\n");
-     tpm_free(out);
-+    tpm_free(addressed_out);
-
-   } // loop
-
-   tpm_emulator_shutdown();
-
--  close(tpm_tx_fh);
--  close(tpm_rx_fh);
-+  close(vtpm_tx_fh);
-+#ifndef VTPM_MUTLI_VM
-+  close(vtpm_rx_fh);
-+  free (vtpm_rx_file);
-+#endif
-
- }




Attachment: smime.p7s
Description: S/MIME Cryptographic Signature

_______________________________________________
Xen-devel mailing list
Xen-devel@xxxxxxxxxxxxx
http://lists.xen.org/xen-devel

 


Rackspace

Lists.xenproject.org is hosted with RackSpace, monitoring our
servers 24x7x365 and backed by RackSpace's Fanatical Support®.