1 // Copyright (c) 2006, Google Inc.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 //     * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 //     * Redistributions in binary form must reproduce the above
11 // copyright notice, this list of conditions and the following disclaimer
12 // in the documentation and/or other materials provided with the
13 // distribution.
14 //     * Neither the name of Google Inc. nor the names of its
15 // contributors may be used to endorse or promote products derived from
16 // this software without specific prior written permission.
17 //
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 
30 // Tool to upload an exe/dll and its associated symbols to an HTTP server.
31 // The PDB file is located automatically, using the path embedded in the
32 // executable.  The upload is sent as a multipart/form-data POST request,
33 // with the following parameters:
34 //  code_file: the basename of the module, e.g. "app.exe"
35 //  debug_file: the basename of the debugging file, e.g. "app.pdb"
36 //  debug_identifier: the debug file's identifier, usually consisting of
37 //                    the guid and age embedded in the pdb, e.g.
38 //                    "11111111BBBB3333DDDD555555555555F"
39 //  product: the HTTP-friendly product name, e.g. "MyApp"
40 //  version: the file version of the module, e.g. "1.2.3.4"
41 //  os: the operating system that the module was built for, always
42 //      "windows" in this implementation.
43 //  cpu: the CPU that the module was built for, typically "x86".
44 //  symbol_file: the contents of the breakpad-format symbol file
45 
46 #include <windows.h>
47 #include <dbghelp.h>
48 #include <wininet.h>
49 
50 #include <cstdio>
51 #include <map>
52 #include <string>
53 #include <vector>
54 
55 #include "common/windows/string_utils-inl.h"
56 
57 #include "common/windows/http_upload.h"
58 #include "common/windows/pdb_source_line_writer.h"
59 #include "common/windows/symbol_collector_client.h"
60 
61 using std::string;
62 using std::wstring;
63 using std::vector;
64 using std::map;
65 using google_breakpad::HTTPUpload;
66 using google_breakpad::SymbolCollectorClient;
67 using google_breakpad::SymbolStatus;
68 using google_breakpad::UploadUrlResponse;
69 using google_breakpad::CompleteUploadResult;
70 using google_breakpad::PDBModuleInfo;
71 using google_breakpad::PDBSourceLineWriter;
72 using google_breakpad::WindowsStringUtils;
73 
74 // Extracts the file version information for the given filename,
75 // as a string, for example, "1.2.3.4".  Returns true on success.
GetFileVersionString(const wchar_t * filename,wstring * version)76 static bool GetFileVersionString(const wchar_t *filename, wstring *version) {
77   DWORD handle;
78   DWORD version_size = GetFileVersionInfoSize(filename, &handle);
79   if (version_size < sizeof(VS_FIXEDFILEINFO)) {
80     return false;
81   }
82 
83   vector<char> version_info(version_size);
84   if (!GetFileVersionInfo(filename, handle, version_size, &version_info[0])) {
85     return false;
86   }
87 
88   void *file_info_buffer = NULL;
89   unsigned int file_info_length;
90   if (!VerQueryValue(&version_info[0], L"\\",
91                      &file_info_buffer, &file_info_length)) {
92     return false;
93   }
94 
95   // The maximum value of each version component is 65535 (0xffff),
96   // so the max length is 24, including the terminating null.
97   wchar_t ver_string[24];
98   VS_FIXEDFILEINFO *file_info =
99     reinterpret_cast<VS_FIXEDFILEINFO*>(file_info_buffer);
100   swprintf(ver_string, sizeof(ver_string) / sizeof(ver_string[0]),
101            L"%d.%d.%d.%d",
102            file_info->dwFileVersionMS >> 16,
103            file_info->dwFileVersionMS & 0xffff,
104            file_info->dwFileVersionLS >> 16,
105            file_info->dwFileVersionLS & 0xffff);
106 
107   // remove when VC++7.1 is no longer supported
108   ver_string[sizeof(ver_string) / sizeof(ver_string[0]) - 1] = L'\0';
109 
110   *version = ver_string;
111   return true;
112 }
113 
114 // Creates a new temporary file and writes the symbol data from the given
115 // exe/dll file to it.  Returns the path to the temp file in temp_file_path
116 // and information about the pdb in pdb_info.
DumpSymbolsToTempFile(const wchar_t * file,wstring * temp_file_path,PDBModuleInfo * pdb_info)117 static bool DumpSymbolsToTempFile(const wchar_t *file,
118                                   wstring *temp_file_path,
119                                   PDBModuleInfo *pdb_info) {
120   google_breakpad::PDBSourceLineWriter writer;
121   // Use EXE_FILE to get information out of the exe/dll in addition to the
122   // pdb.  The name and version number of the exe/dll are of value, and
123   // there's no way to locate an exe/dll given a pdb.
124   if (!writer.Open(file, PDBSourceLineWriter::EXE_FILE)) {
125     return false;
126   }
127 
128   wchar_t temp_path[_MAX_PATH];
129   if (GetTempPath(_MAX_PATH, temp_path) == 0) {
130     return false;
131   }
132 
133   wchar_t temp_filename[_MAX_PATH];
134   if (GetTempFileName(temp_path, L"sym", 0, temp_filename) == 0) {
135     return false;
136   }
137 
138   FILE *temp_file = NULL;
139 #if _MSC_VER >= 1400  // MSVC 2005/8
140   if (_wfopen_s(&temp_file, temp_filename, L"w") != 0)
141 #else  // _MSC_VER >= 1400
142   // _wfopen_s was introduced in MSVC8.  Use _wfopen for earlier environments.
143   // Don't use it with MSVC8 and later, because it's deprecated.
144   if (!(temp_file = _wfopen(temp_filename, L"w")))
145 #endif  // _MSC_VER >= 1400
146   {
147     return false;
148   }
149 
150   bool success = writer.WriteSymbols(temp_file);
151   fclose(temp_file);
152   if (!success) {
153     _wunlink(temp_filename);
154     return false;
155   }
156 
157   *temp_file_path = temp_filename;
158 
159   return writer.GetModuleInfo(pdb_info);
160 }
161 
DoSymUploadV2(const wchar_t * api_url,const wchar_t * api_key,const wstring & debug_file,const wstring & debug_id,const wstring & symbol_file,bool force)162 static bool DoSymUploadV2(
163     const wchar_t* api_url,
164     const wchar_t* api_key,
165     const wstring& debug_file,
166     const wstring& debug_id,
167     const wstring& symbol_file,
168     bool force) {
169   wstring url(api_url);
170   wstring key(api_key);
171 
172   if (!force) {
173     SymbolStatus symbolStatus = SymbolCollectorClient::CheckSymbolStatus(
174       url,
175       key,
176       debug_file,
177       debug_id);
178     if (symbolStatus == SymbolStatus::Found) {
179       wprintf(L"Symbol file already exists, upload aborted."
180         L" Use \"-f\" to overwrite.\n");
181       return true;
182     }
183     else if (symbolStatus == SymbolStatus::Unknown) {
184       wprintf(L"Failed to get check for existing symbol.\n");
185       return false;
186     }
187   }
188 
189   UploadUrlResponse uploadUrlResponse;
190   if (!SymbolCollectorClient::CreateUploadUrl(
191       url,
192       key,
193       &uploadUrlResponse)) {
194     wprintf(L"Failed to create upload URL.\n");
195     return false;
196   }
197 
198   wstring signed_url = uploadUrlResponse.upload_url;
199   wstring upload_key = uploadUrlResponse.upload_key;
200   wstring response;
201   int response_code;
202   bool success = HTTPUpload::SendPutRequest(
203     signed_url,
204     symbol_file,
205     /* timeout = */ NULL,
206     &response,
207     &response_code);
208   if (!success) {
209     wprintf(L"Failed to send symbol file.\n");
210     wprintf(L"Response code: %ld\n", response_code);
211     wprintf(L"Response:\n");
212     wprintf(L"%s\n", response.c_str());
213     return false;
214   }
215   else if (response_code == 0) {
216     wprintf(L"Failed to send symbol file: No response code\n");
217     return false;
218   }
219   else if (response_code != 200) {
220     wprintf(L"Failed to send symbol file: Response code %ld\n", response_code);
221     wprintf(L"Response:\n");
222     wprintf(L"%s\n", response.c_str());
223     return false;
224   }
225 
226   CompleteUploadResult completeUploadResult =
227     SymbolCollectorClient::CompleteUpload(
228       url,
229       key,
230       upload_key,
231       debug_file,
232       debug_id);
233   if (completeUploadResult == CompleteUploadResult::Error) {
234     wprintf(L"Failed to complete upload.\n");
235     return false;
236   }
237   else if (completeUploadResult == CompleteUploadResult::DuplicateData) {
238     wprintf(L"Uploaded file checksum matched existing file checksum,"
239       L" no change necessary.\n");
240   }
241   else {
242     wprintf(L"Successfully sent the symbol file.\n");
243   }
244 
245   return true;
246 }
247 
printUsageAndExit()248 __declspec(noreturn) void printUsageAndExit() {
249   wprintf(L"Usage:\n\n"
250           L"    symupload [--timeout NN] [--product product_name] ^\n"
251           L"              <file.exe|file.dll> <symbol upload URL> ^\n"
252           L"              [...<symbol upload URLs>]\n\n");
253   wprintf(L"  - Timeout is in milliseconds, or can be 0 to be unlimited.\n");
254   wprintf(L"  - product_name is an HTTP-friendly product name. It must only\n"
255           L"    contain an ascii subset: alphanumeric and punctuation.\n"
256           L"    This string is case-sensitive.\n\n");
257   wprintf(L"Example:\n\n"
258           L"    symupload.exe --timeout 0 --product Chrome ^\n"
259           L"        chrome.dll http://no.free.symbol.server.for.you\n");
260   wprintf(L"\n");
261   wprintf(L"sym-upload-v2 usage:\n"
262           L"    symupload -p [-f] <file.exe|file.dll> <API-URL> <API-key>\n");
263   wprintf(L"\n");
264   wprintf(L"sym_upload_v2 Options:\n");
265   wprintf(L"    <API-URL> is the sym_upload_v2 API URL.\n");
266   wprintf(L"    <API-key> is a secret used to authenticate with the API.\n");
267   wprintf(L"    -p:\t Use sym_upload_v2 protocol.\n");
268   wprintf(L"    -f:\t Force symbol upload if already exists.\n");
269 
270   exit(0);
271 }
272 
wmain(int argc,wchar_t * argv[])273 int wmain(int argc, wchar_t *argv[]) {
274   const wchar_t *module;
275   const wchar_t *product = nullptr;
276   int timeout = -1;
277   int currentarg = 1;
278   bool use_sym_upload_v2 = false;
279   bool force = false;
280   const wchar_t* api_url = nullptr;
281   const wchar_t* api_key = nullptr;
282   while (argc > currentarg + 1) {
283     if (!wcscmp(L"--timeout", argv[currentarg])) {
284       timeout = _wtoi(argv[currentarg + 1]);
285       currentarg += 2;
286       continue;
287     }
288     if (!wcscmp(L"--product", argv[currentarg])) {
289       product = argv[currentarg + 1];
290       currentarg += 2;
291       continue;
292     }
293     if (!wcscmp(L"-p", argv[currentarg])) {
294       use_sym_upload_v2 = true;
295       ++currentarg;
296       continue;
297     }
298     if (!wcscmp(L"-f", argv[currentarg])) {
299       force = true;
300       ++currentarg;
301       continue;
302     }
303     break;
304   }
305 
306   if (argc >= currentarg + 2)
307     module = argv[currentarg++];
308   else
309     printUsageAndExit();
310 
311   wstring symbol_file;
312   PDBModuleInfo pdb_info;
313   if (!DumpSymbolsToTempFile(module, &symbol_file, &pdb_info)) {
314     fwprintf(stderr, L"Could not get symbol data from %s\n", module);
315     return 1;
316   }
317 
318   wstring code_file = WindowsStringUtils::GetBaseName(wstring(module));
319   wstring file_version;
320   // Don't make a missing version a hard error.  Issue a warning, and let the
321   // server decide whether to reject files without versions.
322   if (!GetFileVersionString(module, &file_version)) {
323     fwprintf(stderr, L"Warning: Could not get file version for %s\n", module);
324   }
325 
326   bool success = true;
327 
328   if (use_sym_upload_v2) {
329     if (argc >= currentarg + 2) {
330       api_url = argv[currentarg++];
331       api_key = argv[currentarg++];
332 
333       success = DoSymUploadV2(
334         api_url,
335         api_key,
336         pdb_info.debug_file,
337         pdb_info.debug_identifier,
338         symbol_file,
339         force);
340     } else {
341       printUsageAndExit();
342     }
343   } else {
344     map<wstring, wstring> parameters;
345     parameters[L"code_file"] = code_file;
346     parameters[L"debug_file"] = pdb_info.debug_file;
347     parameters[L"debug_identifier"] = pdb_info.debug_identifier;
348     parameters[L"os"] = L"windows";  // This version of symupload is Windows-only
349     parameters[L"cpu"] = pdb_info.cpu;
350 
351     map<wstring, wstring> files;
352     files[L"symbol_file"] = symbol_file;
353 
354     if (!file_version.empty()) {
355       parameters[L"version"] = file_version;
356     }
357 
358     // Don't make a missing product name a hard error.  Issue a warning and let
359     // the server decide whether to reject files without product name.
360     if (product) {
361       parameters[L"product"] = product;
362     }
363     else {
364       fwprintf(
365         stderr,
366         L"Warning: No product name (flag --product) was specified for %s\n",
367         module);
368     }
369 
370     while (currentarg < argc) {
371       int response_code;
372       if (!HTTPUpload::SendMultipartPostRequest(argv[currentarg], parameters, files,
373           timeout == -1 ? NULL : &timeout,
374           nullptr, &response_code)) {
375         success = false;
376         fwprintf(stderr,
377           L"Symbol file upload to %s failed. Response code = %ld\n",
378           argv[currentarg], response_code);
379       }
380       currentarg++;
381     }
382   }
383 
384   _wunlink(symbol_file.c_str());
385 
386   if (success) {
387     wprintf(L"Uploaded breakpad symbols for windows-%s/%s/%s (%s %s)\n",
388             pdb_info.cpu.c_str(), pdb_info.debug_file.c_str(),
389             pdb_info.debug_identifier.c_str(), code_file.c_str(),
390             file_version.c_str());
391   }
392 
393   return success ? 0 : 1;
394 }
395