• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /** @file
2 Python Utility
3 
4 Copyright (c) 2009 - 2014, Intel Corporation. All rights reserved.<BR>
5 This program and the accompanying materials are licensed and made available
6 under the terms and conditions of the BSD License which accompanies this
7 distribution.  The full text of the license may be found at
8 http://opensource.org/licenses/bsd-license.php
9 
10 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
11 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
12 
13 **/
14 
15 #include <Python.h>
16 #include <Windows.h>
17 #include <Common/UefiBaseTypes.h>
18 
19 /*
20  SaveFileToDisk(FilePath, Content)
21 */
22 STATIC
23 PyObject*
SaveFileToDisk(PyObject * Self,PyObject * Args)24 SaveFileToDisk (
25   PyObject    *Self,
26   PyObject    *Args
27   )
28 {
29   CHAR8         *File;
30   UINT8         *Data;
31   UINTN         DataLength;
32   UINTN         WriteBytes;
33   UINTN         Status;
34   HANDLE        FileHandle;
35   PyObject      *ReturnValue = Py_False;
36 
37   Status = PyArg_ParseTuple(
38             Args,
39             "ss#",
40             &File,
41             &Data,
42             &DataLength
43             );
44   if (Status == 0) {
45     return NULL;
46   }
47 
48   FileHandle = CreateFile(
49                 File,
50                 GENERIC_WRITE,
51                 FILE_SHARE_WRITE|FILE_SHARE_READ|FILE_SHARE_DELETE,
52                 NULL,
53                 CREATE_ALWAYS,
54                 FILE_ATTRIBUTE_NORMAL,
55                 NULL
56                 );
57   if (FileHandle == INVALID_HANDLE_VALUE) {
58     PyErr_SetString(PyExc_Exception, "File creation failure");
59     return NULL;
60   }
61 
62   while (WriteFile(FileHandle, Data, DataLength, &WriteBytes, NULL)) {
63     if (DataLength <= WriteBytes) {
64       DataLength = 0;
65       break;
66     }
67 
68     Data += WriteBytes;
69     DataLength -= WriteBytes;
70   }
71 
72   if (DataLength != 0) {
73     // file saved unsuccessfully
74     PyErr_SetString(PyExc_Exception, "File write failure");
75     goto Done;
76   }
77 
78   //
79   // Flush buffer may slow down the whole build performance (average 10s slower)
80   //
81   //if (!FlushFileBuffers(FileHandle)) {
82   //  PyErr_SetString(PyExc_Exception, "File flush failure");
83   //  goto Done;
84   //}
85 
86   // success!
87   ReturnValue = Py_True;
88 
89 Done:
90   CloseHandle(FileHandle);
91   return ReturnValue;
92 }
93 
94 STATIC INT8 SaveFileToDiskDocs[] = "SaveFileToDisk(): Make sure the file is saved to disk\n";
95 
96 STATIC PyMethodDef PyUtility_Funcs[] = {
97   {"SaveFileToDisk", (PyCFunction)SaveFileToDisk, METH_VARARGS, SaveFileToDiskDocs},
98   {NULL, NULL, 0, NULL}
99 };
100 
101 PyMODINIT_FUNC
initPyUtility(VOID)102 initPyUtility(VOID) {
103   Py_InitModule3("PyUtility", PyUtility_Funcs, "Utilties Module Implemented C Language");
104 }
105 
106 
107