2023-09-11 15:59:11 +00:00
# macOS Objective-C
< details >
2023-12-31 00:07:27 +00:00
< summary > < strong > Aprenda hacking no AWS do zero ao herói com< / strong > < a href = "https://training.hacktricks.xyz/courses/arte" > < strong > htARTE (HackTricks AWS Red Team Expert)< / strong > < / a > < strong > !< / strong > < / summary >
2023-09-11 15:59:11 +00:00
2023-12-31 00:07:27 +00:00
Outras formas de apoiar o HackTricks:
* Se você quer ver sua **empresa anunciada no HackTricks** ou **baixar o HackTricks em PDF** , confira os [**PLANOS DE ASSINATURA** ](https://github.com/sponsors/carlospolop )!
* Adquira o [**material oficial PEASS & HackTricks** ](https://peass.creator-spring.com )
* Descubra [**A Família PEASS** ](https://opensea.io/collection/the-peass-family ), nossa coleção de [**NFTs** ](https://opensea.io/collection/the-peass-family ) exclusivos
* **Junte-se ao grupo** 💬 [**Discord** ](https://discord.gg/hRep4RUj7f ) ou ao [**grupo do telegram** ](https://t.me/peass ) ou **siga-me** no **Twitter** 🐦 [**@carlospolopm** ](https://twitter.com/carlospolopm )**.**
* **Compartilhe suas técnicas de hacking enviando PRs para os repositórios do GitHub** [**HackTricks** ](https://github.com/carlospolop/hacktricks ) e [**HackTricks Cloud** ](https://github.com/carlospolop/hacktricks-cloud ).
2023-09-11 15:59:11 +00:00
< / details >
2023-06-01 11:07:04 +00:00
## Objective-C
{% hint style="danger" %}
2023-12-31 00:07:27 +00:00
Observe que programas escritos em Objective-C **mantêm** suas declarações de classe **quando** **compilados** em [binários Mach-O ](macos-files-folders-and-binaries/universal-binaries-and-mach-o-format.md ). Tais declarações de classe **incluem** o nome e tipo de:
2023-06-01 11:07:04 +00:00
{% endhint %}
2023-06-06 18:56:34 +00:00
* A classe
* Os métodos da classe
* As variáveis de instância da classe
2023-06-01 11:07:04 +00:00
2023-12-31 00:07:27 +00:00
Você pode obter essas informações usando [**class-dump** ](https://github.com/nygard/class-dump ):
2023-06-01 11:07:04 +00:00
```bash
class-dump Kindle.app
```
2023-12-31 00:07:27 +00:00
Observe que esses nomes podem ser ofuscados para tornar a reversão do binário mais difícil.
## Classes, Métodos & Objetos
2023-05-08 22:07:46 +00:00
2023-12-31 00:07:27 +00:00
### Interface, Propriedades & Métodos
2023-05-08 22:07:46 +00:00
```objectivec
// Declare the interface of the class
@interface MyVehicle : NSObject
// Declare the properties
@property NSString *vehicleType;
@property int numberOfWheels;
// Declare the methods
- (void)startEngine;
- (void)addWheels:(int)value;
@end
```
2023-06-06 18:56:34 +00:00
### **Classe**
2023-05-08 22:07:46 +00:00
```objectivec
@implementation MyVehicle : NSObject
// No need to indicate the properties, only define methods
- (void)startEngine {
2023-09-11 15:59:11 +00:00
NSLog(@"Engine started");
2023-05-08 22:07:46 +00:00
}
- (void)addWheels:(int)value {
2023-09-11 15:59:11 +00:00
self.numberOfWheels += value;
2023-05-08 22:07:46 +00:00
}
@end
```
2023-12-31 00:07:27 +00:00
### **Objeto & Método de Chamada**
2023-05-08 22:07:46 +00:00
2023-12-31 00:07:27 +00:00
Para criar uma instância de uma classe, o método ** `alloc` ** é chamado, o qual **aloca memória** para cada **propriedade** e **zera** essas alocações. Em seguida, ** `init` ** é chamado, o qual **inicializa as propriedades** com os **valores necessários** .
2023-05-08 22:07:46 +00:00
```objectivec
// Something like this:
MyVehicle *newVehicle = [[MyVehicle alloc] init];
// Which is usually expressed as:
MyVehicle *newVehicle = [MyVehicle new];
// To call a method
// [myClassInstance nameOfTheMethodFirstParam:param1 secondParam:param2]
[newVehicle addWheels:4];
```
2023-06-06 18:56:34 +00:00
### **Métodos de Classe**
2023-05-08 22:07:46 +00:00
2023-12-31 00:07:27 +00:00
Métodos de classe são definidos com o **sinal de mais** (+) e não o hífen (-) que é usado com métodos de instância. Como o método de classe **NSString** ** `stringWithString` **:
2023-05-08 22:07:46 +00:00
```objectivec
+ (id)stringWithString:(NSString *)aString;
```
2023-12-31 00:07:27 +00:00
### Setter & Getter
2023-05-08 22:07:46 +00:00
2023-12-31 00:07:27 +00:00
Para **definir** & **obter** propriedades, você pode fazer isso com uma **notação de ponto** ou como se estivesse **chamando um método** :
2023-05-08 22:07:46 +00:00
```objectivec
// Set
newVehicle.numberOfWheels = 2;
[newVehicle setNumberOfWheels:3];
// Get
NSLog(@"Number of wheels: %i", newVehicle.numberOfWheels);
NSLog(@"Number of wheels: %i", [newVehicle numberOfWheels]);
```
2023-06-06 18:56:34 +00:00
### **Variáveis de Instância**
2023-05-08 22:07:46 +00:00
2023-12-31 00:07:27 +00:00
Alternativamente aos métodos setter & getter, você pode usar variáveis de instância. Essas variáveis têm o mesmo nome das propriedades, mas começam com um "\_":
2023-05-08 22:07:46 +00:00
```objectivec
- (void)makeLongTruck {
2023-09-11 15:59:11 +00:00
_numberOfWheels = +10000;
NSLog(@"Number of wheels: %i", self.numberOfLeaves);
2023-05-08 22:07:46 +00:00
}
```
2023-06-06 18:56:34 +00:00
### Protocolos
2023-05-08 22:07:46 +00:00
2023-06-06 18:56:34 +00:00
Protocolos são conjuntos de declarações de métodos (sem propriedades). Uma classe que implementa um protocolo implementa os métodos declarados.
2023-05-09 00:02:08 +00:00
2023-12-31 00:07:27 +00:00
Existem 2 tipos de métodos: **obrigatórios** e **opcionais** . Por **padrão** , um método é **obrigatório** (mas você também pode indicar isso com a tag ** `@required` **). Para indicar que um método é opcional, use ** `@optional` **.
2023-05-09 00:02:08 +00:00
```objectivec
@protocol myNewProtocol
- (void) method1; //mandatory
@required
- (void) method2; //mandatory
@optional
- (void) method3; //optional
@end
```
2023-06-06 18:56:34 +00:00
### Tudo junto
2023-05-09 00:02:08 +00:00
```objectivec
// gcc -framework Foundation test_obj.m -o test_obj
#import <Foundation/Foundation.h>
@protocol myVehicleProtocol
- (void) startEngine; //mandatory
@required
- (void) addWheels:(int)value; //mandatory
@optional
- (void) makeLongTruck; //optional
@end
@interface MyVehicle : NSObject < myVehicleProtocol >
@property int numberOfWheels;
- (void)startEngine;
- (void)addWheels:(int)value;
- (void)makeLongTruck;
@end
@implementation MyVehicle : NSObject
- (void)startEngine {
2023-09-11 15:59:11 +00:00
NSLog(@"Engine started");
2023-05-09 00:02:08 +00:00
}
- (void)addWheels:(int)value {
2023-09-11 15:59:11 +00:00
self.numberOfWheels += value;
2023-05-09 00:02:08 +00:00
}
- (void)makeLongTruck {
2023-09-11 15:59:11 +00:00
_numberOfWheels = +10000;
NSLog(@"Number of wheels: %i", self.numberOfWheels);
2023-05-09 00:02:08 +00:00
}
@end
int main() {
2023-09-11 15:59:11 +00:00
MyVehicle* mySuperCar = [MyVehicle new];
[mySuperCar startEngine];
mySuperCar.numberOfWheels = 4;
NSLog(@"Number of wheels: %i", mySuperCar.numberOfWheels);
[mySuperCar setNumberOfWheels:3];
NSLog(@"Number of wheels: %i", mySuperCar.numberOfWheels);
[mySuperCar makeLongTruck];
2023-05-09 00:02:08 +00:00
}
```
2023-06-06 18:56:34 +00:00
### Classes Básicas
2023-05-09 00:02:08 +00:00
#### String
{% code overflow="wrap" %}
```objectivec
// NSString
NSString *bookTitle = @"The Catcher in the Rye";
NSString *bookAuthor = [[NSString alloc] initWithCString:"J.D. Salinger" encoding:NSUTF8StringEncoding];
NSString *bookPublicationYear = [NSString stringWithCString:"1951" encoding:NSUTF8StringEncoding];
```
2023-12-31 00:07:27 +00:00
{% endcode %}
Classes básicas são **imutáveis** , então para adicionar uma string a uma existente **é necessário criar um novo NSString** .
2023-05-09 00:02:08 +00:00
{% code overflow="wrap" %}
```objectivec
NSString *bookDescription = [NSString stringWithFormat:@"%@ by %@ was published in %@", bookTitle, bookAuthor, bookPublicationYear];
```
{% endcode %}
2023-12-31 00:07:27 +00:00
Ou você também poderia usar uma classe de string **mutável** :
2023-05-09 00:02:08 +00:00
{% code overflow="wrap" %}
```objectivec
NSMutableString *mutableString = [NSMutableString stringWithString:@"The book "];
[mutableString appendString:bookTitle];
[mutableString appendString:@" was written by "];
[mutableString appendString:bookAuthor];
[mutableString appendString:@" and published in "];
[mutableString appendString:bookPublicationYear];
```
2023-06-06 18:56:34 +00:00
#### Número
2023-05-09 00:02:08 +00:00
{% code overflow="wrap" %}
```objectivec
// character literals.
NSNumber *theLetterZ = @'Z'; // equivalent to [NSNumber numberWithChar:'Z']
// integral literals.
NSNumber *fortyTwo = @42 ; // equivalent to [NSNumber numberWithInt:42]
NSNumber *fortyTwoUnsigned = @42U ; // equivalent to [NSNumber numberWithUnsignedInt:42U]
NSNumber *fortyTwoLong = @42L ; // equivalent to [NSNumber numberWithLong:42L]
NSNumber *fortyTwoLongLong = @42LL ; // equivalent to [NSNumber numberWithLongLong:42LL]
// floating point literals.
NSNumber *piFloat = @3 .141592654F; // equivalent to [NSNumber numberWithFloat:3.141592654F]
NSNumber *piDouble = @3 .1415926535; // equivalent to [NSNumber numberWithDouble:3.1415926535]
// BOOL literals.
NSNumber *yesNumber = @YES ; // equivalent to [NSNumber numberWithBool:YES]
NSNumber *noNumber = @NO ; // equivalent to [NSNumber numberWithBool:NO]
```
2023-12-31 00:07:27 +00:00
#### Array, Sets & Dictionary
2023-05-09 00:02:08 +00:00
{% code overflow="wrap" %}
```objectivec
// Inmutable arrays
NSArray *colorsArray1 = [NSArray arrayWithObjects:@"red", @"green", @"blue", nil];
NSArray *colorsArray2 = @[@"yellow", @"cyan", @"magenta"];
NSArray *colorsArray3 = @[firstColor, secondColor, thirdColor];
// Mutable arrays
NSMutableArray *mutColorsArray = [NSMutableArray array];
[mutColorsArray addObject:@"red"];
[mutColorsArray addObject:@"green"];
[mutColorsArray addObject:@"blue"];
[mutColorsArray addObject:@"yellow"];
[mutColorsArray replaceObjectAtIndex:0 withObject:@"purple"];
2023-09-11 15:59:11 +00:00
// Inmutable Sets
2023-05-09 00:02:08 +00:00
NSSet *fruitsSet1 = [NSSet setWithObjects:@"apple", @"banana", @"orange", nil];
NSSet *fruitsSet2 = [NSSet setWithArray:@[@"apple", @"banana", @"orange"]];
2023-09-11 15:59:11 +00:00
// Mutable sets
2023-05-09 00:02:08 +00:00
NSMutableSet *mutFruitsSet = [NSMutableSet setWithObjects:@"apple", @"banana", @"orange", nil];
[mutFruitsSet addObject:@"grape"];
[mutFruitsSet removeObject:@"apple"];
// Dictionary
NSDictionary *fruitColorsDictionary = @{
2023-09-11 15:59:11 +00:00
@"apple" : @"red",
@"banana" : @"yellow",
@"orange" : @"orange",
@"grape" : @"purple"
2023-05-09 00:02:08 +00:00
};
// In dictionaryWithObjectsAndKeys you specify the value and then the key:
NSDictionary *fruitColorsDictionary2 = [NSDictionary dictionaryWithObjectsAndKeys:
2023-09-11 15:59:11 +00:00
@"red", @"apple",
@"yellow", @"banana",
@"orange", @"orange",
@"purple", @"grape",
2023-05-09 00:02:08 +00:00
nil];
// Mutable dictionary
NSMutableDictionary *mutFruitColorsDictionary = [NSMutableDictionary dictionaryWithDictionary:fruitColorsDictionary];
[mutFruitColorsDictionary setObject:@"green" forKey:@"apple"];
[mutFruitColorsDictionary removeObjectForKey:@"grape"];
```
2023-06-06 18:56:34 +00:00
### Blocos
2023-05-09 13:53:58 +00:00
2023-12-31 00:07:27 +00:00
Blocos são **funções que se comportam como objetos** para que possam ser passados para funções ou **armazenados** em **arrays** ou **dicionários** . Além disso, eles podem **representar um valor se lhes forem atribuídos valores** , então é semelhante a lambdas.
2023-05-09 13:53:58 +00:00
{% code overflow="wrap" %}
```objectivec
returnType (^blockName)(argumentType1, argumentType2, ...) = ^(argumentType1 param1, argumentType2 param2, ...){
2023-09-11 15:59:11 +00:00
//Perform operations here
2023-05-09 13:53:58 +00:00
};
// For example
2023-09-11 15:59:11 +00:00
int (^suma)(int, int) = ^(int a, int b){
return a+b;
2023-05-09 13:53:58 +00:00
};
NSLog(@"3+4 = %d", suma(3,4));
```
{% endcode %}
2023-06-06 18:56:34 +00:00
Também é possível **definir um tipo de bloco para ser usado como parâmetro** em funções:
2023-05-09 13:53:58 +00:00
```objectivec
// Define the block type
typedef void (^callbackLogger)(void);
// Create a bloack with the block type
2023-09-11 15:59:11 +00:00
callbackLogger myLogger = ^{
NSLog(@"%@", @"This is my block");
2023-05-09 13:53:58 +00:00
};
// Use it inside a function as a param
void genericLogger(callbackLogger blockParam) {
2023-09-11 15:59:11 +00:00
NSLog(@"%@", @"This is my function");
blockParam();
2023-05-09 13:53:58 +00:00
}
genericLogger(myLogger);
// Call it inline
genericLogger(^{
2023-09-11 15:59:11 +00:00
NSLog(@"%@", @"This is my second block");
2023-05-09 13:53:58 +00:00
});
```
2023-06-06 18:56:34 +00:00
### Arquivos
2023-05-09 13:53:58 +00:00
{% code overflow="wrap" %}
```objectivec
// Manager to manage files
NSFileManager *fileManager = [NSFileManager defaultManager];
// Check if file exists:
if ([fileManager fileExistsAtPath:@"/path/to/file.txt" ] == YES) {
2023-09-11 15:59:11 +00:00
NSLog (@"File exists");
2023-05-09 13:53:58 +00:00
}
// copy files
if ([fileManager copyItemAtPath: @"/path/to/file1.txt" toPath: @"/path/to/file2.txt" error:nil] == YES) {
2023-09-11 15:59:11 +00:00
NSLog (@"Copy successful");
2023-05-09 13:53:58 +00:00
}
// Check if the content of 2 files match
if ([fileManager contentsEqualAtPath:@"/path/to/file1.txt" andPath:@"/path/to/file2.txt"] == YES) {
2023-09-11 15:59:11 +00:00
NSLog (@"File contents match");
2023-05-09 13:53:58 +00:00
}
// Delete file
if ([fileManager removeItemAtPath:@"/path/to/file1.txt" error:nil]) {
2023-09-11 15:59:11 +00:00
NSLog(@"Removed successfully");
2023-05-09 13:53:58 +00:00
}
```
{% endcode %}
2023-06-06 18:56:34 +00:00
Também é possível gerenciar arquivos **usando objetos `NSURL` em vez de objetos `NSString`** . Os nomes dos métodos são semelhantes, mas **com `URL` em vez de `Path`** .
2023-05-09 13:53:58 +00:00
```objectivec
NSURL *fileSrc = [NSURL fileURLWithPath:@"/path/to/file1.txt"];
NSURL *fileDst = [NSURL fileURLWithPath:@"/path/to/file2.txt"];
[fileManager moveItemAtURL:fileSrc toURL:fileDst error: nil];
```
2023-12-31 00:07:27 +00:00
A maioria das classes básicas possui um método `writeToFile:<path> atomically:<YES> encoding:<encoding> error:nil` definido que permite que elas sejam diretamente escritas em um arquivo:
2023-05-09 13:53:58 +00:00
{% code overflow="wrap" %}
```objectivec
NSString* tmp = @"something temporary";
[tmp writeToFile:@"/tmp/tmp1.txt" atomically:YES encoding:NSASCIIStringEncoding error:nil];
```
2023-12-31 00:07:27 +00:00
```markdown
2023-05-09 13:53:58 +00:00
{% endcode %}
2023-05-08 22:07:46 +00:00
< details >
2023-12-31 00:07:27 +00:00
< summary > < strong > Aprenda hacking no AWS do zero ao herói com< / strong > < a href = "https://training.hacktricks.xyz/courses/arte" > < strong > htARTE (HackTricks AWS Red Team Expert)< / strong > < / a > < strong > !< / strong > < / summary >
Outras formas de apoiar o HackTricks:
2023-05-08 22:07:46 +00:00
2023-12-31 00:07:27 +00:00
* Se você quer ver sua **empresa anunciada no HackTricks** ou **baixar o HackTricks em PDF** , confira os [**PLANOS DE ASSINATURA** ](https://github.com/sponsors/carlospolop )!
* Adquira o [**material oficial PEASS & HackTricks** ](https://peass.creator-spring.com )
* Descubra [**A Família PEASS** ](https://opensea.io/collection/the-peass-family ), nossa coleção de [**NFTs** ](https://opensea.io/collection/the-peass-family ) exclusivos
* **Junte-se ao grupo** 💬 [**Discord** ](https://discord.gg/hRep4RUj7f ) ou ao grupo [**telegram** ](https://t.me/peass ) ou **siga-me** no **Twitter** 🐦 [**@carlospolopm** ](https://twitter.com/carlospolopm )**.**
* **Compartilhe suas técnicas de hacking enviando PRs para os repositórios github do** [**HackTricks** ](https://github.com/carlospolop/hacktricks ) e [**HackTricks Cloud** ](https://github.com/carlospolop/hacktricks-cloud ).
2023-05-08 22:07:46 +00:00
< / details >
2023-12-31 00:07:27 +00:00
```