Files
Pyarmor-Static-Unpack-1shot/pyc_string.cpp

122 lines
3.1 KiB
C++
Raw Normal View History

2011-10-23 17:48:10 -07:00
#include "pyc_string.h"
#include "pyc_module.h"
2009-07-24 08:35:21 +00:00
#include "data.h"
#include <cstring>
/* PycString */
void PycString::load(PycData* stream, PycModule* mod)
{
if (m_value)
delete[] m_value;
2009-07-24 08:35:21 +00:00
if (type() == TYPE_STRINGREF) {
PycRef<PycString> str = mod->getIntern(stream->get32());
m_length = str->length();
if (m_length) {
m_value = new char[m_length+1];
memcpy(m_value, str->value(), m_length);
m_value[m_length] = 0;
} else {
m_value = 0;
}
} else {
m_length = stream->get32();
if (m_length) {
m_value = new char[m_length+1];
stream->getBuffer(m_length, m_value);
m_value[m_length] = 0;
} else {
m_value = 0;
}
if (type() == TYPE_INTERNED)
mod->intern(this);
}
}
2009-07-24 19:52:47 +00:00
2009-07-24 21:15:51 +00:00
bool PycString::isEqual(PycRef<PycObject> obj) const
{
if (type() != obj->type())
return false;
2009-07-24 21:15:51 +00:00
PycRef<PycString> strObj = obj.cast<PycString>();
return isEqual(strObj->m_value);
2009-07-24 21:15:51 +00:00
}
bool PycString::isEqual(const char* str) const
{
if (m_value == str)
return true;
return (strcmp(m_value, str) == 0);
}
2009-07-24 19:52:47 +00:00
void OutputString(PycRef<PycString> str, char prefix, bool triple, FILE* F)
2009-07-24 19:52:47 +00:00
{
if (prefix != 0)
fputc(prefix, F);
2009-07-24 19:52:47 +00:00
const char* ch = str->value();
int len = str->length();
if (ch == 0) {
fprintf(F, "''");
2009-07-24 19:52:47 +00:00
return;
}
// Determine preferred quote style (Emulate Python's method)
bool useQuotes = false;
while (len--) {
if (*ch == '\'') {
useQuotes = true;
} else if (*ch == '"') {
useQuotes = false;
break;
}
ch++;
}
ch = str->value();
len = str->length();
// Output the string
if (triple)
fprintf(F, useQuotes ? "\"\"\"" : "'''");
else
fputc(useQuotes ? '"' : '\'', F);
while (len--) {
if (*ch < 0x20 || *ch == 0x7F) {
2009-07-24 19:52:47 +00:00
if (*ch == '\r') {
fprintf(F, "\\r");
} else if (*ch == '\n') {
if (triple)
2009-07-24 19:52:47 +00:00
fputc('\n', F);
else
fprintf(F, "\\n");
} else if (*ch == '\t') {
fprintf(F, "\\t");
} else {
fprintf(F, "\\x%x", (*ch & 0xFF));
2009-07-24 19:52:47 +00:00
}
} else if ((unsigned char)(*ch) >= 0x80) {
if (str->type() == PycObject::TYPE_UNICODE) {
// Unicode stored as UTF-8... Let the stream interpret it
fputc(*ch, F);
} else {
fprintf(F, "\\x%x", (*ch & 0xFF));
}
2009-07-24 19:52:47 +00:00
} else {
if (!useQuotes && *ch == '\'')
2009-07-24 19:52:47 +00:00
fprintf(F, "\\'");
else if (useQuotes && *ch == '"')
2009-07-24 19:52:47 +00:00
fprintf(F, "\\\"");
2011-10-23 19:33:24 -07:00
else if (*ch == '\\')
fprintf(F, "\\\\");
2009-07-24 19:52:47 +00:00
else
fputc(*ch, F);
}
ch++;
}
if (triple)
fprintf(F, useQuotes ? "\"\"\"" : "'''");
else
fputc(useQuotes ? '"' : '\'', F);
2009-07-24 19:52:47 +00:00
}